fix the way tabs are used

The previous code just assumed a tab was 4 spaces wide.
This is not true, because a tab can be between 1 and 4 spaces wide.
This commit is contained in:
2021-12-20 19:44:46 +01:00
parent 3c27913e75
commit ffea831e2d
4 changed files with 75 additions and 20 deletions

33
line.py
View File

@@ -16,9 +16,12 @@ class Line:
def line(self) -> str:
return self._line
def length(self) -> int:
def length_in_charaters(self) -> int:
return len(self._line)
def length_in_columns(self) -> int:
return self.char_to_column(len(self._line))
def char_index_to_byte(self, char_in_line: int) -> int:
return len(self.prefix(char_in_line).encode("utf8"))
@@ -27,26 +30,46 @@ class Line:
prefix_chars = prefix_bytes.decode("utf8", errors="ignore")
return len(prefix_chars)
def line_tabs_replaced(self):
line = self._line;
i = 0
offset = 0
result = ""
length = len(line)
while True:
tab_index = line.find("\t", offset)
if tab_index < 0:
break
result = result + line[offset:tab_index]
result = result + " " * (constants.tab_width - len(result) % constants.tab_width)
offset = tab_index + 1
result = result + line[offset:]
return result
def column_to_char(self, column_in_line: int) -> int:
i = 0
result = 0
while i < column_in_line:
char = self._line[result]
if char == "\t":
i = i + constants.tab_width - 1 # jump the additional 7 columns of the tab width
if i >= column_in_line:
i = i + constants.tab_width - i % constants.tab_width # jump the additional columns to complete the tab
if i > column_in_line:
break;
i = i + 1
else:
i = i + 1
result = result + 1
return result
# todo this method is slow
def char_to_column(self, char_in_line: int) -> int:
result = 0
i = 0
while i < char_in_line:
if i < len(self._line) and self._line[i] == "\t":
result = result + constants.tab_width
result = result + constants.tab_width - result % constants.tab_width
else:
result = result + 1
i = i + 1