From fa19f99d27744e39a8ad6fc89e089149c85566d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9ophile=20Bastian?= Date: Sat, 9 May 2020 19:35:59 +0200 Subject: [PATCH] Vim session: better movement tracking --- patch2vimedit/vim_session.py | 58 ++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 6 deletions(-) diff --git a/patch2vimedit/vim_session.py b/patch2vimedit/vim_session.py index f535752..207e967 100644 --- a/patch2vimedit/vim_session.py +++ b/patch2vimedit/vim_session.py @@ -1,6 +1,32 @@ import sys +class LineMovement: + """ A movement to a given line, absolute or relative """ + + def __init__(self, absolute=None, relative=None): + self.absolute = absolute + self.relative = relative + if self.absolute and self.relative: + raise Exception("Cannot move both absolutely and relatively") + + def __add__(self, num): + if not isinstance(num, type(0)): + raise Exception("Can only add an integer") + if self.absolute is not None: + return self.__class__(absolute=self.absolute + num) + if self.relative is not None: + return self.__class__(relative=self.relative + num) + + def do(self, tmux_session): + if self.relative: + tmux_session.type_keys("escape", "{}j".format(self.relative)) + elif self.absolute: + tmux_session.type_keys("escape", "{}G".format(self.absolute)) + self.relative = 0 + self.absolute = None + + class VimSession: """ A Vim session instrumented through tmux """ @@ -38,17 +64,37 @@ class VimSession: self.tmux_session.type_keys("escape", ":w", "enter") + def write_line(self, line): + """ Write a line to the vim buffer, assuming everything is set up for it and it + must be insterted above. """ + + if line.startswith(" "): + lead_spaces = 0 + while lead_spaces < len(line) and line[lead_spaces] == " ": + lead_spaces += 1 + line = line.strip() + + self.tmux_session.type_keys( + "O", "escape", "{}a ".format(lead_spaces), "escape", "A", line, "escape" + ) + else: + self.tmux_session.type_keys("O", line, "escape") + def apply_hunk(self, hunk): # So far, very naive. - self.tmux_session.type_keys("escape", "{}G0".format(hunk.starttgt)) + line_mvt = LineMovement(absolute=hunk.starttgt) + for b_line in hunk.text: line = b_line.decode("utf8") if line[0] == " ": - self.tmux_session.type_keys("j") - elif line[0] == "-": - self.tmux_session.type_keys("dd") - elif line[0] == "+": - self.tmux_session.type_keys("O", line.strip()[1:], "escape", "j") + line_mvt += 1 + else: + line_mvt.do(self.tmux_session) + if line[0] == "-": + self.tmux_session.type_keys("dd") + elif line[0] == "+": + self.write_line(line.strip()[1:]) + line_mvt += 1 def quit(self): self.tmux_session.type_keys("escape", ":q", "enter")