From 055d73814234d82ebd40c410f53b8edb4fc1ce56 Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Fri, 28 Aug 2020 20:49:14 -0700 Subject: [PATCH] Fix out of bounds on uncomment --- babi/file.py | 7 ++++++- tests/features/comment_test.py | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/babi/file.py b/babi/file.py index 21ea376..6b37f87 100644 --- a/babi/file.py +++ b/babi/file.py @@ -681,13 +681,18 @@ class File: rest_offset = ws_len + len(prefix) if line.startswith(prefix, ws_len): self.buf[lineno] = f'{ws_match[0]}{line[rest_offset:].lstrip()}' + if self.buf.y == lineno and self.buf.x > ws_len: + self.buf.x -= len(line) - len(self.buf[lineno]) def _comment_add(self, lineno: int, prefix: str) -> None: + prefix = f'{prefix} ' line = self.buf[lineno] ws_match = WS_RE.match(line) assert ws_match is not None ws_len = len(ws_match[0]) - self.buf[lineno] = f'{ws_match[0]}{prefix} {line[ws_len:]}' + self.buf[lineno] = f'{ws_match[0]}{prefix}{line[ws_len:]}' + if lineno == self.buf.y: + self.buf.x += len(prefix) @edit_action('comment', final=True) def toggle_comment(self, prefix: str) -> None: diff --git a/tests/features/comment_test.py b/tests/features/comment_test.py index 4ea64f2..1d5c192 100644 --- a/tests/features/comment_test.py +++ b/tests/features/comment_test.py @@ -73,3 +73,27 @@ def test_comment_with_trailing_whitespace(run, ten_lines): h.press_and_enter(':comment // ') h.await_text('// line_0\nline_1\n') + + +def test_comment_cursor_at_end_of_line(run, ten_lines): + with run(str(ten_lines)) as h, and_exit(h): + h.press('# ') + h.press('End') + h.await_cursor_position(x=8, y=1) + + trigger_command_mode(h) + h.press_and_enter(':comment') + + h.await_cursor_position(x=6, y=1) + + +def test_add_comment_moves_cursor(run, ten_lines): + with run(str(ten_lines)) as h, and_exit(h): + h.press('End') + + h.await_cursor_position(x=6, y=1) + + trigger_command_mode(h) + h.press_and_enter(':comment') + + h.await_cursor_position(x=8, y=1)