Debian Codegraph @

complete.go

raw
1 package main
2
3 import (
4 "log"
5 "maps"
6 "os"
7 "path/filepath"
8 "reflect"
9 "slices"
10 "sort"
11 "strings"
12 )
13
14 var (
15 gCmdWords = []string{
16 "set",
17 "setlocal",
18 "map",
19 "nmap",
20 "vmap",
21 "cmap",
22 "cmd",
23 "addcustominfo",
24 "bottom",
25 "calcdirsize",
26 "cd",
27 "clear",
28 "clearmaps",
29 "copy",
30 "cut",
31 "down",
32 "delete",
33 "draw",
34 "echo",
35 "echoerr",
36 "echomsg",
37 "filter",
38 "find",
39 "find-back",
40 "find-next",
41 "find-prev",
42 "glob-select",
43 "glob-unselect",
44 "half-down",
45 "half-up",
46 "high",
47 "invert",
48 "jump-next",
49 "jump-prev",
50 "load",
51 "low",
52 "mark-load",
53 "mark-remove",
54 "mark-save",
55 "middle",
56 "open",
57 "page-down",
58 "page-up",
59 "paste",
60 "push",
61 "quit",
62 "read",
63 "redraw",
64 "reload",
65 "rename",
66 "scroll-down",
67 "scroll-up",
68 "search",
69 "search-back",
70 "search-next",
71 "search-prev",
72 "select",
73 "setfilter",
74 "shell",
75 "shell-async",
76 "shell-pipe",
77 "shell-wait",
78 "source",
79 "sync",
80 "tag",
81 "tag-toggle",
82 "toggle",
83 "top",
84 "tty-write",
85 "unselect",
86 "up",
87 "updir",
88 "visual",
89 "visual-accept",
90 "visual-change",
91 "visual-discard",
92 "visual-unselect",
93 "cmd-capitalize-word",
94 "cmd-complete",
95 "cmd-delete",
96 "cmd-delete-back",
97 "cmd-delete-end",
98 "cmd-delete-home",
99 "cmd-delete-unix-word",
100 "cmd-delete-word",
101 "cmd-delete-word-back",
102 "cmd-end",
103 "cmd-enter",
104 "cmd-escape",
105 "cmd-history-next",
106 "cmd-history-prev",
107 "cmd-home",
108 "cmd-interrupt",
109 "cmd-left",
110 "cmd-lowercase-word",
111 "cmd-menu-accept",
112 "cmd-menu-complete",
113 "cmd-menu-complete-back",
114 "cmd-menu-discard",
115 "cmd-right",
116 "cmd-transpose",
117 "cmd-transpose-word",
118 "cmd-uppercase-word",
119 "cmd-word",
120 "cmd-word-back",
121 "cmd-yank",
122 }
123
124 gOptWords = getOptWords(gOpts)
125 gLocalOptWords = getLocalOptWords(gLocalOpts)
126 )
127
128 func getOptWords(opts any) (optWords []string) {
129 t := reflect.TypeOf(opts)
130 for i := range t.NumField() {
131 field := t.Field(i)
132 switch field.Type.Kind() {
133 case reflect.Map:
134 continue
135 case reflect.Bool:
136 name := field.Name
137 optWords = append(optWords, name, "no"+name, name+"!")
138 default:
139 optWords = append(optWords, field.Name)
140 }
141 }
142 sort.Strings(optWords)
143 return
144 }
145
146 func getLocalOptWords(localOpts any) (localOptWords []string) {
147 t := reflect.TypeOf(localOpts)
148 for i := range t.NumField() {
149 field := t.Field(i)
150 name := field.Name
151 if field.Type.Kind() != reflect.Map {
152 continue
153 }
154 if field.Type.Elem().Kind() == reflect.Bool {
155 localOptWords = append(localOptWords, name, "no"+name, name+"!")
156 } else {
157 localOptWords = append(localOptWords, name)
158 }
159 }
160 sort.Strings(localOptWords)
161 return
162 }
163
164 func getLongest(s1, s2 string) string {
165 r1 := []rune(s1)
166 r2 := []rune(s2)
167
168 i := 0
169 for ; i < len(r1) && i < len(r2); i++ {
170 if r1[i] != r2[i] {
171 break
172 }
173 }
174
175 return string(r1[:i])
176 }
177
178 type compMatch struct {
179 name string // display name in completion menu
180 result string // result when cycling through completion menu
181 }
182
183 func matchWord(s string, words []string) (matches []compMatch, longest string) {
184 for _, w := range words {
185 if !strings.HasPrefix(w, s) {
186 continue
187 }
188
189 matches = append(matches, compMatch{w, w})
190 if len(matches) == 1 {
191 longest = w
192 } else {
193 longest = getLongest(longest, w)
194 }
195 }
196
197 switch len(matches) {
198 case 0:
199 longest = s
200 case 1:
201 longest += " "
202 }
203 return
204 }
205
206 func matchList(s string, words []string) (matches []compMatch, longest string) {
207 toks := strings.Split(s, ":")
208
209 for _, w := range words {
210 if slices.Contains(toks[:len(toks)-1], w) || !strings.HasPrefix(w, toks[len(toks)-1]) {
211 continue
212 }
213
214 matchResult := strings.Join(append(slices.Clone(toks[:len(toks)-1]), w), ":")
215 matches = append(matches, compMatch{w, matchResult})
216
217 if len(matches) == 1 {
218 longest = matchResult
219 } else {
220 longest = getLongest(longest, matchResult)
221 }
222 }
223
224 switch len(matches) {
225 case 0:
226 longest = s
227 case 1:
228 if longest == s {
229 longest += " "
230 }
231 }
232 return
233 }
234
235 func matchCmd(s string) (matches []compMatch, longest string) {
236 words := slices.Concat(gCmdWords, slices.Collect(maps.Keys(gOpts.cmds)))
237 slices.Sort(words)
238 matches, longest = matchWord(s, slices.Compact(words))
239 return
240 }
241
242 func matchFile(s string, dirOnly bool, escape, unescape func(string) string) (matches []compMatch, longest string) {
243 dir, file := filepath.Split(unescape(replaceTilde(s)))
244
245 d := dir
246 if dir == "" {
247 d = "."
248 }
249 files, err := os.ReadDir(d)
250 if err != nil {
251 log.Printf("reading directory: %s", err)
252 longest = s
253 return
254 }
255
256 var longestName string
257
258 for _, f := range files {
259 isDir := false
260 if f.IsDir() {
261 isDir = true
262 } else if f.Type()&os.ModeSymlink != 0 {
263 if stat, err := os.Stat(filepath.Join(d, f.Name())); err == nil && stat.IsDir() {
264 isDir = true
265 }
266 }
267
268 if !isDir && dirOnly {
269 continue
270 }
271
272 if !strings.HasPrefix(strings.ToLower(f.Name()), strings.ToLower(file)) {
273 continue
274 }
275
276 name := f.Name()
277 if isDir {
278 name += string(filepath.Separator)
279 }
280 matches = append(matches, compMatch{name, escape(dir + name)})
281
282 if len(matches) == 1 {
283 longestName = name
284 } else {
285 // Match case-insensitively without changing the prefix's case.
286 p := getLongest(strings.ToLower(longestName), strings.ToLower(name))
287 longestName = string([]rune(longestName)[:len([]rune(p))])
288 }
289 }
290
291 switch len(matches) {
292 case 0:
293 longest = s
294 case 1:
295 longest = escape(dir + longestName)
296 if !strings.HasSuffix(longestName, string(filepath.Separator)) {
297 longest += " "
298 }
299 default:
300 longest = escape(dir + longestName)
301 }
302 return
303 }
304
305 func matchCmdFile(s string, dirOnly bool) (matches []compMatch, longest string) {
306 matches, longest = matchFile(s, dirOnly, cmdEscape, cmdUnescape)
307 return
308 }
309
310 func matchShellFile(s string) (matches []compMatch, longest string) {
311 matches, longest = matchFile(s, false, shellEscape, shellUnescape)
312 return
313 }
314
315 func matchExec(s string) (matches []compMatch, longest string) {
316 var words []string
317 for p := range strings.SplitSeq(envPath, string(filepath.ListSeparator)) {
318 files, err := os.ReadDir(p)
319 if err != nil {
320 if !os.IsNotExist(err) {
321 log.Printf("reading path: %s", err)
322 }
323 continue
324 }
325
326 for _, f := range files {
327 if !strings.HasPrefix(f.Name(), s) {
328 continue
329 }
330
331 finfo, err := f.Info()
332 if err != nil {
333 log.Printf("getting file information: %s", err)
334 continue
335 }
336
337 if finfo.Mode().IsRegular() && isExecutable(finfo) {
338 words = append(words, f.Name())
339 }
340 }
341 }
342
343 slices.Sort(words)
344 matches, longest = matchWord(s, slices.Compact(words))
345 return
346 }
347
348 func matchSearch(s string) (matches []compMatch, longest string) {
349 files, err := os.ReadDir(".")
350 if err != nil {
351 log.Printf("reading directory: %s", err)
352 longest = s
353 return
354 }
355
356 for _, f := range files {
357 if !strings.HasPrefix(strings.ToLower(f.Name()), strings.ToLower(s)) {
358 continue
359 }
360
361 matches = append(matches, compMatch{f.Name(), f.Name()})
362 if len(matches) == 1 {
363 longest = f.Name()
364 } else {
365 p := getLongest(strings.ToLower(longest), strings.ToLower(f.Name()))
366 longest = string([]rune(longest)[:len([]rune(p))])
367 }
368 }
369
370 if len(matches) == 0 {
371 longest = s
372 }
373 return
374 }
375
376 func completeCmd(s string) (matches []compMatch, longest string) {
377 f := tokenize(s)
378
379 if len(f) == 1 {
380 matches, longest = matchCmd(s)
381 return
382 }
383
384 longest = f[len(f)-1]
385
386 switch f[0] {
387 case "set":
388 if len(f) == 2 {
389 matches, longest = matchWord(f[1], gOptWords)
390 break
391 }
392 if len(f) != 3 {
393 break
394 }
395 switch f[1] {
396 case "cleaner", "previewer", "rulerfile":
397 matches, longest = matchCmdFile(f[2], false)
398 case "borderstyle":
399 matches, longest = matchWord(f[2], []string{"box", "roundbox", "outline", "roundoutline", "separators"})
400 case "filtermethod", "searchmethod":
401 matches, longest = matchWord(f[2], []string{"glob", "regex", "text"})
402 case "info":
403 matches, longest = matchList(f[2], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"})
404 case "preserve":
405 matches, longest = matchList(f[2], []string{"mode", "timestamps"})
406 case "selmode":
407 matches, longest = matchWord(f[2], []string{"all", "dir"})
408 case "sizeunits":
409 matches, longest = matchWord(f[2], []string{"binary", "decimal"})
410 case "sortby":
411 matches, longest = matchWord(f[2], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"})
412 case "terminalcursor":
413 matches, longest = matchWord(f[2], []string{"default", "block", "underline", "bar", "blinkblock", "blinkunderline", "blinkbar"})
414 default:
415 if slices.Contains(gOptWords, f[1]+"!") {
416 matches, longest = matchWord(f[2], []string{"false", "true"})
417 }
418 }
419 case "setlocal":
420 if len(f) == 2 {
421 matches, longest = matchCmdFile(f[1], true)
422 break
423 }
424 if len(f) == 3 {
425 matches, longest = matchWord(f[2], gLocalOptWords)
426 break
427 }
428 if len(f) != 4 {
429 break
430 }
431 switch f[2] {
432 case "info":
433 matches, longest = matchList(f[3], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"})
434 case "sortby":
435 matches, longest = matchWord(f[3], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"})
436 default:
437 if slices.Contains(gLocalOptWords, f[2]+"!") {
438 matches, longest = matchWord(f[3], []string{"false", "true"})
439 }
440 }
441 case "map", "nmap", "vmap", "cmap":
442 if len(f) == 3 {
443 matches, longest = matchCmd(f[2])
444 }
445 case "cmd":
446 case "cd":
447 if len(f) == 2 {
448 matches, longest = matchCmdFile(f[1], true)
449 }
450 case "addcustominfo", "select", "source":
451 if len(f) == 2 {
452 matches, longest = matchCmdFile(f[1], false)
453 }
454 case "toggle":
455 matches, longest = matchCmdFile(f[len(f)-1], false)
456 default:
457 if !slices.Contains(gCmdWords, f[0]) {
458 matches, longest = matchCmdFile(f[len(f)-1], false)
459 }
460 }
461
462 f[len(f)-1] = longest
463 longest = strings.Join(f, " ")
464 return
465 }
466
467 func completeShell(s string) (matches []compMatch, longest string) {
468 f := tokenize(s)
469
470 switch len(f) {
471 case 1:
472 matches, longest = matchExec(f[0])
473 default:
474 matches, longest = matchShellFile(f[len(f)-1])
475 }
476
477 f[len(f)-1] = longest
478 longest = strings.Join(f, " ")
479 return
480 }
481
482 func completeSearch(s string) (matches []compMatch, longest string) {
483 matches, longest = matchSearch(s)
484 return
485 }