zhist 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,143 @@
1
+ .TH ZHIST 1 "November 2026" "zhist 0.1" "User Commands"
2
+ .SH NAME
3
+ zhist \- interactive terminal browser for shell history
4
+ .SH SYNOPSIS
5
+ .B zhist
6
+ [\fB--histfile\fR \fIFILE\fR] [\fB--version\fR]
7
+ .SH DESCRIPTION
8
+ .B zhist
9
+ opens a terminal interface for searching and sorting shell history entries.
10
+ Select an entry to edit it and run the edited command, or delete an entry
11
+ from the history file.
12
+ .PP
13
+ Commands are filtered as you type using a case-insensitive substring match.
14
+ The available sort orders are Recent, Oldest, Frequency, and A-Z. Zsh
15
+ extended-history timestamps are hidden in the list.
16
+ .SH OPTIONS
17
+ .TP
18
+ .BI "--histfile " FILE
19
+ Read and update
20
+ .IR FILE .
21
+ A leading tilde is expanded. If this option is omitted, the history file is
22
+ selected from the
23
+ .B HISTFILE
24
+ environment variable, then from the shell default described below.
25
+ .TP
26
+ .B -h, --help
27
+ Show command-line help and exit.
28
+ .TP
29
+ .B --version
30
+ Show the version number and exit.
31
+ .SH INSTALLATION
32
+ Install the executable as
33
+ .I /usr/local/bin/zhist
34
+ and the manual page as
35
+ .IR /usr/local/share/man/man1/zhist.1 .
36
+ After installing or updating the manual page, refresh the manual page database
37
+ with
38
+ .BR "sudo mandb" .
39
+ On z/OS USS, install the zopen
40
+ .B man-db
41
+ package before running
42
+ .BR mandb ;
43
+ it provides that command. If installing into a zopen environment, place the
44
+ page in its man1 directory and run
45
+ .B mandb
46
+ from that environment.
47
+ The page can then be viewed with
48
+ .BR "man zhist" .
49
+ .SH HISTORY FILE
50
+ When
51
+ .B --histfile
52
+ and
53
+ .B HISTFILE
54
+ are both unset, zhist uses
55
+ .I ~/.zsh_history
56
+ if the
57
+ .B SHELL
58
+ environment variable contains
59
+ .BR zsh ;
60
+ otherwise it uses
61
+ .IR ~/.bash_history .
62
+ The file is read as UTF-8, replacing invalid byte sequences. If the selected
63
+ file does not exist, zhist starts with an empty history.
64
+ .PP
65
+ Deleting an entry writes the updated history directly to the selected file.
66
+ In Frequency sort, deletion removes all entries with that command. No backup
67
+ is created.
68
+ .SH INTERACTIVE CONTROLS
69
+ .SS History list
70
+ .TP
71
+ .B Up / Down
72
+ Move the selection.
73
+ .TP
74
+ .B Page Up / Page Down
75
+ Move the selection by one screen.
76
+ .TP
77
+ .B Type
78
+ Append characters to the search filter.
79
+ .TP
80
+ .B Backspace
81
+ Remove the last character from the filter.
82
+ .TP
83
+ .B Ctrl+U
84
+ Clear the filter.
85
+ .TP
86
+ .B Ctrl+O / F2
87
+ Cycle through Recent, Oldest, Frequency, and A-Z sorting.
88
+ .TP
89
+ .B F1
90
+ Show the interactive help screen. Use Up/Down or Page Up/Page Down to scroll;
91
+ press F1, Esc, or Enter to close it.
92
+ .TP
93
+ .B Enter
94
+ Open the selected command in the editor.
95
+ .TP
96
+ .B Delete / Ctrl+D
97
+ Delete the selected history entry (or all matching entries in Frequency sort).
98
+ .TP
99
+ .B Esc / Ctrl+C
100
+ Quit.
101
+ .SS Command editor
102
+ .TP
103
+ .B Left / Right
104
+ Move the cursor.
105
+ .TP
106
+ .B Home / Ctrl+A
107
+ Move to the beginning of the command.
108
+ .TP
109
+ .B End / Ctrl+E
110
+ Move to the end of the command.
111
+ .TP
112
+ .B Backspace / Delete
113
+ Delete a character before or at the cursor.
114
+ .TP
115
+ .B Ctrl+U
116
+ Clear the command before the cursor.
117
+ .TP
118
+ .B Ctrl+K
119
+ Clear the command after the cursor.
120
+ .TP
121
+ .B Enter
122
+ Run the edited command.
123
+ .TP
124
+ .B Esc / Ctrl+C
125
+ Return to the history list without running it.
126
+ .SH COMMAND EXECUTION
127
+ An edited command is executed through the shell named by the
128
+ .B SHELL
129
+ environment variable. If
130
+ .B SHELL
131
+ is unset, zhist uses
132
+ .BR /bin/bash .
133
+ Review commands before running them.
134
+ .SH REQUIREMENTS
135
+ Python 3, a terminal, and a Python build that provides the
136
+ .B curses
137
+ module are required. The script uses only the Python standard library.
138
+ .SH EXIT STATUS
139
+ When a command is run, zhist exits with that command's status. Otherwise, it
140
+ exits with status 0 after the interface closes.
141
+ .SH SEE ALSO
142
+ .BR bash (1),
143
+ .BR zsh (1)
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: zhist
3
+ Version: 0.1
4
+ Summary: Interactive terminal browser for shell history
5
+ Author-email: "Lionel B. Dyck" <lbdyck@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/lbdyck/zhist
8
+ Project-URL: Repository, https://github.com/lbdyck/zhist
9
+ Project-URL: Issues, https://github.com/lbdyck/zhist/issues
10
+ Keywords: bash,curses,history,shell,terminal,zsh
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Operating System :: POSIX
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: System :: Shells
23
+ Classifier: Topic :: Utilities
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Dynamic: license-file
28
+
29
+ # zhist
30
+
31
+ `zhist.py` is an interactive terminal interface for searching, sorting, editing,
32
+ running, and deleting commands in a shell history file.
33
+
34
+ Current version: **0.1**
35
+
36
+ ## Requirements
37
+
38
+ - Python 3
39
+ - A terminal and a Python build with the `curses` module (typically available
40
+ on Unix-like systems)
41
+
42
+ The script uses only Python's standard library.
43
+
44
+ See [zhist.1](zhist.1) for the manual page.
45
+
46
+ ## Installation
47
+
48
+ Install from PyPI:
49
+
50
+ ```sh
51
+ python3 -m pip install zhist
52
+ ```
53
+
54
+ Then run:
55
+
56
+ ```sh
57
+ zhist
58
+ ```
59
+
60
+ The manual page is installed with the package when supported by the
61
+ installation environment:
62
+
63
+ ```sh
64
+ man zhist
65
+ ```
66
+
67
+ ## Installation from source
68
+
69
+ From the project directory:
70
+
71
+ ```sh
72
+ python3 -m pip install .
73
+ ```
74
+
75
+ To install directly without pip:
76
+
77
+ ```sh
78
+ python3 install.py --prefix /usr/local
79
+ ```
80
+
81
+ The installer copies the executable to `bin/zhist` and the manual page to
82
+ `share/man/man1/zhist.1` under the prefix. The prefix must be absolute; it
83
+ defaults to `$PREFIX` or `/usr/local`.
84
+
85
+ On z/OS USS, the installer tags installed files as ISO8859-1 when `chtag` is
86
+ available. Install the zopen `man-db` package before running `mandb`; it
87
+ provides that command. If installing into a zopen environment, run `mandb`
88
+ from that environment to refresh its manual page database.
89
+
90
+ For manual installation on z/OS USS, ensure the executable is executable and
91
+ tagged as ISO8859-1:
92
+
93
+ ```sh
94
+ chmod 755 /usr/local/bin/zhist
95
+ chtag -tc ISO8859-1 /usr/local/bin/zhist
96
+ ```
97
+
98
+ The manual page belongs in `/usr/local/share/man/man1/` (section 1, user
99
+ commands). Run `mandb` after installing or updating it to refresh the manual
100
+ page database. Then use `zhist` to start the program and `man zhist` to read
101
+ its manual.
102
+
103
+ ## Usage
104
+
105
+ ```sh
106
+ python3 zhist.py
107
+ ```
108
+
109
+ After installation, run `zhist` instead. Use `zhist --version` to display the
110
+ installed version.
111
+
112
+ By default, the history file is selected in this order:
113
+
114
+ 1. The path passed with `--histfile`
115
+ 2. The `HISTFILE` environment variable
116
+ 3. `~/.zsh_history` when `SHELL` contains `zsh`; otherwise `~/.bash_history`
117
+
118
+ For example:
119
+
120
+ ```sh
121
+ python3 zhist.py --histfile ~/.zsh_history
122
+ ```
123
+
124
+ ## Controls
125
+
126
+ In the history list:
127
+
128
+ - **Up/Down** or **Page Up/Page Down**: move through matches
129
+ - **Type**: filter commands by a case-insensitive substring
130
+ - **Backspace**: remove the last filter character
131
+ - **Ctrl+U**: clear the filter
132
+ - **Ctrl+O** or **F2**: cycle through Recent, Oldest, Frequency, and A-Z sorting
133
+ - **F1**: open help; scroll with Up/Down or Page Up/Page Down, and close with
134
+ F1, Esc, or Enter
135
+ - **Enter**: edit the selected command, then press Enter to run it
136
+ - **Delete** or **Ctrl+D**: delete the selected history entry
137
+ - **Esc** or **Ctrl+C**: quit
138
+
139
+ The editor supports Left/Right, Home/Ctrl+A, End/Ctrl+E, Backspace, Delete,
140
+ Ctrl+U (clear before the cursor), and Ctrl+K (clear after the cursor). Press
141
+ Enter to execute the edited command, or Esc/Ctrl+C to return without running it.
142
+
143
+ ## Notes
144
+
145
+ - Deleting an entry writes the updated contents directly to the selected history
146
+ file. In Frequency sort, deleting a command removes all of its matching
147
+ entries.
148
+ - Running a command executes it through the shell specified by `SHELL`, or
149
+ `/bin/bash` if `SHELL` is unset. Review edited commands before running them.
150
+ - Zsh extended-history timestamps are hidden in the list and preserved when
151
+ saving entries that were not deleted.
152
+
153
+ ## License
154
+
155
+ This project is distributed under the [MIT License](LICENSE).
@@ -0,0 +1,8 @@
1
+ zhist.py,sha256=EPSYNbtTMGCv3jPMU58p81AlI2hOMFuNncA9TPmMoJg,14829
2
+ zhist-0.1.data/data/share/man/man1/zhist.1,sha256=JBVPE_UA-tVyWcSkF_Sr0kmc-OJUGOGjbIqVc64Ki5A,3578
3
+ zhist-0.1.dist-info/licenses/LICENSE,sha256=RGzUJ-lYwfDpApWCfTBNGfjd2j5U2TztAbGYkpwX7_k,1096
4
+ zhist-0.1.dist-info/METADATA,sha256=s0RlWApFXVIAMnsDGoEw0d0XTyDxTPu062ZQ4byV1JA,4694
5
+ zhist-0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ zhist-0.1.dist-info/entry_points.txt,sha256=65lkL2i_iFIJ6KxwX3_dGgPm48uYKpvC7yqqWrAIHdg,37
7
+ zhist-0.1.dist-info/top_level.txt,sha256=vZS_tlyiG8W-hIqEjUTAdlyUlaUv3PXQzzz9JRELix4,6
8
+ zhist-0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ zhist = zhist:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zhist contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ zhist
zhist.py ADDED
@@ -0,0 +1,450 @@
1
+ #!/usr/bin/env python3
2
+ "exec" "python3" "$0" "$@"
3
+ import argparse
4
+ import os
5
+ import re
6
+ import subprocess
7
+ import sys
8
+ from collections import Counter
9
+
10
+ __version__ = "0.1"
11
+
12
+ # Matches Zsh extended history format: ": 1700000000:0;command"
13
+ ZSH_EXT_RE = re.compile(r"^:\s*\d+:\d+;(.*)$")
14
+
15
+ SORT_MODES = [
16
+ ("Recent", "recent"),
17
+ ("Oldest", "oldest"),
18
+ ("Frequency", "freq"),
19
+ ("A-Z", "alpha"),
20
+ ]
21
+
22
+
23
+ def detect_histfile(cli_path=None):
24
+ if cli_path:
25
+ return os.path.expanduser(cli_path)
26
+ if os.environ.get("HISTFILE"):
27
+ return os.path.expanduser(os.environ["HISTFILE"])
28
+ shell = os.environ.get("SHELL", "")
29
+ if "zsh" in shell:
30
+ return os.path.expanduser("~/.zsh_history")
31
+ return os.path.expanduser("~/.bash_history")
32
+
33
+
34
+ def parse_line(raw_line):
35
+ line = raw_line.rstrip("\r\n")
36
+ m = ZSH_EXT_RE.match(line)
37
+ return m.group(1) if m else line
38
+
39
+
40
+ def load_history(path):
41
+ if not os.path.exists(path):
42
+ return []
43
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
44
+ return [line.rstrip("\r\n") for line in f if line.strip()]
45
+
46
+
47
+ def save_history(path, raw_lines):
48
+ with open(path, "w", encoding="utf-8", errors="replace") as f:
49
+ for line in raw_lines:
50
+ f.write(line + "\n")
51
+
52
+
53
+ def build_view(raw_lines, query, sort_key):
54
+ q = query.lower()
55
+ parsed = [(idx, parse_line(raw)) for idx, raw in enumerate(raw_lines)]
56
+
57
+ if sort_key == "freq":
58
+ counts = Counter(cmd for _, cmd in parsed)
59
+ idx_map = {}
60
+ for idx, cmd in parsed:
61
+ idx_map.setdefault(cmd, []).append(idx)
62
+ return [
63
+ {
64
+ "cmd": cmd,
65
+ "label": f"[{count:>4}x] {cmd}",
66
+ "indices": idx_map[cmd],
67
+ }
68
+ for cmd, count in counts.most_common()
69
+ if q in cmd.lower()
70
+ ]
71
+
72
+ items = [
73
+ {"cmd": cmd, "label": cmd, "indices": [idx]}
74
+ for idx, cmd in parsed
75
+ if q in cmd.lower()
76
+ ]
77
+
78
+ if sort_key == "recent":
79
+ items.reverse()
80
+ elif sort_key == "alpha":
81
+ items.sort(key=lambda x: x["cmd"].lower())
82
+
83
+ return items
84
+
85
+
86
+ def edit_command_modal(stdscr, initial_cmd):
87
+ """Interactive edit screen. Returns modified command string or None if cancelled."""
88
+ import curses
89
+ buf = list(initial_cmd)
90
+ cursor = len(buf)
91
+ h_offset = 0
92
+
93
+ while True:
94
+ height, width = stdscr.getmaxyx()
95
+ stdscr.erase()
96
+
97
+ # Header
98
+ header = " EDIT & EXECUTE COMMAND "
99
+ stdscr.attron(curses.color_pair(3))
100
+ stdscr.addnstr(0, 0, header.ljust(width - 1), width - 1)
101
+ stdscr.attroff(curses.color_pair(3))
102
+
103
+ # Centered edit panel dimensions
104
+ box_w = max(20, min(width - 4, 100))
105
+ box_h = 7
106
+ start_y = max(2, (height - box_h) // 2)
107
+ start_x = max(1, (width - box_w) // 2)
108
+ inner_w = max(1, box_w - 4)
109
+
110
+ # Draw panel box if terminal is tall enough
111
+ if height >= start_y + box_h + 1:
112
+ stdscr.addnstr(start_y, start_x, "+" + "-" * (box_w - 2) + "+", width - start_x - 1)
113
+ for row in range(1, box_h - 1):
114
+ stdscr.addnstr(
115
+ start_y + row,
116
+ start_x,
117
+ "|" + " " * (box_w - 2) + "|",
118
+ width - start_x - 1,
119
+ )
120
+ stdscr.addnstr(
121
+ start_y + box_h - 1,
122
+ start_x,
123
+ "+" + "-" * (box_w - 2) + "+",
124
+ width - start_x - 1,
125
+ )
126
+
127
+ title = " Modify command below: "
128
+ stdscr.attron(curses.color_pair(2))
129
+ stdscr.addnstr(start_y + 1, start_x + 2, title, inner_w)
130
+ stdscr.attroff(curses.color_pair(2))
131
+
132
+ # Horizontal scrolling for long commands
133
+ if cursor < h_offset:
134
+ h_offset = cursor
135
+ elif cursor >= h_offset + inner_w:
136
+ h_offset = cursor - inner_w + 1
137
+
138
+ cmd_str = "".join(buf)
139
+ visible_text = cmd_str[h_offset : h_offset + inner_w]
140
+
141
+ input_y = start_y + 3
142
+ input_x = start_x + 2
143
+ stdscr.attron(curses.color_pair(1))
144
+ stdscr.addnstr(input_y, input_x, visible_text.ljust(inner_w), inner_w)
145
+ stdscr.attroff(curses.color_pair(1))
146
+
147
+ # Action hints inside box
148
+ actions = "[Enter] Execute [Esc] Cancel & Back"
149
+ stdscr.addnstr(start_y + 5, start_x + 2, actions, inner_w)
150
+
151
+ # Footer keybindings
152
+ footer = " [Left/Right] Move [Home/Ctrl+A] Start [End/Ctrl+E] End [Ctrl+U] Clear Left [Ctrl+K] Clear Right "
153
+ stdscr.attron(curses.color_pair(3))
154
+ stdscr.addnstr(height - 1, 0, footer.ljust(width - 1), width - 1)
155
+ stdscr.attroff(curses.color_pair(3))
156
+
157
+ # Position cursor inside the input field
158
+ stdscr.move(input_y, min(input_x + (cursor - h_offset), width - 2))
159
+
160
+ stdscr.refresh()
161
+
162
+ try:
163
+ key = stdscr.get_wch()
164
+ except curses.error:
165
+ continue
166
+
167
+ # Cancel (Esc or Ctrl+C)
168
+ if key in ("\x1b", "\x03"):
169
+ return None
170
+
171
+ # Execute (Enter)
172
+ elif key in ("\n", "\r", curses.KEY_ENTER):
173
+ final_cmd = "".join(buf).strip()
174
+ return final_cmd if final_cmd else None
175
+
176
+ # Cursor movement
177
+ elif key == curses.KEY_LEFT:
178
+ cursor = max(0, cursor - 1)
179
+ elif key == curses.KEY_RIGHT:
180
+ cursor = min(len(buf), cursor + 1)
181
+ elif key in (curses.KEY_HOME, "\x01"): # Home or Ctrl+A
182
+ cursor = 0
183
+ elif key in (curses.KEY_END, "\x05"): # End or Ctrl+E
184
+ cursor = len(buf)
185
+
186
+ # Editing
187
+ elif key in (curses.KEY_BACKSPACE, "\x7f", "\b"):
188
+ if cursor > 0:
189
+ del buf[cursor - 1]
190
+ cursor -= 1
191
+ elif key == curses.KEY_DC:
192
+ if cursor < len(buf):
193
+ del buf[cursor]
194
+ elif key == "\x15": # Ctrl+U: clear before cursor
195
+ buf = buf[cursor:]
196
+ cursor = 0
197
+ elif key == "\x0b": # Ctrl+K: clear after cursor
198
+ buf = buf[:cursor]
199
+ elif key == curses.KEY_RESIZE:
200
+ pass
201
+ elif isinstance(key, str) and key.isprintable():
202
+ buf.insert(cursor, key)
203
+ cursor += 1
204
+
205
+
206
+ def show_help(stdscr):
207
+ import curses
208
+
209
+ lines = [
210
+ "History list:",
211
+ " Up/Down, Page Up/Down Move through matches",
212
+ " Type Filter commands",
213
+ " Backspace Remove the last filter character",
214
+ " Ctrl+U Clear the filter",
215
+ " Ctrl+O or F2 Cycle sort order",
216
+ " Enter Edit the selected command",
217
+ " Delete or Ctrl+D Delete the selected entry",
218
+ " Esc or Ctrl+C Quit",
219
+ "",
220
+ "Command editor:",
221
+ " Left/Right Move the cursor",
222
+ " Home/Ctrl+A, End/Ctrl+E Move to the start or end",
223
+ " Backspace/Delete Delete a character",
224
+ " Ctrl+U Clear before the cursor",
225
+ " Ctrl+K Clear after the cursor",
226
+ " Enter Run the edited command",
227
+ " Esc or Ctrl+C Return without running it",
228
+ ]
229
+ scroll = 0
230
+
231
+ while True:
232
+ height, width = stdscr.getmaxyx()
233
+ body_height = max(0, height - 2)
234
+ scroll = min(scroll, max(0, len(lines) - body_height))
235
+ stdscr.erase()
236
+
237
+ header = " HISTORY TUI HELP "
238
+ stdscr.attron(curses.color_pair(3))
239
+ stdscr.addnstr(0, 0, header.ljust(max(0, width - 1)), max(0, width - 1))
240
+ stdscr.attroff(curses.color_pair(3))
241
+
242
+ for row, line in enumerate(lines[scroll : scroll + body_height], start=1):
243
+ if line.endswith(":"):
244
+ stdscr.attron(curses.color_pair(2))
245
+ stdscr.addnstr(row, 0, line, max(0, width - 1))
246
+ stdscr.attroff(curses.color_pair(2))
247
+ else:
248
+ stdscr.addnstr(row, 0, line, max(0, width - 1))
249
+
250
+ if height > 1:
251
+ footer = " [Up/Down, PgUp/PgDn] Scroll [F1/Esc/Enter] Close "
252
+ stdscr.attron(curses.color_pair(3))
253
+ stdscr.addnstr(
254
+ height - 1,
255
+ 0,
256
+ footer.ljust(max(0, width - 1)),
257
+ max(0, width - 1),
258
+ )
259
+ stdscr.attroff(curses.color_pair(3))
260
+
261
+ stdscr.refresh()
262
+
263
+ try:
264
+ key = stdscr.get_wch()
265
+ except curses.error:
266
+ continue
267
+
268
+ if key in ("\x1b", "\x03", "\n", "\r", curses.KEY_ENTER, curses.KEY_F1):
269
+ return
270
+ elif key == curses.KEY_UP:
271
+ scroll = max(0, scroll - 1)
272
+ elif key == curses.KEY_DOWN:
273
+ scroll = min(max(0, len(lines) - body_height), scroll + 1)
274
+ elif key == curses.KEY_PPAGE:
275
+ scroll = max(0, scroll - max(1, body_height))
276
+ elif key == curses.KEY_NPAGE:
277
+ scroll = min(
278
+ max(0, len(lines) - body_height),
279
+ scroll + max(1, body_height),
280
+ )
281
+ elif key == curses.KEY_RESIZE:
282
+ continue
283
+
284
+
285
+ def run_tui(stdscr, histfile):
286
+ import curses
287
+
288
+ curses.curs_set(1)
289
+ curses.use_default_colors()
290
+ curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_CYAN) # Highlight / input
291
+ curses.init_pair(2, curses.COLOR_YELLOW, -1) # Status / accent
292
+ curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) # Header / footer
293
+
294
+ raw_lines = load_history(histfile)
295
+ query = ""
296
+ sort_idx = 0
297
+ selected = 0
298
+ scroll_offset = 0
299
+ status_msg = f"Loaded {len(raw_lines)} entries from {histfile}"
300
+
301
+ while True:
302
+ sort_name, sort_key = SORT_MODES[sort_idx]
303
+ items = build_view(raw_lines, query, sort_key)
304
+
305
+ if not items:
306
+ selected = 0
307
+ scroll_offset = 0
308
+ else:
309
+ selected = max(0, min(selected, len(items) - 1))
310
+
311
+ height, width = stdscr.getmaxyx()
312
+ list_top = 2
313
+ list_height = max(1, height - 4)
314
+
315
+ if selected < scroll_offset:
316
+ scroll_offset = selected
317
+ elif selected >= scroll_offset + list_height:
318
+ scroll_offset = selected - list_height + 1
319
+
320
+ stdscr.erase()
321
+
322
+ # Header
323
+ header = f" HISTORY TUI | Sort: {sort_name} | Matches: {len(items)}/{len(raw_lines)} "
324
+ stdscr.attron(curses.color_pair(3))
325
+ stdscr.addnstr(0, 0, header.ljust(width - 1), width - 1)
326
+ stdscr.attroff(curses.color_pair(3))
327
+
328
+ # Search prompt
329
+ prompt = f"Filter: {query}"
330
+ stdscr.addnstr(1, 0, prompt, width - 1)
331
+
332
+ # Command list
333
+ visible = items[scroll_offset : scroll_offset + list_height]
334
+ for row_i, item in enumerate(visible):
335
+ y = list_top + row_i
336
+ abs_i = scroll_offset + row_i
337
+ text = item["label"].replace("\t", " ")
338
+ if abs_i == selected:
339
+ stdscr.attron(curses.color_pair(1))
340
+ stdscr.addnstr(y, 0, f"> {text}".ljust(width - 1), width - 1)
341
+ stdscr.attroff(curses.color_pair(1))
342
+ else:
343
+ stdscr.addnstr(y, 0, f" {text}", width - 1)
344
+
345
+ # Status line
346
+ if height > 3:
347
+ stdscr.attron(curses.color_pair(2))
348
+ stdscr.addnstr(height - 2, 0, status_msg, width - 1)
349
+ stdscr.attroff(curses.color_pair(2))
350
+
351
+ # Footer
352
+ if height > 2:
353
+ help_bar = " [F1] Help [Enter] Edit & Run [Ctrl+O/F2] Sort [Del/Ctrl+D] Delete [Esc] Quit "
354
+ stdscr.attron(curses.color_pair(3))
355
+ stdscr.addnstr(height - 1, 0, help_bar.ljust(width - 1), width - 1)
356
+ stdscr.attroff(curses.color_pair(3))
357
+
358
+ stdscr.move(1, min(len(prompt), width - 2))
359
+ stdscr.refresh()
360
+
361
+ try:
362
+ key = stdscr.get_wch()
363
+ except curses.error:
364
+ continue
365
+
366
+ # Quit
367
+ if key in ("\x1b", "\x03"):
368
+ return None
369
+
370
+ elif key == curses.KEY_F1:
371
+ show_help(stdscr)
372
+
373
+ # Open in-TUI editor for selected command
374
+ elif key in ("\n", "\r", curses.KEY_ENTER):
375
+ if items:
376
+ edited = edit_command_modal(stdscr, items[selected]["cmd"])
377
+ if edited is not None:
378
+ return edited
379
+ status_msg = "Execution cancelled"
380
+
381
+ # Navigation
382
+ elif key == curses.KEY_UP:
383
+ selected = max(0, selected - 1)
384
+ elif key == curses.KEY_DOWN:
385
+ selected = min(len(items) - 1, selected + 1)
386
+ elif key == curses.KEY_PPAGE:
387
+ selected = max(0, selected - list_height)
388
+ elif key == curses.KEY_NPAGE:
389
+ selected = min(len(items) - 1, selected + list_height)
390
+
391
+ # Sort cycle
392
+ elif key in ("\x0f", curses.KEY_F2):
393
+ sort_idx = (sort_idx + 1) % len(SORT_MODES)
394
+ selected = 0
395
+ scroll_offset = 0
396
+ status_msg = f"Sorted by: {SORT_MODES[sort_idx][0]}"
397
+
398
+ # Delete entry
399
+ elif key in (curses.KEY_DC, "\x04"):
400
+ if items:
401
+ target = items[selected]
402
+ to_remove = set(target["indices"])
403
+ raw_lines = [
404
+ line for i, line in enumerate(raw_lines) if i not in to_remove
405
+ ]
406
+ save_history(histfile, raw_lines)
407
+ status_msg = f"Deleted {len(to_remove)} entry(s) matching: {target['cmd'][:40]}"
408
+
409
+ # Filter editing
410
+ elif key in (curses.KEY_BACKSPACE, "\x7f", "\b"):
411
+ if query:
412
+ query = query[:-1]
413
+ selected = 0
414
+ scroll_offset = 0
415
+ elif key == "\x15":
416
+ query = ""
417
+ selected = 0
418
+ scroll_offset = 0
419
+ elif key == curses.KEY_RESIZE:
420
+ pass
421
+ elif isinstance(key, str) and key.isprintable():
422
+ query += key
423
+ selected = 0
424
+ scroll_offset = 0
425
+
426
+
427
+ def main():
428
+ parser = argparse.ArgumentParser(description="Interactive shell history TUI with editor")
429
+ parser.add_argument(
430
+ "--version", action="version", version=f"%(prog)s {__version__}"
431
+ )
432
+ parser.add_argument("--histfile", help="Path to shell history file")
433
+ args = parser.parse_args()
434
+
435
+ import curses
436
+
437
+ os.environ.setdefault("ESCDELAY", "25")
438
+ histfile = detect_histfile(args.histfile)
439
+
440
+ cmd_to_run = curses.wrapper(run_tui, histfile)
441
+
442
+ if cmd_to_run:
443
+ shell = os.environ.get("SHELL", "/bin/bash")
444
+ print(f"$ {cmd_to_run}", flush=True)
445
+ result = subprocess.run(cmd_to_run, shell=True, executable=shell)
446
+ sys.exit(result.returncode)
447
+
448
+
449
+ if __name__ == "__main__":
450
+ main()