home · contact · privacy
Add prompt history.
authorChristian Heller <c.heller@plomlompom.de>
Mon, 2 Jun 2025 13:15:49 +0000 (15:15 +0200)
committerChristian Heller <c.heller@plomlompom.de>
Mon, 2 Jun 2025 13:15:49 +0000 (15:15 +0200)
ircplom.py

index c13de196b1e8590f6d36132e6681f9fa8ba5b8f1..c7049bc93535122d868b3ff8269026c80c69deb6 100755 (executable)
@@ -25,8 +25,10 @@ INPUT_PROMPT = '> '
 KEYBINDINGS = {
     'KEY_BACKSPACE': ('prompt_backspace',),
     'KEY_ENTER': ('prompt_enter',),
-    'KEY_PGUP': ('scroll', 'up'),
-    'KEY_PGDOWN': ('scroll', 'down'),
+    'KEY_UP': ('prompt_scroll', 'up'),
+    'KEY_DOWN': ('prompt_scroll', 'down'),
+    'KEY_PGUP': ('log_scroll', 'up'),
+    'KEY_PGDOWN': ('log_scroll', 'down'),
 }
 
 IRCSPEC_LINE_SEPARATOR = b'\r\n'
@@ -442,15 +444,19 @@ class TuiPrompt:
     def __init__(self, term: Terminal) -> None:
         self._term = term
         self._buffer = ''
+        self._history: list[str] = []
+        self._history_idx = 0
 
     def append(self, char: str) -> None:
         'Append char to current content.'
         self._buffer += char
+        self._history_idx = 0
         self.draw()
 
     def backspace(self) -> None:
         'Truncate current content by one character, if possible.'
         self._buffer = self._buffer[:-1]
+        self._history_idx = 0
         self.draw()
 
     def clear(self) -> None:
@@ -466,10 +472,30 @@ class TuiPrompt:
     def enter(self) -> str:
         'Return current content while also clearing and then redrawing.'
         to_return = self._buffer[:]
-        self.clear()
-        self.draw()
+        if to_return:
+            self._history += [to_return]
+            self.clear()
+            self.draw()
         return to_return
 
+    def scroll(self, up=True) -> None:
+        'Scroll through past prompt inputs.'
+        if up and -(self._history_idx) < len(self._history):
+            if self._history_idx == 0 and self._buffer:
+                self._history += [self._buffer[:]]
+                self.clear()
+                self._history_idx -= 1
+            self._history_idx -= 1
+        elif (not up) and self._history_idx < 0:
+            self._history_idx += 1
+            if self._history_idx == 0:
+                self.clear()
+                return
+        else:
+            return
+        self._buffer = self._history[self._history_idx][:]
+        self.draw()
+
 
 class TuiLoop(Loop):
     'Loop for drawing/updating TUI.'
@@ -562,7 +588,10 @@ class TuiLoop(Loop):
         if alert:
             self.broadcast('ALERT', f'invalid prompt command: {alert}')
 
-    def _cmd__scroll(self, direction: str) -> None:
+    def _cmd__prompt_scroll(self, direction: str) -> None:
+        self._prompt.scroll(up=direction == 'up')
+
+    def _cmd__log_scroll(self, direction: str) -> None:
         self._log.scroll(up=direction == 'up')
         self._log.draw()