Skip to content

Commit

Permalink
Merge pull request #233 from asottile/reload-bug
Browse files Browse the repository at this point in the history
fix reload replacing lines with different sized lines
  • Loading branch information
asottile authored Apr 8, 2022
2 parents cafd4b2 + f4e263b commit 37934ee
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
21 changes: 17 additions & 4 deletions babi/buf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@
InsCallback = Callable[['Buf', int], None]


def _diff_codes(
a: list[str],
b: list[str],
) -> Generator[tuple[str, int, int, int, int], None, None]:
matcher = difflib.SequenceMatcher(a=a, b=b)
for op, i1, i2, j1, j2 in reversed(matcher.get_opcodes()):
if op == 'replace':
if i2 - i1 == j2 - j1:
yield op, i1, i2, j1, j2
else:
yield 'delete', i1, i2, j1, j2
yield 'insert', i1, i1, j1, j2
elif op != 'equal':
yield op, i1, i2, j1, j2


def _offsets(s: str, tab_size: int) -> tuple[int, ...]:
ret = [0]
for c in s:
Expand Down Expand Up @@ -135,8 +151,7 @@ def pop(self, idx: int = -1) -> str:
return victim

def replace_lines(self, lines: list[str]) -> None:
matcher = difflib.SequenceMatcher(a=self._lines, b=lines)
for op, i1, i2, j1, j2 in reversed(matcher.get_opcodes()):
for op, i1, i2, j1, j2 in _diff_codes(self._lines, lines):
if op == 'replace':
for i, j in zip(range(i1, i2), range(j1, j2)):
self[i] = lines[j]
Expand All @@ -146,8 +161,6 @@ def replace_lines(self, lines: list[str]) -> None:
elif op == 'insert':
for j in reversed(range(j1, j2)):
self.insert(i1, lines[j])
elif op == 'equal':
pass
else:
raise AssertionError(f'{op} {self._lines} {lines} ???')

Expand Down
1 change: 1 addition & 0 deletions tests/buf_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ def test_buf_pop_idx():
'new_lines',
(
pytest.param(['d', 'b', 'c'], id='replace op'),
pytest.param(['a', 'q', 'q', 'c'], id='replace different size'),
pytest.param(['c'], id='delete op'),
pytest.param(['a', 'q', 'q', 'q', 'b', 'c'], id='insert op'),
),
Expand Down

0 comments on commit 37934ee

Please sign in to comment.