diff --git a/CHANGELOG.md b/CHANGELOG.md index d957bb9..ca690b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,19 @@ Repository and `curl | sh` installs only; the PyPI package is unaffected. change to `master` was 11 December 2019, not January 2021, which was two README image URL edits. +## Unreleased + +**Fixed** + +- Pasting indented text produced a staircase, each line indented further + than the last. A paste arrives as ordinary keystrokes, so auto indent + fired on every newline and prepended the previous line's whitespace to + a line that already carried its own, compounding down the block. + Suplemon now turns on the terminal's bracketed paste mode, which wraps + a paste in markers so it can be told apart from typing, and inserts it + literally: no auto indent, and tabs stay tabs instead of being + expanded. Terminals without bracketed paste behave as before. + ## [v0.3.3](https://github.com/leancode/suplemon/tree/0.3.3) (2026-09-03) **Fixed** diff --git a/suplemon/editor.py b/suplemon/editor.py index d754289..3c21d42 100644 --- a/suplemon/editor.py +++ b/suplemon/editor.py @@ -56,6 +56,9 @@ def __init__(self, app, window): self.current_state = 0 # Last editor action that was used (for undo/redo) self.last_action = None + # True while a bracketed paste is being inserted. Auto indent + # and per-keystroke undo states are both wrong during one. + self.pasting = False def init(self): Viewer.init(self) @@ -109,6 +112,10 @@ def set_data(self, data): def store_action_state(self, action, state=None): """Store the editor state if a new action is taken.""" + if self.pasting: + # The whole paste is one action. Its state was stored before + # insertion began, so undo puts back what was there before. + return if self.last_action != action: self.last_action = action self.store_state(state) @@ -364,7 +371,7 @@ def enter(self): # Leave the beginning of the line self.lines[cursor.y].set_data(start) wspace = "" - if self.config["auto_indent_newline"]: + if self.config["auto_indent_newline"] and not self.pasting: wspace = helpers.leading_whitespace(self.lines[cursor.y]) self.lines.insert(cursor.y+1, Line(wspace+end)) self.move_y_cursors(cursor.y, 1) @@ -531,6 +538,32 @@ def type(self, data): # Add a restore point if previous action != type self.store_action_state("type") + def insert_text(self, text): + """Insert pasted text literally, without auto indent. + + A paste arrives as ordinary keystrokes, so auto indent fires on + every newline and prepends the previous line's whitespace to a line + that already carries its own. Over a block of text that compounds + line by line into a staircase. The terminal tells us where a paste + starts and ends, so suppress it for the duration. + + :param str text: Text to insert at the cursor(s). + """ + text = text.replace("\r\n", "\n").replace("\r", "\n") + self.pasting = True + try: + for i, line in enumerate(text.split("\n")): + if i: + self.enter() + if line: + self.type(line) + finally: + self.pasting = False + # Stored once, after the insertion, the same way type() and enter() + # do it. The flag kept the per-keystroke stores from piling up, so + # one undo steps over the whole paste rather than part of it. + self.store_action_state("paste") + def type_at_cursor(self, cursor, data): """Insert data at specified cursor.""" line = self.lines[cursor.y] diff --git a/suplemon/main.py b/suplemon/main.py index 9590544..b3bc883 100644 --- a/suplemon/main.py +++ b/suplemon/main.py @@ -314,8 +314,22 @@ def handle_input(self, event): return self.handle_key(event) elif event.type == "mouse": return self.handle_mouse(event) + elif event.type == "paste": + return self.handle_paste(event) return False + def handle_paste(self, event): + """Insert text the terminal reported as a paste. + + :param event: Event instance carrying the text in .data. + :return: Boolean indicating if the event was handled. + :rtype: boolean + """ + if not event.data: + return False + self.get_editor().insert_text(event.data) + return True + def handle_key(self, event): """Handle a key input event. diff --git a/suplemon/ui.py b/suplemon/ui.py index 264f8af..1d5330c 100644 --- a/suplemon/ui.py +++ b/suplemon/ui.py @@ -4,6 +4,7 @@ """ import os +import sys import logging from wcwidth import wcswidth @@ -15,6 +16,13 @@ curses = None +# What the terminal wraps a paste in when bracketed paste mode is on. +# curses has no terminfo entry for these, so they arrive as plain +# characters and have to be recognised here. +PASTE_START = "\x1b[200~" +PASTE_END = "\x1b[201~" + + class InputEvent: """Represents a keyboard or mouse event.""" def __init__(self): @@ -24,6 +32,7 @@ def __init__(self): self.is_typeable = False self.curses_key_name = None self.mouse_code = None + self.data = None # Pasted text, for events of type 'paste' self.mouse_pos = (0, 0) self.logger = logging.getLogger("{0}.InputEvent".format(__name__)) @@ -39,6 +48,12 @@ def set_key_name(self, name): self.type = "key" self.key_name = name + def set_paste_data(self, data): + """Turn this into a paste event carrying the pasted text.""" + self.type = "paste" + self.data = data + return self + def parse_mouse_state(self, state): """Parse curses mouse events.""" self.type = "mouse" @@ -166,15 +181,35 @@ def load(self, *args): self.current_yx = self.screen.getmaxyx() # For checking resize self.setup_mouse() + self.setup_bracketed_paste(True) self.setup_windows() + def setup_bracketed_paste(self, enable): + """Turn the terminal's bracketed paste mode on or off. + + With it on, a paste arrives wrapped in ESC[200~ and ESC[201~ so it + can be told apart from typing. Terminals that don't support it + ignore the sequence and nothing changes. + + :param bool enable: True to turn it on, False to turn it off. + """ + try: + sys.stdout.write("\033[?2004h" if enable else "\033[?2004l") + sys.stdout.flush() + except (OSError, ValueError): + # Not fatal: without it, pastes are simply indistinguishable + # from typing, which is how it behaved before. + self.logger.debug("Could not set bracketed paste mode.") + def unload(self): """Unload curses.""" + # Leave the terminal as we found it. Without this the shell keeps + # receiving paste markers after suplemon exits. + self.setup_bracketed_paste(False) # Don't call curses.endwin() here. self.run() drives the app via # curses.wrapper(), which always calls endwin() itself when it # returns. Ending the screen twice makes modern ncurses return ERR, # which Python raises as _curses.error on exit. - pass def setup_mouse(self): # Mouse support @@ -623,11 +658,73 @@ def get_input(self, blocking=True): if state: event.parse_mouse_state(state) return event + elif char == "\x1b" and self.match_sequence(PASTE_START[1:]): + return event.set_paste_data(self.read_paste()) else: event.parse_key_code(char) return event return False + def match_sequence(self, rest): + """Check whether the characters after ESC are `rest`. + + Reads without blocking and pushes back anything that does not + match, so an ESC that starts something else, or a lone ESC key + press, is handed on untouched. + + :param str rest: Expected characters following the escape. + :return: True if they were consumed, False if pushed back. + :rtype: boolean + """ + seen = "" + self.screen.nodelay(1) + try: + for expected in rest: + try: + c = self.screen.get_wch() + except (curses.error, KeyboardInterrupt): + c = None + if c != expected: + if c is not None: + seen += str(c) + for ch in reversed(seen): + try: + curses.unget_wch(ch) + except (curses.error, TypeError): + pass + return False + seen += str(c) + finally: + self.screen.nodelay(0) + return True + + def read_paste(self): + """Read a paste up to the closing marker and return its text. + + :return: The pasted text, without the markers. + :rtype: str + """ + data = [] + while True: + try: + c = self.screen.get_wch() + except KeyboardInterrupt: + break + except curses.error: + break + if c == "\x1b": + if self.match_sequence(PASTE_END[1:]): + break + # An ESC inside the payload is content, not a marker. + data.append(c) + continue + if isinstance(c, int): + # A translated key code cannot appear in pasted text; + # ignore rather than corrupt the payload with a number. + continue + data.append(c) + return "".join(data) + def is_mouse(self, key): """Check for mouse events""" return key == curses.KEY_MOUSE