-
Notifications
You must be signed in to change notification settings - Fork 7
/
fishcomplete.lua
806 lines (719 loc) · 26.2 KB
/
fishcomplete.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
--------------------------------------------------------------------------------
-- PROTOTYPE SCRIPT -- Disabled by default; see below for how to enable it.
--------------------------------------------------------------------------------
-- Usage:
--
-- When a command is typed and it does not have an argmatcher, then fishcomplete
-- automatically checks if there is a .fish file by the same name in the same
-- directory as the command program, or in an autocomplete or complete
-- subdirectory below it, or in the directory specified by the
-- fishcomplete.completions_dir setting. If yes, then it attempts to parse the
-- .fish file and generate a Clink argmatcher from it.
--
-- To enable it, run:
--
-- clink set fishcomplete.enable true
--
-- If fishcomplete is enabled, then by default it shows feedback at the top of
-- the screen when attempting to load *.fish completion files. If you want to
-- disable the feedback, you can run "clink set fishcomplete.banner false".
--
-- You can optionally configure a directory containing *.fish completion files
-- by running "clink set fishcomplete.completions_dir c:\some\dir". This
-- directory is searched last, if a .fish file isn't found by the default search
-- strategy.
--
-- NOTE: The fishcomplete script does not yet handle the -e or -w flags for
-- the fish "complete" command. It attempts to handle simple fish completion
-- scripts, but it will likely malfunction with more sophisticated fish
-- completion scripts. It cannot handle the fish scripting language, apart from
-- the "complete" command itself.
-- TODO: -e : `complete -c command -e` erases wrapped "command".
-- TODO: -e arg : `complete -c command -e cmpltn` erases completion "cmpltn" from "command".
-- TODO: -w arg : `complete -c hub -w git` makes "hub" inherit the current state of "git" command completions.
local standalone = clink and not clink.argmatcher and not clink.arg and true
if not standalone then
settings.add("fishcomplete.enable", false, "Auto-translate fish completion files",
"When this is enabled and a command is typed that doesn't have an argmatcher,\n"..
"then this automatically looks for a .fish file by the same name. If found,\n"..
"it attempts to parse the .fish file and generate a Clink argmatcher from it.")
settings.add("fishcomplete.banner", true, "Show feedback when loading .fish files")
settings.add("fishcomplete.completions_dir", "", "Path to .fish completion files",
"This specifies a directory to search for .fish completion files. This is in\n"..
"addition to the directory containing the corresponding command program, and\n"..
"any autocomplete or complete subdirectory below that directory.")
if not settings.get("fishcomplete.enable") then
return
end
if not clink.oncommand then
print('fishcomplete.lua requires a newer version of Clink; please upgrade.')
return
end
end -- not standalone
-- luacheck: globals NONL
--------------------------------------------------------------------------------
-- Options helpers.
local match_longflag = '^(%-%-[^ \t]+)([ \t=])'
local match_shortflag = '^(%-[^ \t])([ \t])'
local match_oldflag = '^(%-[^ \t]+)([ \t=])'
local function initopt(state, options, line)
state._options = options
state._line = line.." "
end
local function getopt(state)
if state._line == '' then
return
end
local f, delim = state._line:match(match_longflag)
if f then
state._line = state._line:gsub(match_longflag, '')
else
f, delim = state._line:match(match_shortflag)
if f then
state._line = state._line:gsub(match_shortflag, '')
else
f, delim = state._line:match(match_oldflag)
if f then
state._line = state._line:gsub(match_oldflag, '')
else
local words = string.explode(state._line, ' \t')
state.failure = 'unexpected text "'..(words and words[1] or '')..'"'
state.flags = nil
return
end
end
end
if delim ~= '=' then
state._line = state._line:gsub('^[ \t]+', '')
end
local opt = state._options[f]
if not opt then
state.failure = 'unrecognized flag '..f
state.flags = nil
return nil, nil, f
end
local arg
if opt.arg then
local i = 1
local qc = state._line:match('^([\'"])')
local end_match = qc
if qc then
i = 2
else
end_match = '[ \t]'
end
arg = ''
local last = 0
local nextstart = i
local len = #state._line
while i <= len do
local ch = state._line:sub(i,i)
if ch:match(end_match) then
break
elseif ch == [[\]] then
arg = arg..state._line:sub(nextstart, last)
i = i + 1
nextstart = i
end
last = i
i = i + 1
end
if last >= nextstart then
arg = arg..state._line:sub(nextstart, last)
end
state._line = state._line:sub(last + 1)
if qc then
state._line = state._line:gsub('^'..qc, '')
end
state._line = state._line:gsub('^[ \t]+', '')
end
if opt.func then
opt.func(state, arg)
end
return opt, arg, f
end
--------------------------------------------------------------------------------
-- Fish `complete` command parser.
local function trim(s)
return s:gsub('^ +', ''):gsub(' +$', '')
end
local _command = {
arg=true,
func=function (state, arg)
state.command = arg
end
}
local _path = {
-- This approximates the -p flag.
arg=true,
func=function (state, arg)
state.command = path.getbasename(arg)
end
}
local _condition = {
arg=true,
func=function (state, arg)
if arg == '__fish_use_subcommand' then -- luacheck: ignore 542
elseif arg:find('__fish_contains_opt') then -- luacheck: ignore 542
local opt = arg:match('__fish_contains_opt%s+(.*)$')
if opt then
local conditions = {}
local t = string.explode(opt)
local short
for _,s in ipairs(t) do
if s == '-s' then
short = true
elseif short then
short = false
table.insert(conditions, '-'..s)
else
table.insert(conditions, '--'..s)
end
end
if conditions[1] then
state.condition_contains_opt = conditions
end
end
else
state.failures = state.failures or {}
table.insert(state.failures, 'unrecognized condition "'..arg..'"')
end
end
}
local _short_option = {
arg=true,
func=function (state, arg)
if not state.command then
state.failures = state.failures or {}
table.insert(state.failures, 'missing command for short option "-'..arg..'"')
else
table.insert(state.flags, '-'..arg)
end
end
}
local _long_option = {
arg=true,
func=function (state, arg)
if not state.command then
state.failures = state.failures or {}
table.insert(state.failures, 'missing command for long option "--'..arg..'"')
else
table.insert(state.flags, '--'..arg)
end
end
}
local _old_option = {
arg=true,
func=function (state, arg)
if not state.command then
state.failures = state.failures or {}
table.insert(state.failures, 'missing command for old option "-'..arg..'"')
else
table.insert(state.flags, '-'..arg)
end
end
}
local _description = {
arg=true,
func=function (state, arg)
state.desc = arg
end
}
-- TODO: Support multi-line arguments, as in rg.fish.
-- NOTE: The {..} globbing syntax is more complicated than I'm willing to
-- support at this time.
local _arguments = {
arg=true,
func=function (state, arg)
state.linked_parser = true
if arg:find('^%#') then -- luacheck: ignore 542
-- Ignore comment lines.
elseif arg:find('^%{') then
arg = arg:gsub('^%{(.*)}$', '%1')
local s1 = ''
local s2 = ''
local desc, quote, esc
for i = 1, #arg do
local c = arg:sub(i, i)
if not desc then
if c == '\t' then
desc = true
quote = false
else
s1 = s1..c
end
else
if esc then
s2 = s2..c
esc = nil
elseif quote then
if c == '\\' then
esc = true
elseif c == '\'' then
quote = nil
else
s2 = s2..c
end
else
if c == '\'' then
quote = true
elseif c == ',' then
table.insert(state.matches, { match=trim(s1), desc=trim(s2) })
s1 = ''
s2 = ''
desc = nil
end
end
end
end
if s1 ~= '' then
table.insert(state.matches, { match=trim(s1), desc=trim(s2) })
end
else
for _,s in ipairs(string.explode(arg)) do
table.insert(state.matches, { match=trim(s) })
end
end
end
}
local _keep_order = {
func=function (state, arg) -- luacheck: no unused
state.nosort = true
end
}
local _no_files = {
func=function (state, arg) -- luacheck: no unused
state.nofiles = true
end
}
local _force_files = {
func=function (state, arg) -- luacheck: no unused
state.forcefiles = true
end
}
local _require_parameter = {
func=function (state, arg) -- luacheck: no unused
state.linked_parser = true
end
}
local _exclusive = {
func=function (state, arg) -- luacheck: no unused
state.nofiles = true
state.linked_parser = true
end
}
local _nyi = { nyi=true }
local _nyi_arg = { nyi=true, arg=true }
local options = {
['-c'] = _command, ['--command'] = _command,
['-p'] = _path, ['--path'] = _path,
['-s'] = _short_option, ['--short-option'] = _short_option,
['-l'] = _long_option, ['--long-option'] = _long_option,
['-o'] = _old_option, ['--old-option'] = _old_option,
['-d'] = _description, ['--description'] = _description,
['-a'] = _arguments, ['--arguments'] = _arguments,
['-k'] = _keep_order, ['--keep-order'] = _keep_order,
['-f'] = _no_files, ['--no-files'] = _no_files,
['-F'] = _force_files, ['--force-files'] = _force_files,
['-r'] = _require_parameter, ['--require-parameter'] = _require_parameter,
['-n'] = _condition, ['--condition'] = _condition,
['-x'] = _exclusive, ['--exclusive'] = _exclusive,
['-e'] = _nyi, ['--erase'] = _nyi,
['-w'] = _nyi_arg, ['--wraps'] = _nyi_arg,
}
local function parse_fish_completions(name, fish)
local file = io.open(fish, 'r')
if not file then
return
end
local failures
local commands = {}
local state
local match_complete = '^complete[ \t]+'
local i = 0
for line in file:lines() do
i = i + 1
if line:match(match_complete) then
state = {
command=name,
flags={},
matches={},
}
initopt(state, options, line:gsub(match_complete, ''))
while getopt(state) do -- luacheck: ignore 542
end
commands[state.command] = commands[state.command] or {}
local lp
local lpname
if state.linked_parser then
local s1 = state.command:gsub('[^A-Za-z]', '')
local s2 = ''
for _,f in ipairs(state.flags) do
if #s2 < #f then
s2 = f
end
end
s2 = s2:gsub('[^A-Za-z]', '')
if s2 == '' then
state.failures = state.failures or {}
table.insert(state.failures, 'missing flag')
state.linked_parser = nil
else
lpname = s1..'_'..s2
if state.forcefiles or not state.nofiles then
table.insert(state.matches, clink.filematches)
end
lp = state.matches or {}
commands[state.command].links = commands[state.command].links or {}
commands[state.command].links[lpname] = lp
end
end
if state.failures then
failures = failures or {}
for _,f in ipairs(state.failures) do
table.insert(failures, f..' on line '..tostring(i))
end
end
if (state.desc and #state.desc > 0) or state.linked_parser then
local descs = commands[state.command].descs or {}
for _,f in ipairs(state.flags) do
local d = {}
if state.linked_parser then
table.insert(d, ' arg')
end
table.insert(d, state.desc or '')
descs[f] = d
end
commands[state.command].descs = descs
end
local flags = commands[state.command].flags or {}
for _,f in ipairs(state.flags) do
local flag = { f }
if lpname and lp then
table.insert(flag, lpname)
end
table.insert(flags, flag)
end
commands[state.command].flags = flags
if state.condition_contains_opt then
local conditions = commands[state.command].conditions or {}
for _,f in ipairs(state.flags) do
conditions[f] = state.condition_contains_opt
end
commands[state.command].conditions = conditions
end
end
end
file:close()
return commands, failures
end
if standalone then
require('modules/dumpvar')
local function escape_string(s)
return s:gsub('(["\\])', '\\%1')
end
local function spairs(t, order)
local keys = {}
local num = 0
for k in pairs(t) do
num = num + 1
keys[num] = k
end
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
local function convert()
local red = '\x1b[91m'
local green = '\x1b[92m'
local norm = '\x1b[m'
local infile = arg[1]
local outfile = arg[2]
if not infile then
clink.print(red..'Missing input file.'..norm)
os.exit(1)
end
if not outfile then
local dir = path.getdirectory(infile)
local name = path.getbasename(infile)
outfile = path.join(dir, name)..'.lua'
end
if os.isdir(outfile) then
outfile = path.join(outfile, path.getbasename(infile)..'.lua')
end
local o, msg = io.open(outfile, 'w')
if not o then
msg = msg and '; '..msg or ''
msg = string.gsub(msg..'.', '%.+$', '.')
clink.print(red..'Error opening "'..outfile..'" for write'..msg..norm)
os.exit(1)
end
local commands, failures = parse_fish_completions(path.getbasename(infile), infile)
-- For each command.
local first = true
local first_conditions = true
for cname,c in spairs(commands) do
if not first then
o:write('\n')
end
o:write('------------------------------------------------------------------------------\n')
o:write('-- '..cname:upper()..'\n')
o:write('\n')
if first then
first = nil
o:write('-- luacheck: no max line length\n')
o:write('\n')
o:write('local function try_require(module)\n')
o:write(' local r\n')
o:write(' pcall(function() r = require(module) end)\n')
o:write(' return r\n')
o:write('end\n')
o:write('\n')
o:write('try_require("arghelper")\n')
o:write('\n')
end
if c.conditions and first_conditions then
first_conditions = nil
-- IMPORTANT: Keep in sync with onarg_contains_opt().
o:write('local function onarg_contains_opt(arg_index, word, _, _, user_data)\n')
o:write(' if arg_index == 0 then\n')
o:write(' local present = user_data.present\n')
o:write(' if not present then\n')
o:write(' present = {}\n')
o:write(' user_data.present = present\n')
o:write(' end\n')
o:write(' present[word] = true\n')
o:write(' end\n')
o:write('end\n')
o:write('\n')
-- IMPORTANT: Keep in sync with do_filter().
o:write('local function do_filter(matches, conditions, user_data)\n')
o:write(' local ret = {}\n')
o:write(' local present = user_data.present or {}\n')
o:write(' for _,m in ipairs(matches) do\n')
o:write(' local test_list = conditions[m.match]\n')
o:write(' if test_list then\n')
o:write(' local ok\n')
o:write(' for _,test in ipairs(test_list) do\n')
o:write(' if present[test] then\n')
o:write(' ok = true\n')
o:write(' break\n')
o:write(' end\n')
o:write(' end\n')
o:write(' if not ok then\n')
o:write(' goto continue\n')
o:write(' end\n')
o:write(' end\n')
o:write(' table.insert(ret, m)\n')
o:write('::continue::\n')
o:write(' end\n')
o:write(' return ret\n')
o:write('end\n')
o:write('\n')
end
-- Make linked argmatchers.
if c.links then
for lname,l in spairs(c.links) do
local any_desc
o:write('local '..lname..' = clink.argmatcher():addarg({')
for i,arg in ipairs(l) do
if i > 1 then
o:write(', ')
end
o:write('"'..escape_string(arg.match)..'"')
if arg.desc and arg.desc ~= '' then
any_desc = true
end
end
o:write('})')
if any_desc then
o:write(':adddescriptions({\n')
for _,arg in ipairs(l) do
if arg.desc and arg.desc ~= '' then
o:write(' ["'..escape_string(arg.match)..'"] = "'..escape_string(arg.desc)..'",\n')
end
end
o:write('})')
end
o:write('\n')
end
o:write('\n')
end
-- Make conditions table.
if c.conditions then
o:write('local '..cname..'__hide_unless = {\n')
for k,values in spairs(c.conditions) do
o:write(' ["'..k..'"] = { ')
for i,value in ipairs(values) do
if i > 1 then
o:write(', ')
end
o:write('"'..escape_string(value)..'"')
end
o:write(' },\n')
end
o:write('}\n')
o:write('\n')
end
-- Make command argmatcher.
o:write('clink.argmatcher("'..cname..'")\n')
if c.descs then
o:write(':adddescriptions({\n')
for f,d in spairs(c.descs) do
o:write(' ["'..f..'"] = { "'..escape_string(d[1])..'"')
if d[2] then
o:write(', "'..escape_string(d[2])..'"')
end
o:write(' },\n')
assert(not d[3])
end
o:write('})\n')
end
do
o:write(':addflags({\n')
for _,f in ipairs(c.flags) do
o:write(' "'..f[1]..'"')
if f[2] then
o:write('..'..f[2])
end
o:write(',\n')
end
if c.conditions then
o:write(' onarg = onarg_contains_opt,\n')
o:write(' function(_, _, _, _, user_data) clink.onfiltermatches(function(matches) return do_filter(matches, '..cname..'__hide_unless, user_data) end) end,\n') -- luacheck: no max line length
end
o:write('})\n')
end
end
o:close()
if failures then
clink.print(red..'Failure(s) while converting the completion script:'..norm)
for _,f in ipairs(failures) do
print(f)
end
os.exit(1)
else
clink.print(green..'Successful conversion.'..norm)
end
end
return convert()
end
-- IMPORTANT: Keep in sync with convert().
local function onarg_contains_opt(arg_index, word, word_index, line_state, user_data) -- luacheck: no unused
if arg_index == 0 then
local present = user_data.present
if not present then
present = {}
user_data.present = present
end
present[word] = true
end
end
-- IMPORTANT: Keep in sync with convert().
local function do_filter(matches, conditions, user_data)
local ret = {}
local present = user_data.present or {}
for _,m in ipairs(matches) do
local test_list = conditions[m.match]
if test_list then
local ok
for _,test in ipairs(test_list) do
if present[test] then
ok = true
break
end
end
if not ok then
goto continue
end
end
table.insert(ret, m)
::continue::
end
return ret
end
local function generate_completions(commands)
-- For each command.
for cname,c in pairs(commands) do
-- Make linked argmatchers.
local links = {}
if c.links then
for lname,l in pairs(c.links) do
local am = clink.argmatcher()
am:addarg(l)
links[lname] = am
end
end
-- Make command argmatcher.
local flags = {}
local am = clink.argmatcher(cname)
if c.descs then
am:adddescriptions(c.descs)
end
for _,f in ipairs(c.flags) do
if f[2] then
table.insert(flags, f[1]..links[f[2]])
else
table.insert(flags, f[1])
end
end
if c.conditions then
local conditions = c.conditions
flags.onarg = onarg_contains_opt
table.insert(flags, function (word, word_index, line_state, match_builder, user_data) -- luacheck: no unused
clink.onfiltermatches(function (matches)
return do_filter(matches, conditions, user_data)
end)
end)
end
am:addflags(flags)
end
end
local function oncommand(line_state, info)
if info.file ~= '' and not clink.getargmatcher(line_state) then
local dir = path.getdirectory(info.file)
local name = path.getbasename(info.file)
local fish = path.join(dir, name..'.fish')
if not os.isfile(fish) then
fish = path.join(path.join(dir, 'autocomplete'), name..'.fish')
if not os.isfile(fish) then
fish = path.join(path.join(dir, 'complete'), name..'.fish')
if not os.isfile(fish) then
local completions_dir = settings.get('fishcomplete.completions_dir') or ''
if completions_dir == '' then
return
end
fish = path.join(completions_dir, name..'.fish')
if not os.isfile(fish) then
return
end
end
end
end
local commands, failures = parse_fish_completions(name, fish)
generate_completions(commands)
if not settings.get('fishcomplete.banner') then
return
end
local top = '\x1b[s\x1b[H'
local restore = '\x1b[K\x1b[m\x1b[u'
fish = path.getname(fish)
if not failures then
clink.print(top..'\x1b[0;48;5;56;1;97mCompletions loaded from "'..fish..'".'..restore, NONL)
else
local failure = failures[1]
failure = failure and '; '..failure..'.' or '.'
clink.print(top..'\x1b[0;48;5;52;1;97mFailed reading "'..fish..'"'..failure..restore, NONL)
end
end
end
clink.oncommand(oncommand)