pi-vim-tree 0.1.0 → 0.1.2

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.
package/CHANGELOG.md CHANGED
@@ -1,18 +1,32 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.1.2] - 2026-11-20
4
4
 
5
- - Branch motion is now `h` / `l` (next / previous branch head), matching `ctrl+j` / `ctrl+k`. Branch-head jumps also enter the jump list, so `ctrl+o` walks back through the branches you visited.
6
- - Half-page scroll added on `u` / `d`, matching `ctrl+u` / `ctrl+d`.
7
- - Removed the `d{m}` single-mark delete. `d` is half-page scroll now; `M` still clears every mark.
8
- - Label editing and label timestamps moved to uppercase only: `L` / `T`. Lowercase `l` is branch motion, lowercase `t` is unbound.
9
- - `q` closes the tree (native `esc` behaviour is unchanged; `ctrl+l` stays the way to clear a pending command or the search highlight).
5
+ - **The scroll keys moved.** `ctrl+f` / `ctrl+b` / `ctrl+u` / `ctrl+d` now scroll the side preview and nothing else; list paging is `f` / `b` (whole page) and `u` / `d` (half page). The four control keys belong to the preview the way they belong to the help window in Vim or `less`: when the preview is closed, too narrow to render, or its body fits on one screen, they do nothing. They never fall back to the list, and they never reach Pi's native keys underneath.
6
+ - The tree can be closed with the key that opened it. In the tree, `app.session.tree` closes it - whatever `keybindings.json` binds that action to. The key is read through Pi's `KeybindingsManager`, not hardcoded, so `/reload` and a changed binding are picked up. It is unbound by default, so nothing happens until you bind it; on terminals where `ctrl+i` and Tab are the same byte, binding it to `ctrl+i` makes Tab close the tree too.
7
+ - The filter mode (`gt` / `gl` / `gu` / `ga` / `gd`) is remembered. Pi only passes `treeFilterMode` in when the tree opens and never writes back a mode picked inside the tree, so the extension records it: in memory for the session, and in `vim-tree.json` in the agent directory across launches. Changing `treeFilterMode` in `/settings` takes precedence and resyncs the memory, so the setting never gets shadowed.
8
+ - The mouse wheel scrolls what is under it: over the preview panel it scrolls the preview by whole lines, over Pi's tree panel it moves the list cursor (row by row, like `j` / `k`). Over the preview panel it falls back to the tree when the preview cannot scroll. Only `wheel` is taken over - clicks and drags still go to Pi, and the label editor keeps every event while it is open.
9
+ - Two loaded copies of the extension no longer fight over the patch: the copy that loaded last owns it, and `/vim-tree off` on a stale copy only disables that copy instead of restoring native methods under the active one. This is the `/vim-tree:1` / `/vim-tree:2` case - Pi appends `:1` / `:2` when the same command name is registered twice. `/vim-tree` now warns when it detects another loaded copy, and the test suite loads two copies on purpose to check it.
10
+ - The README explains the two ways to load the extension while working - `pi -e` for a single run, or the auto-discovered extensions directory (or an `extensions` entry in settings) for `/reload` - and what the `[u]` / `[p]` / `[t]` scope tags next to extension commands mean. It also opens with one table of the everyday keys - Pi's tree panel and the preview panel side by side - and documents the remembered filter mode, the wheel, and that a stray `npm install` replaces the links `test/setup.sh` creates.
11
+
12
+ ## [0.1.1] - 2026-11-16
13
+
14
+ - The preview pane now renders the selected entry with Pi's own `Markdown` component and `getMarkdownTheme()`, so headings, lists, quotes and fenced code blocks look like they do in the conversation, including syntax highlighting. It follows the active theme, custom themes included, and adds no new dependency: the renderer and highlight.js come from Pi itself.
15
+ - Preview scrolling is a one-line window over the rendered lines (`ctrl+e` / `ctrl+y`). Plain wrapped text remains as the fallback when no theme is available.
16
+ - Search-term highlighting in the preview now only applies to that plain-text fallback; recolouring Markdown lines would corrupt their ANSI styling.
17
+ - The changelog now lists what 0.1.0 shipped instead of leaving it under `Unreleased`.
10
18
 
11
- ## [0.1.0] - 2026-11-10
19
+ ## [0.1.0] - 2026-11-15
20
+
21
+ First published release.
12
22
 
13
- - Initial release.
14
23
  - Vim folding: `zc` / `zo` / `za` / `zC` / `zO` / `zA` / `zm` / `zr` / `zM` / `zR` / `zj` / `zk` / `zv`.
15
24
  - Stable line numbers: folding never renumbers rows, so `G`, `{n}G`, `gg` and `%` always mean the same row.
16
- - Logical cursor row, jump list (`ctrl+o` / `ctrl+i`), marks (`m{x}`, `` ` ``{x}, `d{x}`), and a showcmd-style status bar.
25
+ - Logical cursor row, jump list (`ctrl+o` / `ctrl+i`), marks (`m{x}`, `` ` ``{x}), and a showcmd-style status bar.
17
26
  - Fixed-height list with a side preview.
18
27
  - `/vim-tree on|off` restores Pi's native tree exactly.
28
+ - Branch motion on `h` / `l` (next / previous branch head), matching `ctrl+j` / `ctrl+k`. Branch-head jumps also enter the jump list, so `ctrl+o` walks back through the branches you visited.
29
+ - Half-page scroll on `u` / `d`, matching `ctrl+u` / `ctrl+d`.
30
+ - Label editing and label timestamps are on uppercase keys only: `L` / `T`. Lowercase `l` is branch motion, lowercase `t` is unbound.
31
+ - `q` closes the tree (native `esc` behaviour is unchanged; `ctrl+l` stays the way to clear a pending command or the search highlight).
32
+ - No single-mark delete: `d` is half-page scroll, so a mark is cleared with `M` or overwritten by setting it again.
package/README.md CHANGED
@@ -1,99 +1,67 @@
1
- > Pi can create extensions. Ask it to build one for your use case.
2
-
3
1
  # pi-vim-tree
4
2
 
5
- A Vim-flavoured patch for Pi's built-in `/tree` view. It adds Vim-style folding, motion, and status feedback on top of the native tree, and hands everything else back to Pi unchanged.
6
-
7
- The extension patches the native tree in place. It never replaces `/tree`, never changes what the tree contains, and can be turned off at runtime to restore the original behaviour exactly.
8
-
9
- **Key capabilities:**
10
- - **Vim folding** - `zc`/`zo`/`za`/`zC`/`zO`/`zA`/`zm`/`zr`/`zM`/`zR`/`zj`/`zk`/`zv` with Vim's semantics
11
- - **Stable line numbers** - folding never renumbers rows, so `G`, `{n}G`, `gg`, and `%` always mean the same row
12
- - **Logical cursor row** - folding hides the row under the cursor but keeps its place, and restores it when the fold opens again
13
- - **Jump list** - `ctrl+o` and `ctrl+i` walk backwards and forwards through your jumps, the way Vim's jump list does
14
- - **Marks** - `m` plus a letter or digit sets a mark, backtick plus the same name jumps back to it
15
- - **Showcmd status bar** - pending prefixes and executed commands echo the way Vim's `showcmd` does
16
- - **Fixed-height layout** - the list never resizes, so filtering or folding never makes the panel jump
17
- - **Side preview** - the selected message body is shown next to the tree, fzf `--preview-window` style
18
-
19
- **Example use cases:**
20
- - Navigating long sessions without losing your place
21
- - Collapsing noisy branches while keeping jump targets stable
22
- - Reaching a collapsed branch with a single keystroke (`zA`, `zv`)
23
- - Working with the tree in a fixed-size panel inside larger terminal layouts
24
-
25
- ## Table of Contents
26
-
27
- - [Installation](#installation)
28
- - [Requirements](#requirements)
29
- - [Commands](#commands)
30
- - [Key Bindings](#key-bindings)
31
- - [Folding](#folding)
32
- - [Motion](#motion)
33
- - [Search](#search)
34
- - [Preview](#preview)
35
- - [Folding Model](#folding-model)
36
- - [Line Numbers and Jumps](#line-numbers-and-jumps)
37
- - [Logical Cursor Row](#logical-cursor-row)
38
- - [Marks](#marks)
39
- - [Jump List](#jump-list)
40
- - [Status Bar](#status-bar)
41
- - [Layout](#layout)
42
- - [Compatibility](#compatibility)
43
- - [Troubleshooting](#troubleshooting)
44
- - [Differences from Vim](#differences-from-vim)
45
- - [Development](#development)
46
-
47
- ## Installation
48
-
49
- Install it as a Pi package:
3
+ Vim folding, motion, jump list, marks and a Markdown preview for Pi's built-in `/tree`.
50
4
 
51
- ```bash
52
- pi install npm:pi-vim-tree
53
- ```
5
+ It patches the native tree in place - same rows, same search, same actions - and puts Vim keys on top. Nothing is replaced, and `/vim-tree off` restores native behaviour exactly.
6
+
7
+ **Two panels: Pi's default tree list, and a preview of the selected message.**
8
+
9
+ ## Everyday Keys
10
+
11
+ The list panel is Pi's own `/tree` - every kind of entry appears there: user message, reply, tool call. The preview panel is added by this extension and shows the full content of the row under the cursor, rendered as Markdown.
12
+
13
+ | I want to | Tree panel (left) - Pi's `/tree` list | Preview panel (right) - the selected message |
14
+ | --- | --- | --- |
15
+ | Move | `j` / `k` - or the wheel | `ctrl+e` / `ctrl+y` line · `ctrl+u` / `ctrl+d` half page · `ctrl+f` / `ctrl+b` page - or the wheel |
16
+ | Switch branch | **`h` / `l`** (previous / next branch head, wraps) · also `ctrl+j` / `ctrl+k`, `shift+up` / `shift+down` | - |
17
+ | Jump by number | `{n}G` row `n` · `G` last · `gg` first · `%` matching branch · `g0` my branch | - |
18
+ | Come back | `ctrl+o` / `ctrl+i` - the jump list, Vim's | - |
19
+ | Park a spot | `m` + a letter, back with `` ` `` + the same letter | - |
20
+ | Label a row | `L` edit its label · `T` show / hide label timestamps | - |
21
+ | Wipe bookkeeping | `J` clears the jump list · `M` clears all marks | - |
22
+ | Fold noise away | `za` toggle · `zc` / `zo` close / open · `zM` / `zR` all · `zv` reveal the cursor row | - |
23
+ | Thin the tree out | `gt` / `gl` / `gu` / `ga` / `gd` filters (remembered) | - |
24
+ | Find something | `/` then `n` / `N` (or `p`) | - |
25
+ | Leave | `q`, or your `app.session.tree` key | - |
26
+
27
+ Learn `h` / `l` first: branch heads are the only structure a tree has, so hopping them does what `w` / `b` does in text - and every hop lands in the jump list, so `ctrl+o` walks you back through the branches you visited.
54
28
 
55
- Or try it for a single run without adding it to your settings:
29
+ ## Contents
30
+
31
+ [Install](#install) · [Requirements](#requirements) · [Commands](#commands) · [Keys](#keys) · [Behaviour](#behaviour) · [Compatibility](#compatibility) · [Troubleshooting](#troubleshooting) · [Differences from Vim](#differences-from-vim) · [Releasing](#releasing) · [Development](#development)
32
+
33
+ ## Install
56
34
 
57
35
  ```bash
58
- pi -e npm:pi-vim-tree
36
+ pi install npm:pi-vim-tree
59
37
  ```
60
38
 
61
- Without npm, copy `extensions/vim-tree.ts` into Pi's global extension directory:
39
+ One-off run, or without npm at all:
62
40
 
63
41
  ```bash
64
- mkdir -p ~/.pi/agent/extensions
65
- cp extensions/vim-tree.ts ~/.pi/agent/extensions/vim-tree.ts
42
+ pi -e npm:pi-vim-tree
43
+ mkdir -p ~/.pi/agent/extensions && cp extensions/vim-tree.ts ~/.pi/agent/extensions/
66
44
  ```
67
45
 
68
- Restart Pi, or hot-reload the extension with `/reload`. Extensions in `~/.pi/agent/extensions/` are auto-discovered and can be reloaded without restarting the session.
69
-
70
- To disable the patch at startup, set `PI_VIM_TREE=0` in the environment. Pi then loads the extension but applies nothing.
46
+ `/reload` hot-reloads; files in `~/.pi/agent/extensions/` are auto-discovered. `PI_VIM_TREE=0` loads the extension but applies nothing.
71
47
 
72
48
  ## Requirements
73
49
 
74
- Pi 1.5.1 or newer. The extension works by patching Pi's internal tree component, so it needs access to those internals - it locates them by content rather than by file name, because the bundle's chunk names change with every release.
75
-
76
- When Pi changes the internals in a way the extension does not recognise, it stays silent and leaves the native tree alone. `/vim-tree` then reports why.
77
-
78
- Node.js 22.19 or newer, same as Pi itself. The extension adds no runtime dependencies.
50
+ Pi 1.5.1+, Node 22.19+. The patch targets Pi's internal tree classes inside the compiled bundle. Chunk names change every release (`chunk-44DLKSKE.js` in 1.5.0, `chunk-ZKNSXGL5.js` in 1.5.1), so the chunk is found by content, not by file name. If the internals change shape, nothing is patched, the native tree keeps working, and `/vim-tree` reports why. No runtime dependencies.
79
51
 
80
52
  ## Commands
81
53
 
82
- | Command | Description |
54
+ | Command | Effect |
83
55
  | --- | --- |
84
- | `/vim-tree` | Report the current state (on/off, build id, and the reason if the patch could not be applied) |
85
- | `/vim-tree on` | Apply the patch to `/tree` |
86
- | `/vim-tree off` | Remove every patch and restore native behaviour |
87
-
88
- `off` is a full undo: each patched method is registered in an undo registry and reverted in reverse order, including the tree instance's filter handling and the search state.
56
+ | `/vim-tree` | State, build id, and the reason if the patch could not be applied |
57
+ | `/vim-tree on` | Apply the patch |
58
+ | `/vim-tree off` | Undo every patch |
89
59
 
90
- The tree *instance* is restored as well. While it is active the extension changes the list height, the filter mode, the fold state and the label-timestamp flag - all of them native fields - so `off` puts the original values back, clears the search box and resets the mode. Without that the native tree would come back with the wrong number of rows, a filter still applied, or folds left over.
60
+ `off` is a full undo: patched methods are reverted in reverse order, and the tree instance gets its original height, filter mode, fold state and label-timestamp flag back. While the label editor is open the extension steps aside and hands every key to Pi.
91
61
 
92
- While the label editor is open, the extension steps aside completely and hands every key to Pi, so labels are typed exactly the way Pi types them.
62
+ ## Keys
93
63
 
94
- ## Key Bindings
95
-
96
- Native tree keys (`j`/`k`, `enter`, `L` label, `T` label time, `/` search) keep working. Label and label time are on the uppercase keys only - lowercase `l` is branch motion now, and lowercase `t` is unbound. The extension adds:
64
+ Native keys (`j` / `k`, `enter`, `/`, `L`, `T`) keep working. Lowercase `l` is branch motion and `t` is unbound, which is why label and label time live on the uppercase keys.
97
65
 
98
66
  ### Folding
99
67
 
@@ -124,17 +92,27 @@ Native tree keys (`j`/`k`, `enter`, `L` label, `T` label time, `/` search) keep
124
92
  | `G` / `{n}G` | Jump to the last row / to row `{n}` |
125
93
  | `%` | Jump to the matching branch |
126
94
  | `gt` / `gl` / `gu` / `ga` / `gd` | Filter: no tools / labelled only / user only / all / default |
127
- | `ctrl+f` / `ctrl+b` | Page down / up |
95
+ | `f` / `b` | Page down / up |
128
96
  | `u` / `d` | Half page up / down |
129
- | `ctrl+u` / `ctrl+d` | Half page up / down (same as `u` / `d`) |
130
97
 
131
- ### Leaving
98
+ List paging is the lowercase `f` / `b` / `u` / `d` group; `ctrl+f` / `ctrl+b` / `ctrl+u` / `ctrl+d` belong to the preview.
99
+
100
+ ### Preview
132
101
 
133
102
  | Key | Action |
134
103
  | --- | --- |
135
- | `q` | Close the tree (like `q` in a Vim help/preview window, or in `less` / `fzf`) |
104
+ | `ctrl+h` (or `F4`) | Toggle the side preview |
105
+ | `ctrl+e` / `ctrl+y` | Scroll the preview by one line |
106
+ | `ctrl+u` / `ctrl+d` | Scroll the preview by half a page |
107
+ | `ctrl+f` / `ctrl+b` | Scroll the preview by a whole page |
108
+
109
+ The body is rendered with Pi's own `Markdown` component and `getMarkdownTheme()`, so headings, lists, quotes and code blocks look like the conversation, syntax highlighting included. It borrows the active theme; without one it falls back to plain wrapped text.
110
+
111
+ Those four control keys belong to the preview and nothing else. Closed, too narrow, or a body that fits on one screen - they do nothing: no fallback to the list, no leak to Pi's native keys.
136
112
 
137
- `esc` keeps its native meaning (cancel the search box, otherwise leave the tree) - nothing is layered on top of it. Clearing a pending command or the search highlight is `ctrl+l`'s job, matching the `ctrl+l` mapping people already have in Vim.
113
+ ### Mouse
114
+
115
+ Only the wheel is taken over: over the preview panel it scrolls the preview by lines, over the tree panel it moves the cursor row by row (like repeated `j` / `k`, never a screen jump). Over the preview panel it falls back to the tree when the preview cannot scroll. Clicks and drags are Pi's; the label editor keeps every event.
138
116
 
139
117
  ### Search
140
118
 
@@ -145,170 +123,186 @@ Native tree keys (`j`/`k`, `enter`, `L` label, `T` label time, `/` search) keep
145
123
  | `p` | Previous match |
146
124
  | `ctrl+l` | Clear the search term and the highlight |
147
125
 
148
- ### Preview
126
+ ### Leaving
149
127
 
150
128
  | Key | Action |
151
129
  | --- | --- |
152
- | `ctrl+h` (or `F4`) | Toggle the side preview |
153
- | `ctrl+e` / `ctrl+y` | Scroll the preview by one line |
130
+ | `q` | Close the tree (like `q` in a Vim help window, or in `less` / `fzf`) |
131
+ | your `app.session.tree` key | Close the tree - the key that opened it closes it, so the binding toggles |
154
132
 
155
- ## Folding Model
133
+ The toggle key is whatever `keybindings.json` binds `app.session.tree` to, read through Pi's `KeybindingsManager` - not hardcoded. It is unbound by default, so nothing happens until you bind it:
156
134
 
157
- Pi's native tree marks the rows that can be folded with `⊟`, and shows `⊞` once a fold is closed. pi-vim-tree folds exactly those rows, and nothing else:
135
+ ```json
136
+ { "app.session.tree": ["ctrl+shift+t"] }
137
+ ```
158
138
 
159
- - Only branch points fold. Leaf rows and the root row have no fold marker, so they never fold.
160
- - A fold closes the whole subtree below the row.
161
- - `zm` and `zr` work on *levels*, not on individual rows. Levels are numbered consecutively (like Vim's `foldlevel`) because Pi's own indent only increments at branch points, which would otherwise produce a `1 -> 3 -> 5` sequence.
139
+ On terminals where `ctrl+i` and Tab are the same byte, binding it to `ctrl+i` makes Tab close the tree too. `esc` keeps its native meaning (cancel the search box, otherwise leave the tree).
162
140
 
163
- The current level and the total number of levels are shown in the title bar:
141
+ ### Filters
164
142
 
165
- ```
166
- Session Tree Fold 2/5 · Match 1/3
167
- ```
143
+ The mode you pick with `gt` / `gl` / `gu` / `ga` / `gd` is remembered: in memory for the session, and in `vim-tree.json` in the agent directory (`~/.pi/agent/vim-tree.json` unless `PI_CODING_AGENT_DIR` says otherwise) across launches. Pi passes `treeFilterMode` in when the tree opens and never writes back a mode picked inside, so the extension records it.
144
+
145
+ Changing `treeFilterMode` in `/settings` wins - that value becomes the new baseline and the memory is resynced to it, so the setting is never shadowed. Deleting `vim-tree.json` resets the memory to the setting.
168
146
 
169
- ## Line Numbers and Jumps
147
+ ## Behaviour
170
148
 
171
- Line numbers are computed against the **unfolded** list, the way Vim counts buffer lines. Folding a branch hides the rows inside it and leaves their numbers blank; it never renumbers the rows below.
149
+ ### Folds
172
150
 
173
- Because of that, every jump command resolves against the same fixed list:
151
+ Pi marks foldable rows with `⊟`, `⊞` once closed. pi-vim-tree folds exactly those rows and nothing else.
174
152
 
175
- - `G` and `{n}G` jump to an absolute row number
176
- - `gg` jumps to the first row
177
- - `%` jumps to the matching branch
153
+ - Only branch points fold - leaf rows and the root have no marker.
154
+ - A fold closes the whole subtree below it.
155
+ - `zm` / `zr` step *levels*, numbered consecutively like Vim's `foldlevel` (Pi's indent only increments at branch points, which would give `1 -> 3 -> 5`). The current level and the total live in the title bar: `Session Tree Fold 2/5`.
178
156
 
179
- If the target row is hidden inside a fold, the fold is opened first and the jump lands on the row itself. `g0` follows the same rule.
157
+ ### Line Numbers
180
158
 
181
- ## Logical Cursor Row
159
+ Numbers are computed against the **unfolded** list, the way Vim counts buffer lines. Folding hides rows and leaves their numbers blank; nothing below is renumbered.
182
160
 
183
- Pi-vim-tree keeps a single *logical cursor row* - the row the cursor really belongs to, even when it is hidden.
161
+ So every jump resolves against one fixed list: `G`, `{n}G`, `gg`, `%`, `g0`. If the target sits inside a fold, the fold opens first and the jump lands on the row itself.
184
162
 
185
- - Folding does not change it.
186
- - While it is hidden, the cursor is displayed on its nearest visible ancestor (the fold row).
187
- - When the fold opens again and the row becomes visible, the cursor returns to it.
188
- - Only moving the cursor replaces it.
163
+ ### Cursor Row
189
164
 
190
- The number of folds covering that row is derived from the parent chain, so folds in unrelated branches are never counted.
165
+ One *logical cursor row* is kept - the row the cursor really belongs to, even while hidden.
191
166
 
192
- `zv` remembers the row that a fold hid. Moving the cursor afterwards does not throw that memory away, so `zv` still brings you back to it - unlike the logical cursor row, which follows the cursor by Vim's rules.
167
+ - Folding does not move it; while hidden, the cursor is drawn on its nearest visible ancestor.
168
+ - Opening the fold puts the cursor back on it. Only moving the cursor replaces it.
169
+ - The number of folds covering it comes from the parent chain, so folds in unrelated branches are never counted.
193
170
 
194
- ## Marks
171
+ `zv` separately remembers the row a fold hid, and moving the cursor does not clear that memory - unlike the logical cursor row, which follows the cursor by Vim's rules.
195
172
 
196
- Marks work like in Vim. `m` followed by a letter or a digit stores the current row under that name; backtick followed by the same name jumps back to it. If the marked row is hidden inside a fold, the fold is opened first.
173
+ ### Marks
174
+
175
+ `m` plus a name stores the current row; backtick plus the same name jumps back, opening folds if needed.
197
176
 
198
177
  | Key | Action |
199
178
  | --- | --- |
200
179
  | `m` + letter or digit | Set a mark on the current row |
201
180
  | `` ` `` + letter or digit | Jump to that mark |
202
- | `` ` `` + `` ` `` | Jump back to the position before the last jump - press it again to come back, and again to go back |
181
+ | `` ` `` + `` ` `` | Jump to the position before the last jump - press again to come back, and again to go back |
203
182
  | `M` | Delete all marks (Vim's `:delmarks!`) |
204
183
 
205
- There are 62 mark names: `a` to `z`, `A` to `Z` and `0` to `9`.
206
-
207
- There is no single-mark delete key: `d` is half-page scroll now, so a mark goes away by clearing them all with `M` or by overwriting it. Setting a mark again under the same name simply replaces the old position.
184
+ 62 names: `a`-`z`, `A`-`Z`, `0`-`9`. No single-mark delete - `d` is half-page scroll, so a mark is cleared with `M` or overwritten.
208
185
 
209
- Marks live in the extension rather than in the tree view, so they survive closing and reopening `/tree`. They are cleared when the session changes, because the row ids they point at belong to the old session.
186
+ Marks live in the extension, so they survive closing and reopening `/tree`, and are cleared when the session changes - the row ids belong to the old session.
210
187
 
211
- Backtick backtick jumps to the position you were at before the last jump - Vim's "previous context" mark. It toggles: the next press brings you forward again, and the next one takes you back, so you can move between the two positions without re-typing the key. A fresh jump resets it to "back".
212
-
213
- ## Jump List
214
-
215
- `ctrl+o` and `ctrl+i` move through the jump list, exactly like Vim in normal mode: `ctrl+o` goes to the previous jump, `ctrl+i` goes to the next one.
188
+ ### Jump List
216
189
 
217
190
  | Key | Action |
218
191
  | --- | --- |
219
192
  | `ctrl+o` / `ctrl+i` | Older / newer position in the jump list |
220
193
  | `J` | Clear the jump list (Vim's `:clearjumps`) |
221
194
 
222
- Only *jumps* are recorded - `gg`, `G`, `{n}G`, `%`, `g0`, a branch-head jump (`h` / `l`, `ctrl+j` / `ctrl+k`, `shift+down` / `shift+up`), a mark jump, a committed search, and `n` / `N` / `p`. Branch-head jumps are structural jumps, the same class as Vim's `{` / `}`, so scanning branches with `h`/`l` and then pressing `ctrl+o` walks back through them one branch at a time. Line movement (`j` / `k`), scrolling (`u` / `d`, `ctrl+f/b`, `ctrl+u/d`) and fold jumps (`zj` / `zk`) do not enter the list, same as in Vim.
223
-
224
- The list behaves like browser history: jumping somewhere new truncates the entries ahead of the current position, so `ctrl+i` no longer walks into a branch you have left. A count works too - `{n}` followed by `ctrl+o` jumps back several entries at once.
225
-
226
- Entries are deduplicated by row, so a round of `l`/`h` branch scanning never piles up the same branch twice.
227
-
228
- Two limits match Vim:
195
+ Only *jumps* are recorded: `gg`, `G`, `{n}G`, `%`, `g0`, branch-head jumps (`h` / `l`, `ctrl+j` / `ctrl+k`, `shift+down` / `shift+up`), mark jumps, a committed search, `n` / `N` / `p`. Movement (`j` / `k`), list paging (`u` / `d`, `f` / `b`), fold jumps (`zj` / `zk`) and preview scrolling do not enter the list.
229
196
 
230
- - **At most 100 entries.** The oldest entries are dropped first.
231
- - **No duplicates.** Jumping to a row you visited before removes the older copy, so `ctrl+o` returns to that position once, not twice.
197
+ Like browser history, a new jump truncates what was ahead. A count works: `{n}` then `ctrl+o`. Entries are deduplicated by row, so scanning `l` / `h` never piles up the same branch twice. Vim's limits apply: at most 100 entries, no duplicates.
232
198
 
233
- ## Status Bar
199
+ ### Status Bar
234
200
 
235
- The status bar follows Vim's `showcmd` behaviour in three tiers:
201
+ `showcmd` in three tiers:
236
202
 
237
203
  | State | Behaviour |
238
204
  | --- | --- |
239
205
  | Waiting for a second key (`11`, `g`, `z`) | The prefix stays on screen |
240
- | Command finished (`j`, `11G`) | The command flashes briefly and is then cleared |
206
+ | Command finished (`j`, `11G`) | The command flashes briefly, then clears |
241
207
  | Unmatched key | Nothing is shown |
242
208
 
243
- The mode badge (`NORMAL` / `SEARCH`) is followed by the pending input in the default foreground colour.
244
-
245
- The counters next to the `Session Tree` title follow the same rule as the fold counter - they appear only when there is something to report, and disappear when it is gone:
209
+ The mode badge (`NORMAL` / `SEARCH`) is followed by the pending input. Counters appear only when there is something to report:
246
210
 
247
211
  ```
248
212
  Session Tree Fold 2/5 · Match 1/3 · Jump 4/9 · Mark a,b
249
213
  ```
250
214
 
251
- `Jump x/y` is your position in the jump list and how long the list is. `Mark a,b` lists the marks you have set. Clear the jump list with `J` and the marks with `M`, and both counters vanish again.
252
-
253
- ## Layout
215
+ `Jump x/y` is your position in the jump list and its length; `Mark a,b` lists the marks you set. `J` and `M` clear them, and the counters go with them.
254
216
 
255
- The list keeps a fixed height - 60% of the available space, capped at 30 rows - so folding, filtering, or a shorter session never resizes the panel and never makes surrounding UI shift.
217
+ ### Layout
256
218
 
257
- The preview occupies the right 55% of the width, fzf `--preview-window right:55%` style. Because the list height is fixed and the preview only takes horizontal space, toggling the preview causes no reflow at all.
219
+ The list keeps a fixed height - 60% of the available space, capped at 30 rows - so folding, filtering or a shorter session never resizes the panel. The preview panel takes the right 55% of the width, fzf `--preview-window right:55%` style, so toggling it causes no reflow at all.
258
220
 
259
221
  ## Compatibility
260
222
 
261
- The patch works on Pi's internal tree classes, which live in the compiled bundle. Chunk file names change between releases (`chunk-44DLKSKE.js` in 1.5.0, `chunk-ZKNSXGL5.js` in 1.5.1), so the extension locates the chunk by its content, imports it dynamically, and patches the prototype.
262
-
263
- Because it relies on private fields, it self-checks on startup. If Pi's internals change shape, the extension stays silent and falls back to native behaviour, and `/vim-tree` reports the reason.
223
+ The patch rides on private tree classes in Pi's compiled bundle, so it self-checks on startup. When the internals change shape it stays silent, leaves the native tree alone, and `/vim-tree` says why. Chunks are located by content, so renamed files (`chunk-44DLKSKE.js` -> `chunk-ZKNSXGL5.js`) are fine.
264
224
 
265
225
  ## Troubleshooting
266
226
 
267
- **`/vim-tree` says "not applied".** Pi's internals changed in a way the extension does not recognise. Update Pi and reload; if it still fails, the reason is printed by `/vim-tree`.
227
+ **`/vim-tree` says "not applied".** The internals changed in a way the extension does not recognise. Update Pi and reload; the reason is printed either way.
268
228
 
269
- **The keys do nothing.** The extension is off (`/vim-tree on`), or the tree does not have keyboard focus. Native tree keys keep working in both cases.
229
+ **The keys do nothing.** The extension is off (`/vim-tree on`), or the tree does not have focus. Native keys work in both cases.
270
230
 
271
- **The tree looks shorter than before.** The list height is fixed at 60% of the terminal (30 rows max) so that folding and filtering never make the panel jump. Resize the terminal to get more rows.
231
+ **The tree looks shorter than before.** Fixed height - 60% of the terminal, 30 rows max. Resize the terminal.
272
232
 
273
- **The tree shows a lot of `remote-pi` rows.** Those are custom messages the remote-pi package appends to the session history, one per rename. Pi's tree filter has no way to hide custom messages.
233
+ **`ctrl+f` does nothing.** The preview is closed, too narrow, or its body fits on one screen - those four keys only scroll the preview. Page the list with `f` / `b` or `u` / `d`.
274
234
 
275
- ## Releasing
235
+ **The tree opens with a filter I did not pick.** That is the remembered mode. Change `treeFilterMode` in `/settings` (it wins and resyncs), or delete `vim-tree.json` from the agent directory.
276
236
 
277
- The package is published from this directory:
237
+ **The tree shows a lot of `remote-pi` rows.** Those are custom messages the remote-pi package appends on every rename. Pi's filter has no way to hide custom messages.
278
238
 
279
- ```bash
280
- npm publish --access public
281
- ```
282
-
283
- Publishing needs a second factor. Use the code from your authenticator app, or the browser confirmation flow - do **not** use a recovery code: npm treats that as a security-sensitive action and can suspend the account.
239
+ **The slash command shows up as `/vim-tree:1` and `/vim-tree:2`.** Two copies are loaded - Pi appends `:1` / `:2` when a command name is registered twice, and the `[u]` / `[p]` / `[t]` tag tells you the scope. The copy that loaded last owns the patch, so `/vim-tree off` on the other one only disables itself. Keep one source: `pi list`, `pi remove <source>`, `~/.pi/agent/extensions/`, the `extensions` key in settings. `/vim-tree` warns when it detects another copy.
284
240
 
285
- For unattended releases, configure **trusted publishing** (OpenID Connect) on the npm package and point it at a GitHub Actions workflow. That removes the need for tokens entirely.
241
+ **The preview shows raw Markdown.** The theme was unavailable at render time, so it fell back to plain text. Restarting Pi re-initialises the theme; if it still happens, `/vim-tree` and the Pi log say why.
286
242
 
287
243
  ## Differences from Vim
288
244
 
289
- These are deliberate:
245
+ Deliberate:
290
246
 
291
247
  | Behaviour | Vim | pi-vim-tree |
292
248
  | --- | --- | --- |
293
- | `g0` | Go to column 0 | Jumps to the session's active branch - a tree has no columns, so Vim's `g0` has nothing to do here |
249
+ | `g0` | Go to column 0 | Jumps to the session's active branch - a tree has no columns |
294
250
  | `zm` / `zr` | Reset manually closed folds | Manual folds survive |
295
251
  | `zm` | Decrements a counter, so closing several levels takes several presses | Steps one level immediately |
296
252
  | Folding the root | Not possible | Falls back to folding the root when a chain has no branch point |
297
- | Search scope | Searches the whole buffer, including hidden lines | Searches the visible rows only |
253
+ | Search scope | Whole buffer, including hidden lines | Visible rows only |
298
254
  | `zX` / `zE` | Operate on manually closed folds | Not implemented - the tree has a single kind of fold |
299
- | Mark names | `a`-`z`, `A`-`Z` (digits are numbered-buffer marks) | The same 62 names, and `m0`-`m9` set marks too |
255
+ | Mark names | `a`-`z`, `A`-`Z` (digits are numbered buffers) | The same 62 names, and `m0`-`m9` set marks too |
256
+ | `ctrl+f` / `ctrl+b` | Scroll the buffer a page | Scroll the side preview; the list pages with `f` / `b` |
257
+ | `ctrl+u` / `ctrl+d` | Scroll the buffer half a page | Scroll the side preview; the list pages with `u` / `d` |
258
+ | Filter mode | N/A | Remembered across sessions in `vim-tree.json` |
259
+
260
+ ## Releasing
261
+
262
+ ```bash
263
+ npm publish --access public
264
+ ```
265
+
266
+ Bump `version` in `package.json` and add a matching `## [x.y.z]` heading to `CHANGELOG.md` first - Pi shows those entries to users after an update.
267
+
268
+ Publishing needs a second factor: use the authenticator app or the browser confirmation, **not** a recovery code (npm treats that as security-sensitive and can suspend the account). For unattended releases, configure trusted publishing (OIDC) on the package and point it at a GitHub Actions workflow.
269
+
270
+ Publishing from a directory without a git repository is fine: no `gitHead`, no provenance, no repository link on the npm page, and every release is a manual `npm login` plus 2FA. The TypeScript source ships in the tarball, so users can read exactly what runs.
271
+
272
+ Verify the artifact without installing it:
273
+
274
+ ```bash
275
+ pi -e npm:pi-vim-tree
276
+ ```
300
277
 
301
278
  ## Development
302
279
 
303
- The extension is a single file with no build step. `npm` is only needed to publish it as a package.
280
+ The extension is a single file with no build step; `npm` is only needed to publish.
281
+
282
+ Pick **one** source to load it. Loading the same extension twice is what produces `/vim-tree:1` / `:2`, and the copies then fight over the patch.
304
283
 
305
- The test suite drives the **real** Pi `TreeSelectorComponent`, loaded from the installed bundle, and feeds it real key bytes:
284
+ | Goal | Command | Scope tag |
285
+ | --- | --- | --- |
286
+ | One-off run | `pi -e ./extensions/vim-tree.ts` | `[t]` |
287
+ | Hot reload with `/reload` | link or copy into `~/.pi/agent/extensions/` | `[u]` |
288
+ | Keep the file where it is | add the path to `extensions` in `~/.pi/agent/settings.json` | `[u]` |
289
+ | As a package | `pi install ./this-dir` | `[u]` |
290
+
291
+ The tag is what Pi prints in autocomplete: `u` = user, `p` = project, `t` = temporary. A symlink keeps one copy of the file while `/reload` still sees edits:
306
292
 
307
293
  ```bash
308
- ./test/setup.sh # 把已安装的 pi 里的 node_modules 链过来(裸 node 需要能 import pi-tui)
309
- npm test
294
+ ln -sfn "$PWD/extensions/vim-tree.ts" ~/.pi/agent/extensions/vim-tree.ts
310
295
  ```
311
296
 
312
- It asserts on the visible rows, the selected row, the counters in the title bar, the fold markers, the jump list and the marks. A failing assertion prints the actual and expected values, and the exit code is non-zero.
297
+ ### `npm install` is never needed
298
+
299
+ Everything the extension imports comes from Pi; `npm install` has nothing to install and replaces the links `test/setup.sh` creates (re-run it afterwards). The links are per package inside a real `node_modules/@earendil-works` directory on purpose: an earlier version linked the whole scope at Pi's own `node_modules`, and a stray `npm install` then resolved the peers through that link and pruned Pi's packages as "extraneous", leaving Pi unable to start.
300
+
301
+ ### Tests
302
+
303
+ ```bash
304
+ ./test/setup.sh # link Pi's node_modules so bare node can import pi-tui
305
+ npm test
306
+ ```
313
307
 
314
- The suite also covers the `/vim-tree off` path: after turning the extension off, the tree must render byte for byte like a tree that was never patched.
308
+ The suite drives the **real** `TreeSelectorComponent` from the installed bundle with real key bytes, and asserts on visible rows, the selected row, the title-bar counters, fold markers, the jump list and the marks. It covers `/vim-tree off` (the tree must render byte for byte like one never patched) and loads two copies on purpose to check that a stale copy's `off` cannot tear down the active patch. Re-run `setup.sh` after upgrading Pi.
@@ -7,11 +7,21 @@
7
7
  * - `ctrl+o` / `ctrl+i`(=Tab):跳转栈后退 / 前进(vim 的 jump list)
8
8
  * - `ctrl+h`(或 f4) :开关右栏预览
9
9
  * - `ctrl+e` / `ctrl+y` :预览内容上下翻一行
10
- * - `ctrl+f` / `ctrl+b` :列表翻整页
11
- * - `u` / `d`(以及 `ctrl+u` / `ctrl+d`):列表翻半页(上 / 下)
10
+ * - `ctrl+u` / `ctrl+d` :预览内容上下翻半页
11
+ * - `ctrl+f` / `ctrl+b` :预览内容上下翻整页
12
+ * (预览这六个键只动右栏;预览关着 / 内容不足一屏就吞掉,不动列表、不落回原生)
13
+ * - `u` / `d` :列表翻半页(上 / 下)
14
+ * - `f` / `b` :列表翻整页(less 手感)
12
15
  * - `ctrl+l` :清掉搜索词和命中高亮
13
16
  * - `L` / `T` :标签编辑 / 标签时间戳(只认大写,小写让给动作键)
14
17
  * - `q` :关掉树(原生只有 esc 能关;vim 的 help/preview 窗口也是 q)
18
+ * - 过滤模式(gt/gl/gu/ga/gd)会被记住:退出 /tree 再进、甚至下次启动都还是上次那个模式
19
+ * (存 agent 目录的 vim-tree.json;`/settings` 里改 `treeFilterMode` 时以设置项为准)
20
+ * - 鼠标滚轮 :左栏滚列表(按行移光标)、右栏滚预览(按行滑窗);
21
+ * 事件被吞掉,不会漏给下层的 chat 正文。只接管滚轮,点击 / 拖拽原样还给原生。
22
+ * - 进树的那个键 :在树里**再按一次**就关(开 / 关同一个键)。
23
+ * 键位不写死 —— 读 pi 的 `app.session.tree`(keybindings.json 里配什么就是什么),
24
+ * 没配就永远不命中。注意:老终端里 ctrl+i 与 Tab 同字节,配成 ctrl+i 时 Tab 也会关树。
15
25
  * - `z` 家族按 vim 折叠语义走:`zc/zo/za` 收/展/切换,`zO/zC` 整棵子树收/展,
16
26
  * `zm/zr` 收/放一层,`zM/zR` 全收/全展,`zj/zk` 跳到下一个/上一个折痕,
17
27
  * `zA` 递归切换(折着就整棵展开,展开就整棵收起),
@@ -22,6 +32,9 @@
22
32
  * 2. 布局:列表高度固定(fzf 风格 `height: 0.6`,上限 30 行),
23
33
  * 内容变少/折叠/过滤都只在框内变化,**整个框不伸缩、不跳**。
24
34
  * 3. 预览:fzf `--preview-window right:55%` 风格——树在左,选中项的完整正文在右;
35
+ * 正文交给 pi 自己的 `Markdown` 组件 + `getMarkdownTheme()` 渲染,所以标题、列表、
36
+ * 引用、代码块的**语法高亮**跟消息正文一模一样(同一套主题 token、同一个 highlight.js)。
37
+ * 预览只滑窗(ctrl+e/y 逐行),不整框滚动;
25
38
  * 因为列表高度固定、预览只占右半,所以开关预览不产生任何高度重排。
26
39
  *
27
40
  * 界面上全是英文;折叠层级(Fold x/y)和匹配计数(Match x/y)紧跟在
@@ -73,12 +86,13 @@
73
86
  * (类原型上的 handleInput/render、树实例上的 applyFilter、搜索状态),不留残留。
74
87
  */
75
88
 
76
- import { Container, Input, decodeKittyPrintable, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
77
- import { existsSync, readdirSync, readFileSync } from "node:fs";
89
+ import { Container, Input, Markdown, decodeKittyPrintable, getKeybindings, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
90
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
78
91
  import { homedir } from "node:os";
79
92
  import { dirname, join } from "node:path";
80
93
  import { pathToFileURL } from "node:url";
81
94
 
95
+ import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
82
96
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
83
97
 
84
98
  // ---------------------------------------------------------------- 布局常量
@@ -108,7 +122,7 @@ const MODE_SEARCH = "\x1b[48;5;84m\x1b[38;5;235m";
108
122
  const MODE_END = "\x1b[0m";
109
123
 
110
124
  /** 构建标记:/vim-tree 会把它显示出来,用来确认 /reload 之后跑的是不是新代码 */
111
- const BUILD = "2026-11-13 keys: h/l branch, u/d half page, q quit, L/T uppercase only";
125
+ const BUILD = "2026-11-18 keys: f/b list page, ctrl+f/b/u/d preview scroll, app.session.tree toggles the tree, wheel scrolls";
112
126
 
113
127
  const STATE = {
114
128
  enabled: process.env.PI_VIM_TREE !== "0",
@@ -117,9 +131,12 @@ const STATE = {
117
131
  patched: false,
118
132
  notice: "",
119
133
  warned: false,
134
+ tookOver: false, // 打补丁时发现已经有人占了:说明同一份扩展被加载了两遍
120
135
  treeList: undefined as any,
121
136
  tui: undefined as any,
122
137
  marks: new Map<string, string>(), // vim 的标记:名字 → 行 id(跨 /tree 开关都留着)
138
+ // 记住的过滤模式:{ mode: 用户上一次选的, initial: 那一轮 pi settings 里的值 }
139
+ filter: undefined as { mode?: string; initial?: string } | undefined,
123
140
  };
124
141
 
125
142
  // ---------------------------------------------------------------- 补丁登记
@@ -655,9 +672,83 @@ function setFilter(treeList: any, mode: string): void {
655
672
  treeList.applyFilter();
656
673
  treeList.__vtCount = 0;
657
674
  treeList.__vtPendingG = 0;
675
+ rememberFilter(mode);
658
676
  }
659
677
 
660
- /** 翻屏:factor=1 整页、0.5 半页;vim 的 ctrl+f/b、ctrl+u/d */
678
+ /**
679
+ * 过滤模式的记忆(gt/gl/gu/ga/gd 选的那个)。
680
+ * pi 自己只在打开树的时候把 settings 里的 `treeFilterMode` 传进来,树里改了不会回写;
681
+ * 所以由扩展记:同一次运行内存里记,跨会话落在 agent 目录的 `vim-tree.json`。
682
+ * `/settings` 里改过 `treeFilterMode`(打开树时传进来的初始值变了)→ 以设置项为准,并把记忆同步过去,
683
+ * 不然记忆会永远盖住设置面板。
684
+ */
685
+ function filterStateFile(): string {
686
+ return join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "vim-tree.json");
687
+ }
688
+
689
+ function filterMemory(): { mode?: string; initial?: string } {
690
+ if (!STATE.filter) {
691
+ try {
692
+ const raw = JSON.parse(readFileSync(filterStateFile(), "utf8")) as any;
693
+ STATE.filter = {
694
+ mode: typeof raw?.treeFilterMode === "string" ? raw.treeFilterMode : undefined,
695
+ initial: typeof raw?.treeFilterInitial === "string" ? raw.treeFilterInitial : undefined,
696
+ };
697
+ } catch {
698
+ STATE.filter = {};
699
+ }
700
+ }
701
+ return STATE.filter;
702
+ }
703
+
704
+ function saveFilterMemory(): void {
705
+ const memory = filterMemory();
706
+ try {
707
+ mkdirSync(dirname(filterStateFile()), { recursive: true });
708
+ writeFileSync(
709
+ filterStateFile(),
710
+ `${JSON.stringify({ treeFilterMode: memory.mode, treeFilterInitial: memory.initial }, null, 2)}\n`,
711
+ );
712
+ } catch (error) {
713
+ warnOnce(`could not save filter preference: ${(error as Error)?.message ?? String(error)}`);
714
+ }
715
+ }
716
+
717
+ /** 用户在树里选了新模式 → 记下来(值没变就不写盘) */
718
+ function rememberFilter(mode: string): void {
719
+ const memory = filterMemory();
720
+ if (memory.mode === mode) return;
721
+ memory.mode = mode;
722
+ saveFilterMemory();
723
+ }
724
+
725
+ /** 新树第一次露面:把记住的模式套上去(每棵树只做一次) */
726
+ function syncRememberedFilter(treeList: any): void {
727
+ if (treeList.__vtFilterSync) return;
728
+ treeList.__vtFilterSync = true;
729
+ const memory = filterMemory();
730
+ const initial = String(treeList.filterMode ?? "default");
731
+ if (!memory.initial) {
732
+ // 第一次运行:拿 pi 传进来的(settings 的 treeFilterMode)当基准
733
+ memory.mode = memory.mode ?? initial;
734
+ memory.initial = initial;
735
+ saveFilterMemory();
736
+ return;
737
+ }
738
+ if (initial !== memory.initial) {
739
+ // /settings 里改过 → 设置项优先,记忆跟着同步
740
+ memory.initial = initial;
741
+ memory.mode = initial;
742
+ saveFilterMemory();
743
+ return;
744
+ }
745
+ if (memory.mode && memory.mode !== initial) {
746
+ treeList.filterMode = memory.mode;
747
+ treeList.applyFilter();
748
+ }
749
+ }
750
+
751
+ /** 翻屏:factor=1 整页、0.5 半页;列表的 f/b、u/d */
661
752
  function scrollLines(treeList: any, factor: number): boolean {
662
753
  const total = treeList.filteredNodes?.length ?? 0;
663
754
  if (total === 0) return false;
@@ -678,6 +769,19 @@ function clearSearchResults(treeList: any): void {
678
769
  treeList.applyFilter();
679
770
  }
680
771
 
772
+ /**
773
+ * 进树的那个键(keybindings.json 里的 `app.session.tree`):树里再按一次就退出(开 / 关同一个键)。
774
+ * 不写死键位,直接问 pi 装进 pi-tui 的那个 KeybindingsManager;**没配就永远不命中**。
775
+ * 注意:老终端里 ctrl+i 和 Tab 是同一个字节,所以真把 app.session.tree 配成 ctrl+i 时,Tab 也会关树。
776
+ */
777
+ function matchesTreeKey(data: string): boolean {
778
+ try {
779
+ return getKeybindings().matches(data, "app.session.tree");
780
+ } catch {
781
+ return false; // 拿不到键位管理器(非交互场景 / 版本不合)就当没配
782
+ }
783
+ }
784
+
681
785
  /** ctrl+l:打开标签编辑(等价于原生 app.tree.editLabel) */
682
786
  function openLabelEditor(treeList: any): boolean {
683
787
  const flat = treeList.filteredNodes?.[treeList.selectedIndex];
@@ -936,35 +1040,81 @@ function gotoRow(treeList: any, row: number): void {
936
1040
 
937
1041
  // ---------------------------------------------------------------- 预览
938
1042
 
939
- /** 选中项的完整内容换行包装;返回总行数便于翻页 */
940
- function wrapPreview(treeList: any, width: number): { lines: string[]; total: number } {
1043
+ /** 纯文本换行(没有 markdown 可用时的退路;也可能是 pi 已经染好色的单行摘要) */
1044
+ function wrapPlain(text: string, width: number): string[] {
1045
+ const lines: string[] = [];
1046
+ if (!text) return lines;
1047
+ for (const rawLine of text.split("\n")) {
1048
+ const line = rawLine.trimEnd();
1049
+ lines.push(...(line ? wrapTextWithAnsi(line, width) : [""]));
1050
+ }
1051
+ return lines;
1052
+ }
1053
+
1054
+ /**
1055
+ * 预览走 pi 自己的 Markdown 渲染器:主题、代码块语法高亮(highlight.js)都跟消息正文一模一样。
1056
+ * 每个 treeList 只留一个实例,选中项变了才 setText,宽度变化由组件内部重排。
1057
+ * 主题没初始化(裸 node 之类)时返回 undefined,由调用方退回纯文本。
1058
+ */
1059
+ function renderMarkdown(
1060
+ treeList: any,
1061
+ node: any,
1062
+ text: string,
1063
+ width: number,
1064
+ ): { lines: string[]; total: number; plain: boolean } | undefined {
1065
+ const holder = (treeList.__vtMd ??= { failed: false, key: undefined, md: undefined });
1066
+ if (holder.failed) return undefined;
1067
+ if (!holder.md) {
1068
+ try {
1069
+ holder.md = new Markdown("", 0, 0, getMarkdownTheme());
1070
+ } catch {
1071
+ holder.failed = true;
1072
+ return undefined;
1073
+ }
1074
+ }
1075
+ const key = `${node?.entry?.id ?? ""}:${text.length}`;
1076
+ if (holder.key !== key) {
1077
+ holder.md.setText(text);
1078
+ holder.key = key;
1079
+ }
1080
+ const lines: string[] = holder.md.render(Math.max(1, width));
1081
+ return { lines, total: lines.length, plain: false };
1082
+ }
1083
+
1084
+ /**
1085
+ * 选中项的完整内容;返回总行数便于翻页。
1086
+ * `plain=true` 表示内容已经是带 ANSI 的纯文本(此时才值得再染搜索词)。
1087
+ */
1088
+ function wrapPreview(treeList: any, width: number): { lines: string[]; total: number; plain: boolean } {
941
1089
  const node = treeList.filteredNodes?.[treeList.selectedIndex]?.node;
942
- if (!node) return { lines: [], total: 0 };
1090
+ if (!node) return { lines: [], total: 0, plain: true };
943
1091
 
944
- let text = "";
1092
+ // 1) 正文(markdown 原文)→ 交给 pi 的 Markdown 渲染
1093
+ let raw = "";
945
1094
  try {
946
- if (typeof treeList.getEntryCopyText === "function") text = String(treeList.getEntryCopyText(node) ?? "");
1095
+ if (typeof treeList.getEntryCopyText === "function") raw = String(treeList.getEntryCopyText(node) ?? "");
947
1096
  } catch {
948
- text = "";
1097
+ raw = "";
949
1098
  }
950
- if (!text.trim()) {
951
- try {
952
- if (typeof treeList.getEntryDisplayText === "function") {
953
- text = String(treeList.getEntryDisplayText(node, false) ?? "");
954
- }
955
- } catch {
956
- text = "";
957
- }
1099
+ raw = raw.replace(/\r/g, "").trim();
1100
+ if (raw) {
1101
+ const rendered = renderMarkdown(treeList, node, raw, width);
1102
+ if (rendered) return rendered;
1103
+ const lines = wrapPlain(raw, width);
1104
+ return { lines, total: lines.length, plain: true };
958
1105
  }
959
- text = text.replace(/\r/g, "").trim();
960
- if (!text) return { lines: [], total: 0 };
961
1106
 
962
- const lines: string[] = [];
963
- for (const rawLine of text.split("\n")) {
964
- const line = rawLine.trimEnd();
965
- lines.push(...(line ? wrapTextWithAnsi(line, width) : [""]));
1107
+ // 2) 没有正文 → 退回原生的一行摘要(已经带 ANSI,不再二次渲染)
1108
+ let text = "";
1109
+ try {
1110
+ if (typeof treeList.getEntryDisplayText === "function") {
1111
+ text = String(treeList.getEntryDisplayText(node, false) ?? "");
1112
+ }
1113
+ } catch {
1114
+ text = "";
966
1115
  }
967
- return { lines, total: lines.length };
1116
+ const lines = wrapPlain(text.replace(/\r/g, "").trim(), width);
1117
+ return { lines, total: lines.length, plain: true };
968
1118
  }
969
1119
 
970
1120
  /** 预览翻页状态:选中项变化时归零,偏移在渲染时按内容长度夹紧 */
@@ -977,6 +1127,29 @@ function previewState(treeList: any, entryId: string | undefined): { id: string
977
1127
  return state;
978
1128
  }
979
1129
 
1130
+ /**
1131
+ * 预览当前能不能滚:预览开着、且内容超出一屏。
1132
+ * page/total 是上一次渲染留下的(列表高度固定,所以这就是真实页大小)。
1133
+ */
1134
+ function previewScrollMeta(treeList: any): { page: number; total: number } | undefined {
1135
+ const info: { page: number; total: number } | undefined = treeList.__vtPreviewInfo;
1136
+ if (!STATE.preview || !info || info.page <= 0 || info.total <= info.page) return undefined;
1137
+ return info;
1138
+ }
1139
+
1140
+ /**
1141
+ * 滚预览 N 行(正数往下):一行是 ctrl+e/y,半页/整页由调用方按 previewScrollMeta().page 换算。
1142
+ * 返回 false = 预览不可滚(关着 / 内容不足一屏),调用方自己决定落回哪里。
1143
+ */
1144
+ function scrollPreview(treeList: any, lines: number): boolean {
1145
+ const info = previewScrollMeta(treeList);
1146
+ if (!info) return false;
1147
+ const state = previewState(treeList, selectedId(treeList));
1148
+ const maxOffset = Math.max(0, info.total - info.page);
1149
+ state.offset = Math.max(0, Math.min(maxOffset, state.offset + lines));
1150
+ return true;
1151
+ }
1152
+
980
1153
 
981
1154
  // ---------------------------------------------------------------- 折叠(vim z 家族)
982
1155
 
@@ -1598,7 +1771,7 @@ function customizeChrome(treeList: any, out: string[], width: number): void {
1598
1771
  const items = [
1599
1772
  "j/k move",
1600
1773
  "u/d half page",
1601
- "ctrl+f/b page",
1774
+ "f/b page",
1602
1775
  "ctrl+l clear search",
1603
1776
  "ctrl+o/i jump back/fwd",
1604
1777
  "zc/zo/za/zO/zC/zA folds",
@@ -1612,7 +1785,7 @@ function customizeChrome(treeList: any, out: string[], width: number): void {
1612
1785
  "h/l branch · g0 current",
1613
1786
  "ctrl+j/k branch",
1614
1787
  "gt/gl/gu/ga/gd filters",
1615
- "ctrl+h ctrl+e/y preview",
1788
+ "ctrl+h preview · ctrl+e/y/u/d/f/b scroll",
1616
1789
  "L label",
1617
1790
  "T label time",
1618
1791
  "/ search",
@@ -2021,6 +2194,8 @@ function layoutScreen(component: any, lines: string[], width: number, hardMax: n
2021
2194
  const leftWidth = Math.max(24, Math.round(width * (1 - PREVIEW_SPLIT)));
2022
2195
  const rightWidth = width - leftWidth - 1;
2023
2196
  const canSplit = previewEnabled && rightWidth >= 12;
2197
+ // 鼠标滚轮按这一列分左右栏(见 vtHandleMouse)
2198
+ treeList.__vtSplitCol = canSplit ? leftWidth : undefined;
2024
2199
 
2025
2200
  let previewLines: string[] = [];
2026
2201
  treeList.__vtPreviewInfo = { page: 0, total: 0 };
@@ -2035,12 +2210,13 @@ function layoutScreen(component: any, lines: string[], width: number, hardMax: n
2035
2210
  treeList.__vtPreviewInfo = { page, total: wrapped.total };
2036
2211
 
2037
2212
  const previewTokens = activeSearch(treeList).query.trim().toLowerCase().split(/\s+/).filter(Boolean);
2213
+ // 搜索词染色只对纯文本做:markdown 行里已经有主题色,再塞 ANSI 会把标记打乱
2038
2214
  const visible = wrapped.lines
2039
2215
  .slice(state.offset, state.offset + page)
2040
- .map((line) => (previewTokens.length > 0 ? highlightTokens(line, previewTokens, false) : line));
2216
+ .map((line) => (wrapped.plain && previewTokens.length > 0 ? highlightTokens(line, previewTokens, false) : line));
2041
2217
  const label =
2042
2218
  wrapped.total > page
2043
- ? `preview ${state.offset + 1}-${Math.min(wrapped.total, state.offset + page)}/${wrapped.total} ctrl+d/u half · ctrl+e/y line`
2219
+ ? `preview ${state.offset + 1}-${Math.min(wrapped.total, state.offset + page)}/${wrapped.total} ctrl+d/u half · ctrl+f/b page · ctrl+e/y line`
2044
2220
  : "preview (all)";
2045
2221
  previewLines = [`${DIM}${label}${RESET}`, ...visible];
2046
2222
  } else if (previewEnabled) {
@@ -2130,11 +2306,23 @@ function vtHandleInner(component: any, data: string, forward: (data: string) =>
2130
2306
  }
2131
2307
 
2132
2308
  ensureSearch(treeList);
2309
+ syncRememberedFilter(treeList);
2133
2310
 
2134
2311
  if (process.env.PI_VIM_TREE_DEBUG === "2") console.error(`[vim-tree] key ${JSON.stringify(data)}`);
2135
2312
 
2136
2313
  const mode = modeOf(treeList);
2137
2314
 
2315
+ // 进树的那个键(pi 的 `app.session.tree`,keybindings.json 里配什么就是什么):在树里再按一次 = 关树。
2316
+ // 不写死键位:直接问 pi 装进 pi-tui 的那个 KeybindingsManager(用户改键 / `/reload` 都会跟着变);
2317
+ // 没配(默认空列表)就永远不命中。
2318
+ if (mode === "normal" && matchesTreeKey(data)) {
2319
+ treeList.__vtCount = 0;
2320
+ treeList.__vtPendingG = 0;
2321
+ treeList.__vtPendingZ = 0;
2322
+ if (typeof treeList.onCancel === "function") treeList.onCancel();
2323
+ return;
2324
+ }
2325
+
2138
2326
  // ---- 下面这些是指令键,只在 normal 生效;search 模式是纯输入(像 chat 输入框)
2139
2327
  if (mode === "normal") {
2140
2328
  // esc 在 normal 下不拦:原样交给原生(原生 esc = 取消/关树)。
@@ -2159,7 +2347,8 @@ function vtHandleInner(component: any, data: string, forward: (data: string) =>
2159
2347
  return;
2160
2348
  }
2161
2349
 
2162
- // ctrl+f / ctrl+b 翻整页,u / d(以及 ctrl+u / ctrl+d)翻半页(vim 的翻屏)
2350
+ // ctrl+f / ctrl+b 整页、ctrl+u / ctrl+d 半页:**只滚预览**(less / vim 的翻屏手感)。
2351
+ // 预览关着或内容不足一屏就吞掉 —— 不落回列表(列表翻屏是 u/d 和 f/b),也不放进原生过滤器键。
2163
2352
  if (
2164
2353
  matchesKey(data, "ctrl+f") ||
2165
2354
  matchesKey(data, "ctrl+b") ||
@@ -2168,7 +2357,10 @@ function vtHandleInner(component: any, data: string, forward: (data: string) =>
2168
2357
  ) {
2169
2358
  const down = matchesKey(data, "ctrl+f") || matchesKey(data, "ctrl+d");
2170
2359
  const half = matchesKey(data, "ctrl+u") || matchesKey(data, "ctrl+d");
2171
- scrollLines(treeList, (down ? 1 : -1) * (half ? 0.5 : 1));
2360
+ const meta = previewScrollMeta(treeList);
2361
+ if (!meta) return;
2362
+ const step = Math.max(1, Math.round(meta.page * (half ? 0.5 : 1)));
2363
+ scrollPreview(treeList, down ? step : -step);
2172
2364
  return;
2173
2365
  }
2174
2366
 
@@ -2180,17 +2372,7 @@ function vtHandleInner(component: any, data: string, forward: (data: string) =>
2180
2372
 
2181
2373
  // 预览滚动:ctrl+e/y 一行;预览不可滚时吞掉(别掉进原生的过滤器键)
2182
2374
  if (matchesKey(data, "ctrl+e") || matchesKey(data, "ctrl+y")) {
2183
- const info: { page: number; total: number } | undefined = treeList.__vtPreviewInfo;
2184
- const canScroll = STATE.preview && info !== undefined && info.page > 0 && info.total > info.page;
2185
- if (!canScroll) return;
2186
-
2187
- const down = matchesKey(data, "ctrl+e");
2188
- const step = 1;
2189
-
2190
- const selectedId = treeList.filteredNodes?.[treeList.selectedIndex]?.node?.entry?.id;
2191
- const state = previewState(treeList, selectedId);
2192
- state.offset += down ? step : -step;
2193
- if (state.offset < 0) state.offset = 0;
2375
+ if (!scrollPreview(treeList, matchesKey(data, "ctrl+e") ? 1 : -1)) return;
2194
2376
  return;
2195
2377
  }
2196
2378
 
@@ -2423,7 +2605,7 @@ function vtHandleInner(component: any, data: string, forward: (data: string) =>
2423
2605
  return;
2424
2606
  }
2425
2607
 
2426
- // u / d:翻半页(vim 的 ctrl+u / ctrl+d),和 ctrl+u / ctrl+d 是同一个动作
2608
+ // u / d:列表翻半页(vim 的 ctrl+u / ctrl+d 手感,但 ctrl 那组让给预览了)
2427
2609
  if (data === "u" || data === "d") {
2428
2610
  scrollLines(treeList, data === "d" ? 0.5 : -0.5);
2429
2611
  treeList.__vtCount = 0;
@@ -2431,6 +2613,14 @@ function vtHandleInner(component: any, data: string, forward: (data: string) =>
2431
2613
  return;
2432
2614
  }
2433
2615
 
2616
+ // f / b:列表翻整页(less 手感;ctrl+f/b 只滚预览)
2617
+ if (data === "f" || data === "b") {
2618
+ scrollLines(treeList, data === "f" ? 1 : -1);
2619
+ treeList.__vtCount = 0;
2620
+ treeList.__vtPendingG = 0;
2621
+ return;
2622
+ }
2623
+
2434
2624
  // 一页 = 原生 pgup/pgdn
2435
2625
  if (matchesKey(data, "pageDown") || matchesKey(data, "pageUp")) {
2436
2626
  treeList.__vtCount = 0;
@@ -2484,6 +2674,43 @@ function vtHandleInner(component: any, data: string, forward: (data: string) =>
2484
2674
  return;
2485
2675
  }
2486
2676
 
2677
+ /**
2678
+ * 鼠标滚轮:**右栏滚预览、左栏滚列表**(pi 的鼠标事件给的是组件内坐标,按上次 render 的宽度分栏)。
2679
+ * 列表按 wheelDelta 行移动光标(跟 j/k 一样,不整屏跳);预览按行滚并夹在内容范围内。
2680
+ * 其余事件(点击 / 拖拽 / 按下)原样还给原生 —— 只接管滚轮。
2681
+ */
2682
+ function vtHandleMouse(component: any, event: any, forward: (event: any) => unknown): unknown {
2683
+ const treeList = component?.treeList;
2684
+ if (!treeList || event?.type !== "wheel") return forward(event);
2685
+ // 标签编辑框开着时整套交给原生(跟键盘那边一个规矩)
2686
+ if (component.labelInput) return forward(event);
2687
+ const delta = Number(event?.wheelDelta ?? 0);
2688
+ if (!Number.isFinite(delta) || delta === 0) return forward(event);
2689
+
2690
+ const width = Number(treeList.__vtWidth ?? event?.width ?? 0);
2691
+ const previewEnabled = STATE.preview && !component.labelInput;
2692
+ // 分栏线:上次 render 记下的那个列(跟画出来的一致),没有就现算
2693
+ const splitCol = Number(treeList.__vtSplitCol ?? Math.max(24, Math.round(width * (1 - PREVIEW_SPLIT))));
2694
+ const overPreview = previewEnabled && event.x > splitCol && scrollPreview(treeList, delta);
2695
+
2696
+ if (process.env.PI_VIM_TREE_DEBUG === "2") {
2697
+ console.error(
2698
+ `[vim-tree] wheel x=${event.x} y=${event.y} delta=${delta} split=${splitCol} width=${width} → ${overPreview ? "preview" : "list"}`,
2699
+ );
2700
+ }
2701
+
2702
+ if (overPreview) return { handled: true };
2703
+
2704
+ // 左栏(或预览关着 / 太窄没分栏):列表框里按滚轮行数移动光标
2705
+ const total = treeList.filteredNodes?.length ?? 0;
2706
+ if (total === 0) return { handled: true };
2707
+ const step = Math.max(1, Math.abs(delta));
2708
+ const next = (treeList.selectedIndex ?? 0) + (delta < 0 ? -step : step);
2709
+ treeList.selectedIndex = Math.max(0, Math.min(total - 1, next));
2710
+ treeList.__vtLogical = selectedId(treeList);
2711
+ return { handled: true };
2712
+ }
2713
+
2487
2714
  // ---------------------------------------------------------------- 补丁
2488
2715
 
2489
2716
  function patchClass(cls: any): void {
@@ -2497,12 +2724,18 @@ function patchClass(cls: any): void {
2497
2724
  const orig: OrigMethods =
2498
2725
  stored && typeof stored.handleInput === "function" && typeof stored.render === "function"
2499
2726
  ? stored
2500
- : { handleInput: proto.handleInput, render: proto.render };
2727
+ : { handleInput: proto.handleInput, render: proto.render, handleMouse: proto.handleMouse };
2501
2728
  proto.__vtOrig = orig;
2502
2729
  proto.__vtPatched = true;
2730
+ // 同一份扩展被加载两遍时(例如既装到 ~/.pi/agent/extensions/ 又用 `pi -e`),
2731
+ // 两个模块实例各自有一套 STATE,但只共用一个 prototype:后打的把先打的盖掉。
2732
+ // 用 owner 令牌记住“当前是谁在管”,旧的实例就不可能在 off 时把新的补丁拆掉。
2733
+ const owner = {};
2734
+ if (proto.__vtOwner) STATE.tookOver = true;
2735
+ proto.__vtOwner = owner;
2503
2736
 
2504
2737
  proto.handleInput = function handleInput(this: any, data: string): unknown {
2505
- if (!STATE.enabled) return orig.handleInput.call(this, data);
2738
+ if (!STATE.enabled || proto.__vtOwner !== owner) return orig.handleInput.call(this, data);
2506
2739
  // 标签编辑框开着的时候整套交给原生:它才知道怎么把按键喂给 LabelInput,
2507
2740
  // 我们接管了 handleInput 就得把这个分支还回去,否则标签打不进字。
2508
2741
  if (this.labelInput) return orig.handleInput.call(this, data);
@@ -2516,12 +2749,18 @@ function patchClass(cls: any): void {
2516
2749
  };
2517
2750
 
2518
2751
  proto.render = function render(this: any, width: number): string[] {
2519
- if (!STATE.enabled) return orig.render.call(this, width);
2752
+ if (!STATE.enabled || proto.__vtOwner !== owner) return orig.render.call(this, width);
2520
2753
 
2521
2754
  let hardMax = 0;
2522
2755
  try {
2523
2756
  const treeList = this.treeList;
2524
2757
  if (treeList) STATE.treeList = treeList;
2758
+ // 鼠标事件给的是“组件内坐标”,分栏位置得跟这次 render 用同一个宽度算
2759
+ if (treeList) treeList.__vtWidth = width;
2760
+ // 先把“原生过滤模式”记下来(off 时要还回去),再套记忆,顺序不能反
2761
+ if (treeList) ensureSearch(treeList);
2762
+ // 退出再进 = 新的 treeList:把用户上次选的过滤模式套回来
2763
+ if (treeList) syncRememberedFilter(treeList);
2525
2764
  if (treeList && typeof treeList.maxVisibleLines === "number") {
2526
2765
  ensureSearch(treeList);
2527
2766
  // 行号基准(未折叠的行清单):先算好,渲染中就不会改树状态
@@ -2552,10 +2791,30 @@ function patchClass(cls: any): void {
2552
2791
  }
2553
2792
  };
2554
2793
 
2794
+ proto.handleMouse = function handleMouse(this: any, event: any): unknown {
2795
+ if (!STATE.enabled || proto.__vtOwner !== owner) return orig.handleMouse?.call(this, event);
2796
+ STATE.treeList = this.treeList;
2797
+ try {
2798
+ return vtHandleMouse(this, event, (e: any) => orig.handleMouse?.call(this, e));
2799
+ } catch (error) {
2800
+ warnOnce(`mouse error, falling back to native: ${(error as Error)?.message ?? String(error)}`);
2801
+ return orig.handleMouse?.call(this, event);
2802
+ }
2803
+ };
2804
+
2555
2805
  STATE.patched = true;
2556
2806
  onDisable(() => {
2807
+ // 被后来的实例接管了:别去拆别人的补丁(否则两边都不工作)
2808
+ if (proto.__vtOwner !== owner) {
2809
+ STATE.patched = false;
2810
+ return;
2811
+ }
2812
+ proto.__vtOwner = undefined;
2557
2813
  proto.handleInput = orig.handleInput;
2558
2814
  proto.render = orig.render;
2815
+ // 原生没有 handleMouse:直接删掉,别留一个 undefined 占着
2816
+ if (orig.handleMouse) proto.handleMouse = orig.handleMouse;
2817
+ else delete proto.handleMouse;
2559
2818
  proto.__vtPatched = false;
2560
2819
  STATE.patched = false;
2561
2820
  restoreNativeTreeState(STATE.treeList);
@@ -2640,7 +2899,7 @@ export default function vimTreeExtension(pi: ExtensionAPI): void {
2640
2899
  }
2641
2900
 
2642
2901
  ctx.ui.notify(
2643
- `vim-tree: ${STATE.patched && STATE.enabled ? "on" : "off"} · build ${BUILD}${STATE.notice ? `(${STATE.notice})` : ""}`,
2902
+ `vim-tree: ${STATE.patched && STATE.enabled ? "on" : "off"} · build ${BUILD}${STATE.notice ? ` (${STATE.notice})` : ""}${STATE.tookOver ? " · another copy is also loaded (see /vim-tree:1, :2) - keep only one source" : ""}`,
2644
2903
  );
2645
2904
  },
2646
2905
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-vim-tree",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Vim-style folding, motion, jump list and marks for Pi's built-in /tree view.",
5
5
  "author": "ooostrich",
6
6
  "type": "module",