Skip to content

Commit 626f8ee

Browse files
committed
Calculate frompos and topos Match attributes if needed.
1 parent fd028ce commit 626f8ee

1 file changed

Lines changed: 34 additions & 6 deletions

File tree

‎language_tool/__init__.py‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,29 +79,57 @@ class Match:
7979
"ruleId", "subId", "msg", "replacements",
8080
"context", "contextoffset", "errorlength")
8181

82-
def __init__(self, attrib, language=None):
82+
def __init__(self, attrib, text=None):
8383
for k, v in attrib.items():
8484
setattr(self, k, int(v) if v.isdigit() else v)
8585
if not isinstance(self.replacements, list):
8686
self.replacements = (self.replacements.split("#")
8787
if self.replacements else [])
8888

89+
# Need to calculate `frompos` and `topos` attributes
90+
# if using unpatched LanguageTool server.
91+
self._lines = text
92+
self._frompos_cache, self._topos_cache = None, None
93+
8994
def __repr__(self):
9095
def _ordered_dict_repr():
96+
attrs = (self._SLOTS +
97+
tuple(set(self.__dict__).difference(self._SLOTS)))
9198
return "{{{}}}".format(
9299
", ".join(
93-
"{!r}: {!r}".format(k, self.__dict__[k])
94-
for k in self._SLOTS +
95-
tuple(set(self.__dict__).difference(self._SLOTS))
96-
if getattr(self, k) is not None
100+
"{!r}: {!r}".format(attr, self.__dict__[attr])
101+
for attr in attrs
102+
if attr in self.__dict__ and not attr.startswith("_")
97103
)
98104
)
99105

100106
return "{}({})".format(self.__class__.__name__, _ordered_dict_repr())
101107

102108
def __getattr__(self, name):
109+
if name == "frompos":
110+
return self._frompos
111+
elif name == "topos":
112+
return self._topos
103113
return None
104114

115+
@property
116+
def _frompos(self):
117+
if self._frompos_cache is None:
118+
self._frompos_cache = self._get_pos(self.fromy, self.fromx)
119+
return self._frompos_cache
120+
121+
@property
122+
def _topos(self):
123+
if self._topos_cache is None:
124+
self._topos_cache = self._get_pos(self.toy, self.tox)
125+
return self._topos_cache
126+
127+
def _get_pos(self, y, x):
128+
if not isinstance(self._lines, list):
129+
self._lines = self._lines.split("\n")
130+
prev_lines = self._lines[:y]
131+
return sum([len(line) for line in prev_lines]) + len(prev_lines) + x
132+
105133

106134
class LanguageTool:
107135
"""Main class used for checking text against different rules
@@ -179,7 +207,7 @@ def check(self, text: str, srctext=None) -> [Match]:
179207
params["disabled"] = ",".join(self.disabled)
180208
data = urllib.parse.urlencode(params).encode()
181209
root = self._get_root(self.url, data)
182-
return [Match(e.attrib, self.language) for e in root]
210+
return [Match(e.attrib, text) for e in root]
183211

184212
def correct(self, text: str, srctext=None) -> str:
185213
"""Automatically apply suggestions to the text.

0 commit comments

Comments
 (0)