Debian Codegraph @

testsuite/completion.00-init/040-fish-procs.exp

raw
1 ##############################################################################
2 # Modules Revision 3.0
3 # Providing a flexible user environment
4 #
5 # File: completion.00-init/%M%
6 # Revision: %I%
7 # First Edition: 2026/08/11
8 # Last Mod.: %U%, %G%
9 #
10 # Authors: Xavier Delaruelle, [email protected]
11 #
12 # Description: Test procedures
13 # Command:
14 # Sub-Command:
15 #
16 # Comment: %C{
17 # Defines the test procedures driving a real fish shell in
18 # a pty to exercise the module Tab completion script
19 # exactly as a user pressing Tab would, then collect the
20 # resulting candidate word list. This mirrors
21 # 020-bash-procs.exp's completion_bash_{start,raw,list,
22 # close} set (see that file's header for why each shell
23 # gets its own), but fish's line editor differs from both
24 # readline and zle in ways that shape almost every proc
25 # below:
26 # - on startup, a modern fish queries the terminal for
27 # its capabilities (primary device attributes,
28 # background color, cursor position, kitty keyboard
29 # protocol support, ...) and blocks waiting for a
30 # reply -- for the primary device attributes query,
31 # for up to 10 real seconds before giving up. A pty
32 # driven by Expect never answers these, so every proc
33 # that reads from the fish session folds in a
34 # 'completion_fish_query_responder' branch that
35 # answers each such query the instant it appears (a
36 # real terminal emulator would do the same), and fish
37 # re-issues at least the cursor-position query on
38 # every single prompt redraw, not just once at startup
39 # - a single Tab is fish's equivalent of bash/zsh's
40 # double-Tab: it both extends the typed word to the
41 # longest common prefix (if any) *and* shows the full
42 # candidate pager below the cmdline in the same
43 # keypress, collapsing it back via one '\x1b[A'
44 # (cursor-up) escape sequence per pager row once done
45 # -- unlike zsh's own double-Tab, it does not also
46 # auto-select/insert the first candidate when there is
47 # no further common prefix to extend into; the typed
48 # word is left exactly as-is, same as bash
49 # - fish echoes a command line back keystroke-by-keystroke
50 # (here: word-by-word, since this file sends a whole
51 # cmdline in one 'send') as it is typed, each echo
52 # wrapped in its own cursor-positioning escape
53 # sequences, rather than readline/zle's single redraw
54 # once done; the *only* reliable way to recover the
55 # final, settled state of the line is to take the
56 # *last* place in the raw output where the typed
57 # cmdline text appears, not the first -- earlier
58 # occurrences are just intermediate echo frames
59 # - candidate names fish shows with a '--description'
60 # (eg every sub-command name, every option flag) get
61 # rendered by the pager as "name (description text)",
62 # several such pairs packed per row -- the
63 # parenthesized part must be stripped before the
64 # listing can be split into plain candidate words, and
65 # since a description can itself legitimately contain
66 # one level of parentheses (eg "(Load modulefile(s))"),
67 # a plain 'no parenthesis inside' pattern is not
68 # enough
69 # - fish has no equivalent of bash/zsh/tcsh's own
70 # distinctive custom $PS1-alike prompt to match on and
71 # wait for: completion_fish_wait_ready instead waits for
72 # the pty to simply fall quiet after a prompt (re)draw,
73 # the same idle-quiet technique completion_fish_capture
74 # uses to read back a completion listing (matching on
75 # fish's own OSC 133 "prompt end" marker, emitted once a
76 # prompt has finished drawing on releases that support
77 # it under the running conditions, was tried first and
78 # abandoned: fish 3.7, observed on a GitHub Actions
79 # runner with no recognized terminal-program hint, never
80 # emits it at all, no matter the prompt content)
81 # }C%
82 #
83 ##############################################################################
84
85 # terminal-capability queries fish issues that this pty never gets asked by
86 # a real terminal to answer on its own -- reply to each the instant it
87 # appears, exactly as a real terminal emulator would, so fish never blocks
88 # waiting on one. Folded into every 'expect' below that reads from the fish
89 # session via 'exp_continue', since fish re-issues at least the cursor
90 # position query on every single prompt redraw, not just once at startup
91 proc completion_fish_query_responder {} {
92 return {
93 -re {\x1b\[6n} { send -- "\x1b\[1;1R"; exp_continue }
94 -re {\x1b\[0c} { send -- "\x1b\[?1;2c"; exp_continue }
95 -re {\x1b\]11;\?} { send -- "\x1b]11;rgb:0000/0000/0000\x1b\\"; exp_continue }
96 -re {\x1b\[\?u} { send -- "\x1b\[?0u"; exp_continue }
97 }
98 }
99
100 # wait for the fish session to fall quiet after a prompt (re)draw --
101 # reusing the exact same idle-quiet technique completion_fish_capture
102 # relies on to read back a completion listing (see completion_fish_read_
103 # quiet's own header for why a fixed delay does not scale here either). An
104 # earlier version of this proc instead matched on the OSC 133 "prompt end"
105 # marker fish emits once a prompt has finished drawing, on releases that
106 # support it under the running conditions -- but fish 3.7 (observed on a
107 # GitHub Actions runner, no recognized terminal-program hint) never emits
108 # it at all, no matter the prompt content, so that marker cannot be relied
109 # on to even exist. Idle detection needs no such cooperation from fish
110 # itself, at the cost of no longer being able to tell "fish is ready" apart
111 # from "fish crashed and will never answer" -- a real difference in theory,
112 # but nothing downstream of this proc treats them differently either way
113 proc completion_fish_wait_ready {} {
114 global completion_fish_spawn_id
115
116 set spawn_id $completion_fish_spawn_id
117 completion_fish_read_quiet
118 }
119
120 # start a fresh fish session with the completion script under test sourced;
121 # 'TERM' is set to a capable value (rather than 'dumb', which silences the
122 # terminal-capability queries but also disables the candidate pager this
123 # file's checks rely on) and every such query is answered as soon as it is
124 # asked (see completion_fish_query_responder), so startup never hits fish's
125 # up-to-10-second wait for a reply that would otherwise never come
126 proc completion_fish_start {} {
127 global fishbin fishcompletion completion_prompt completion_fish_spawn_id
128 global TCLSH MODULECMD verbose
129
130 if {$verbose > 1} {
131 send_user "\tStarting fish for completion test\n"
132 }
133
134 spawn env TERM=xterm-256color $fishbin --no-config
135 set completion_fish_spawn_id $spawn_id
136
137 # a narrow (default 80-column) pty can make a long completed line wrap,
138 # which makes fish redraw it with extra escape sequences that can be
139 # mistaken for stray inserted characters (e.g. a trailing space) by
140 # anything matching on raw output; go wide enough that no cmdline used
141 # in these tests is ever at risk of wrapping
142 stty rows 40 columns 500 < $spawn_out(slave,name)
143
144 completion_fish_wait_ready
145
146 # every setup command after this point goes through completion_fish_raw
147 completion_fish_raw {set -g fish_greeting ''}
148 completion_fish_raw "function fish_prompt; echo -n '$completion_prompt'; end"
149 # a real 'module' command is needed since the completion script shells
150 # out to it (module avail/spider) to list candidate module names
151 completion_fish_raw "source '$fishcompletion'"
152 completion_fish_raw "'$TCLSH' '$MODULECMD' fish autoinit | source -"
153
154 # neutralize any *other* 'module' completion fish can reach on this
155 # machine (eg from a system package -- 'environment-modules' on Fedora
156 # installs its own, older completions/module.fish into fish's vendor
157 # completions directory, a fixed location outside this testsuite's
158 # control that plain sandboxing -- '--no-config', a scratch $HOME --
159 # cannot hide from fish). Once 'module' resolves to a real command (the
160 # autoinit call just above defines it as a fish function), fish
161 # autoloads a same-named completions/module.fish -- if one exists
162 # anywhere on its search path -- the first time completion is attempted
163 # for it, regardless of the manual registrations from the 'source'
164 # above, potentially clobbering them with whatever that other version
165 # defines instead (observed: an older release's renamed sub-command,
166 # 'del' for today's 'delete', showing up alongside/instead of the
167 # built one under test). This autoload only ever happens once per
168 # session, though, so it is deliberately triggered and absorbed right
169 # here with a throwaway completion attempt, its result erased, and the
170 # script under test re-sourced fresh -- every real Tab-completion
171 # attempt later in this session then only ever sees that
172 completion_fish_raw {complete -C'module ' > /dev/null}
173 completion_fish_raw {complete -e -c module}
174 completion_fish_raw "source '$fishcompletion'"
175 }
176
177 # send a line to the completion fish session and wait for the next ready
178 # prompt; used for setup commands whose output is not asserted on
179 proc completion_fish_raw {line} {
180 global completion_fish_spawn_id verbose
181
182 set spawn_id $completion_fish_spawn_id
183 send -- "$line\r"
184 completion_fish_wait_ready
185 if {$verbose > 1} {
186 send_user "\tcompletion> $line\n"
187 }
188 }
189
190 # read back everything the fish session produces until it falls quiet for
191 # 'idle_ms' (answering any terminal-capability query along the way), and
192 # return it all concatenated. A single fixed 'after N; read once' does not
193 # scale across every listing this file captures: a small candidate list
194 # renders near-instantly, while a wide, tall one (eg every sub-command name
195 # plus its description) takes long enough to stream out that a delay sized
196 # for the former still catches the latter mid-render, silently truncating
197 # it -- so this instead loops reading whatever has arrived, each time
198 # resetting the wait, until a whole 'idle_ms' window passes with nothing
199 # new; capped by an overall iteration count as a safety net against an
200 # unrecognized, endlessly-repeating query this proc does not know how to
201 # answer ever leaving it live-locked
202 proc completion_fish_read_quiet {{idle_ms 1000}} {
203 global completion_fish_spawn_id
204
205 set spawn_id $completion_fish_spawn_id
206 set old_timeout $::timeout
207 set ::timeout [expr {$idle_ms / 1000.0}]
208 set buf {}
209 set iterations 0
210 while {[incr iterations] <= 200} {
211 expect {*}[completion_fish_query_responder] \
212 -re {(?s).+} { append buf $expect_out(buffer) } \
213 timeout { break }
214 }
215 set ::timeout $old_timeout
216 return $buf
217 }
218
219 # send a partial command line followed by a single Tab (fish's own
220 # equivalent of bash/zsh's double-Tab, see this file's header), let any
221 # subprocess-backed candidate generation (eg 'module avail') finish
222 # rendering, read back everything fish produced in response, and finally
223 # clear the line so the session is ready to reuse
224 proc completion_fish_capture {cmdline} {
225 global completion_fish_spawn_id completion_last_cmdline verbose
226
227 set completion_last_cmdline $cmdline
228 set spawn_id $completion_fish_spawn_id
229
230 send -- $cmdline
231 send -- "\t"
232 set buf [completion_fish_read_quiet]
233 if {$verbose > 1} {
234 send_user "\tcompletion raw output for '$cmdline': [string map {\x1b ESC} $buf]\n"
235 }
236
237 # clear the (uncompleted or already-completed) input line so the
238 # session is ready to reuse
239 send -- "\x15\r"
240 completion_fish_wait_ready
241
242 return $buf
243 }
244
245 # strip every '(...)' description fish's pager prints next to a candidate
246 # declared with '--description' (eg sub-command names, option flags); a
247 # description can itself carry one level of nested parentheses (eg
248 # "(Load modulefile(s))"), so a plain 'no paren inside' pattern is not
249 # enough -- this handles exactly one level, which covers every description
250 # in the completion script under test
251 proc completion_fish_strip_descriptions {text} {
252 return [regsub -all {\((?:[^()]|\([^()]*\))*\)} $text {}]
253 }
254
255 # locate, in a completion_fish_capture buffer, the *last* place the typed
256 # cmdline text appears followed by plain (non-escape, non-CR) characters --
257 # fish echoes the cmdline back piecemeal as it is typed (see this file's
258 # header), so only the last such occurrence reflects the final, settled
259 # state of the line; a bare '\r' is excluded from that run too, since fish
260 # emits one right after the settled text to return the cursor to column 0
261 # before repositioning it with a following cursor-forward escape -- left
262 # in, it would be mistaken for part of the inserted suffix itself. Returns
263 # the run of characters right after the last occurrence (empty if the
264 # cmdline never appears followed by anything, ie nothing was inserted)
265 proc completion_fish_extract_suffix {buf cmdline} {
266 set recmdline [completion_re_escape $cmdline]
267 set matches [regexp -all -inline -- "${recmdline}(\[^\x1b\r\]*)" $buf]
268 if {[llength $matches] == 0} {
269 return {}
270 }
271 return [lindex $matches end]
272 }
273
274 # send a partial command line followed by a single Tab, and return the
275 # sorted, de-duplicated list of candidate words fish's pager displayed. A
276 # listing is preceded by a real newline (fish moves to a fresh line to
277 # print the pager below the cmdline) and collapsed back via one '\x1b[A'
278 # (cursor-up) escape per pager row right after; a cmdline whose candidate
279 # set has only one member never shows this -- Tab completes it inline
280 # instead, exactly like completion_fish_inline -- so that case is detected
281 # by the absence of this marker and handled by reconstructing the single
282 # candidate from the inline insertion instead, the same way
283 # completion_zsh_list's own single-candidate fallback does
284 proc completion_fish_list {cmdline} {
285 set buf [completion_fish_capture $cmdline]
286
287 if {[regexp {(?s)\n(.*?)(?:\x1b\[A)+} $buf -> listing]} {
288 set listing [completion_fish_strip_descriptions $listing]
289 set words {}
290 foreach word [split $listing] {
291 if {$word ne {}} {
292 lappend words $word
293 }
294 }
295 return [lsort -unique $words]
296 }
297
298 set suffix [string trim [completion_fish_extract_suffix $buf $cmdline]]
299 if {$suffix eq {}} {
300 return {}
301 }
302 return [lsort -unique [split $suffix]]
303 }
304
305 # send a partial command line followed by a single Tab, and return the text
306 # fish inserted inline -- the empty string if nothing at all could be
307 # completed (fish gives no equivalent of readline/zle's audible bell over a
308 # plain pty for this case, so unlike completion_bash_inline/
309 # completion_zsh_inline there is no "\a" to check for here). Used to check
310 # unique, unambiguous completions -- eg that a directory-style entry gets
311 # completed with a trailing '/' and no trailing space. cmdline must be a
312 # prefix with exactly one match, or with a common prefix short enough that
313 # no further Tab is needed to reach it, otherwise the single Tab may extend
314 # by less than a full match (leaving the ambiguous set to still be shown by
315 # the pager, harmless here since only the text right after the cmdline is
316 # read back, not whether a listing also appeared)
317 proc completion_fish_inline {cmdline} {
318 set buf [completion_fish_capture $cmdline]
319 return [completion_fish_extract_suffix $buf $cmdline]
320 }
321
322 proc completion_fish_close {} {
323 global completion_fish_spawn_id
324
325 if {[info exists completion_fish_spawn_id]} {
326 set spawn_id $completion_fish_spawn_id
327 catch {send -- "exit\r"}
328 catch {expect eof}
329 catch {close -i $completion_fish_spawn_id}
330 catch {wait -i $completion_fish_spawn_id}
331 unset completion_fish_spawn_id
332 }
333 }
334
335 # vim:set tabstop=3 shiftwidth=3 expandtab autoindent: