v0.0.29 e425dbb

slash_suggest.go RawHistoryFolder

1package modes
2
3import (
4	"sort"
5	"strings"
6
7	"github.com/patriceckhart/zot/internal/tui"
8)
9
10// slashCommand is one entry in the autocomplete popup. Header rows
11// (group dividers like "── extensions ───") are real entries
12// flagged with header=true; they render but aren't navigable.
13type slashCommand struct {
14	Name   string // with leading "/"
15	Desc   string
16	Header bool // true = visual divider, not selectable
17}
18
19// slashCancelsTurn reports whether the named slash command, when run
20// while a turn is in flight, requires the active turn to be cancelled
21// first. The destructive commands (those that mutate the transcript
22// or rebuild the agent) need a quiet state; the rest run alongside
23// the streaming response without trouble.
24func slashCancelsTurn(head string) bool {
25	switch head {
26	case "/clear", "/compact", "/logout", "/login", "/model":
27		return true
28	}
29	return false
30}
31
32// slashCatalog lists every slash command the interactive mode handles.
33// Keep in sync with runSlash().
34var slashCatalog = []slashCommand{
35	{Name: "/help", Desc: "show key bindings and commands"},
36	{Name: "/login", Desc: "log in via api key or subscription"},
37	{Name: "/logout", Desc: "clear a provider's credentials"},
38	{Name: "/model", Desc: "pick a model (or /model <id>)"},
39	{Name: "/sessions", Desc: "resume a previous session for this directory"},
40	{Name: "/jump", Desc: "scroll the chat to a previous turn (or /jump <text>)"},
41	{Name: "/btw", Desc: "side-chat that doesn't add to the main thread (saves tokens)"},
42	{Name: "/skills", Desc: "list discovered skills (SKILL.md files)"},
43	{Name: "/compact", Desc: "summarize and replace the transcript to free up context"},
44	{Name: "/lock", Desc: "confine tools to the current directory"},
45	{Name: "/unlock", Desc: "allow tools to touch paths outside this directory"},
46	{Name: "/clear", Desc: "clear the chat transcript"},
47	{Name: "/exit", Desc: "exit zot"},
48}
49
50// slashSuggester renders the popup that appears when the editor starts
51// with "/". It does not own any input state — the editor drives.
52type slashSuggester struct {
53	cursor int
54
55	// extra are commands contributed by extensions, refreshed each
56	// frame from the extension manager. Empty when no extensions
57	// have registered any. Sorted by name in SetExtra so map
58	// iteration order doesn't reshuffle the popup between frames.
59	extra []slashCommand
60
61	// lastMatches is the list shown in the most recent Render call.
62	// Up/Down read it so they know which indexes to skip across
63	// header rows.
64	lastMatches []slashCommand
65}
66
67// SetExtra updates the extension-contributed command list. Called
68// once per render with the live snapshot from the extension manager.
69// The list is sorted by name so the popup ordering stays stable
70// across redraws (Manager.Commands() iterates a map, which Go
71// randomises).
72func (s *slashSuggester) SetExtra(cmds []slashCommand) {
73	sorted := append([]slashCommand(nil), cmds...)
74	sort.Slice(sorted, func(i, j int) bool { return sorted[i].Name < sorted[j].Name })
75	s.extra = sorted
76}
77
78// allCatalog returns slashCatalog plus the current extra commands
79// (extension-registered) with a header divider between the two
80// groups. Extra entries are only kept if they don't collide with
81// a built-in name; the built-in always wins.
82func (s *slashSuggester) allCatalog() []slashCommand {
83	if len(s.extra) == 0 {
84		return slashCatalog
85	}
86	out := make([]slashCommand, 0, len(slashCatalog)+len(s.extra)+1)
87	out = append(out, slashCatalog...)
88	var kept []slashCommand
89	for _, c := range s.extra {
90		dup := false
91		for _, b := range slashCatalog {
92			if b.Name == c.Name {
93				dup = true
94				break
95			}
96		}
97		if !dup {
98			kept = append(kept, c)
99		}
100	}
101	if len(kept) > 0 {
102		out = append(out, slashCommand{Header: true, Name: "extensions"})
103		out = append(out, kept...)
104	}
105	return out
106}
107
108// looksLikeSlashCommand reports whether text is an attempt at a slash
109// command (valid or not). Returns true for things like "/foo" or
110// "/bar baz" but false for paths ("/Users/pat/...") and regexes
111// ("/foo.bar/") so those can be sent to the model as-is.
112//
113// The head after "/" must be a single simple word: only letters,
114// digits, hyphens, and underscores. That excludes paths (contain "/"),
115// regexes (contain "."), and URLs.
116func looksLikeSlashCommand(text string) bool {
117	text = strings.TrimSpace(text)
118	if len(text) < 2 || text[0] != '/' {
119		return false
120	}
121	head := text[1:]
122	if i := strings.IndexAny(head, " \t\n"); i >= 0 {
123		head = head[:i]
124	}
125	if head == "" {
126		return false
127	}
128	for _, r := range head {
129		if !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') &&
130			!(r >= '0' && r <= '9') && r != '-' && r != '_' {
131			return false
132		}
133	}
134	return true
135}
136
137// isKnownSlashCommand reports whether text's head matches a registered
138// slash command name in slashCatalog. Built-in only; extension
139// commands are looked up separately by the dispatcher (which
140// consults the extension manager).
141func isKnownSlashCommand(text string) bool {
142	text = strings.TrimSpace(text)
143	if text == "" || text[0] != '/' {
144		return false
145	}
146	head := text
147	if i := strings.IndexAny(text, " \t\n"); i >= 0 {
148		head = text[:i]
149	}
150	for _, c := range slashCatalog {
151		if c.Name == head {
152			return true
153		}
154	}
155	return false
156}
157
158func newSlashSuggester() *slashSuggester { return &slashSuggester{} }
159
160// matches returns the commands whose name has input as a prefix.
161// If input is just "/", everything is shown.
162func (s *slashSuggester) matches(input string) []slashCommand {
163	input = strings.TrimRight(input, " ")
164	if input == "" || !strings.HasPrefix(input, "/") {
165		return nil
166	}
167	// If there is a space, the user has moved past the command name.
168	if idx := strings.IndexByte(input, ' '); idx >= 0 {
169		return nil
170	}
171	var out []slashCommand
172	for _, c := range s.allCatalog() {
173		if c.Header {
174			// Headers ride along whenever there's at least one
175			// matching command from their group; we drop trailing
176			// orphan headers below.
177			out = append(out, c)
178			continue
179		}
180		if strings.HasPrefix(c.Name, input) {
181			out = append(out, c)
182		}
183	}
184	return pruneOrphanHeaders(out)
185}
186
187// pruneOrphanHeaders removes header rows that have no commands
188// after them (i.e. the next non-header is missing or another
189// header). Keeps the popup clean when the input filters out a whole
190// group.
191func pruneOrphanHeaders(in []slashCommand) []slashCommand {
192	out := make([]slashCommand, 0, len(in))
193	for i, c := range in {
194		if c.Header {
195			nextReal := false
196			for j := i + 1; j < len(in); j++ {
197				if !in[j].Header {
198					nextReal = true
199					break
200				}
201			}
202			if !nextReal {
203				continue
204			}
205		}
206		out = append(out, c)
207	}
208	return out
209}
210
211// clampCursor keeps the cursor inside the current match list and
212// nudges it past any header row so navigation never lands on one.
213func (s *slashSuggester) clampCursor(n int) {
214	if n <= 0 {
215		s.cursor = 0
216		return
217	}
218	if s.cursor < 0 {
219		s.cursor = 0
220	}
221	if s.cursor >= n {
222		s.cursor = n - 1
223	}
224}
225
226// Up / Down navigate the suggestion list, skipping header rows in
227// either direction so the cursor only ever lands on selectable
228// commands.
229func (s *slashSuggester) Up() {
230	s.skipHeader(-1)
231}
232func (s *slashSuggester) Down() {
233	s.skipHeader(+1)
234}
235
236// skipHeader moves the cursor by step, then keeps moving in the same
237// direction across header rows until it lands on a real command (or
238// hits the edge, in which case it bounces back to the nearest real
239// row).
240func (s *slashSuggester) skipHeader(step int) {
241	list := s.lastMatches
242	n := len(list)
243	if n == 0 {
244		return
245	}
246	s.cursor += step
247	for s.cursor >= 0 && s.cursor < n && list[s.cursor].Header {
248		s.cursor += step
249	}
250	if s.cursor < 0 {
251		// Bounce: find the first non-header from the top.
252		for i, c := range list {
253			if !c.Header {
254				s.cursor = i
255				return
256			}
257		}
258		s.cursor = 0
259	}
260	if s.cursor >= n {
261		// Bounce: find the last non-header.
262		for i := n - 1; i >= 0; i-- {
263			if !list[i].Header {
264				s.cursor = i
265				return
266			}
267		}
268		s.cursor = n - 1
269	}
270}
271
272// Active reports whether the popup is visible for the given input.
273func (s *slashSuggester) Active(input string) bool {
274	return len(s.matches(input)) > 0
275}
276
277// Selection returns the currently highlighted command for input, or "".
278// Headers are never returned even if the cursor index would point at
279// one; the cursor is moved forward to the next real command.
280func (s *slashSuggester) Selection(input string) string {
281	m := s.matches(input)
282	if len(m) == 0 {
283		return ""
284	}
285	s.clampCursor(len(m))
286	if m[s.cursor].Header {
287		for i := s.cursor + 1; i < len(m); i++ {
288			if !m[i].Header {
289				s.cursor = i
290				break
291			}
292		}
293	}
294	if m[s.cursor].Header {
295		return ""
296	}
297	return m[s.cursor].Name
298}
299
300// Render returns the popup lines or nil.
301func (s *slashSuggester) Render(input string, th tui.Theme, width int) []string {
302	m := s.matches(input)
303	if len(m) == 0 {
304		return nil
305	}
306	s.lastMatches = m
307	s.clampCursor(len(m))
308	// Snap cursor off any header (e.g. after a filter change put it on one).
309	if s.cursor >= 0 && s.cursor < len(m) && m[s.cursor].Header {
310		for i := s.cursor + 1; i < len(m); i++ {
311			if !m[i].Header {
312				s.cursor = i
313				break
314			}
315		}
316	}
317	var lines []string
318	for i, c := range m {
319		if c.Header {
320			// Breathing room around group dividers — a blank row
321			// before AND after makes the boundary read at a glance.
322			lines = append(lines, "")
323			rule := strings.Repeat("─", width)
324			label := "── " + c.Name + " "
325			if len(label) < width {
326				rule = label + strings.Repeat("─", width-len(label))
327			}
328			lines = append(lines, th.FG256(th.Muted, rule))
329			lines = append(lines, "")
330			continue
331		}
332		name := c.Name
333		if len(name) < 10 {
334			name = name + strings.Repeat(" ", 10-len(name))
335		}
336		plain := "  " + name + "  " + c.Desc
337		if i == s.cursor {
338			lines = append(lines, th.PadHighlight(plain, width))
339		} else {
340			lines = append(lines, th.FG256(th.Muted, plain))
341		}
342	}
343	// Blank row before the hint visually detaches it from the
344	// command list and groups it with its trailing blank.
345	lines = append(lines, "")
346	lines = append(lines, th.FG256(th.Muted, "  ↑/↓ navigate · tab complete · enter run"))
347	// Blank row after the hint separates the popup from the status
348	// bar / editor below it.
349	lines = append(lines, "")
350	return lines
351}
352
353// Reset puts the cursor back to the first match. Call this whenever the
354// input changes in a way that reshapes the match list.
355func (s *slashSuggester) Reset() { s.cursor = 0 }

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 477

↑↓ moveenter openesc close