-
Notifications
You must be signed in to change notification settings - Fork 6
/
fzf.lua
1364 lines (1225 loc) · 49.9 KB
/
fzf.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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--------------------------------------------------------------------------------
-- FZF integration for Clink.
--
-- Clink is available at https://chrisant996.github.io/clink
-- FZF is available from https://github.com/junegunn/fzf
--
-- Either put fzf.exe in a directory listed in the system PATH environment
-- variable, or run 'clink set fzf.exe_location <put_full_exe_name_here>' to
-- tell Clink where to find fzf.exe (for example c:\tools\fzf.exe).
--
-- To use FZF integration, you may set key bindings manually in your .inputrc
-- file, or you may use the default key bindings. To use the default key
-- bindings, run 'clink set fzf.default_bindings true'.
--
-- The key bindings when 'fzf.default_bindings' is true are as follows. They
-- are presented in .inputrc file format for convenience, if you want to add
-- them to your .inputrc manually (perhaps with modifications).
--
--
-- NOTE: If multiple copies of this script are loaded in the same Clink
-- session, only the last one initializes itself and the others are
-- ignored.
--
--
-- luacheck: push
-- luacheck: no max line length
--[[
# Default key bindings for fzf with Clink.
"\C-t": "luafunc:fzf_file" # Ctrl+T lists files recursively; choose one or multiple to insert them.
"\C-r": "luafunc:fzf_history" # Ctrl+R lists history entries; choose one to insert it.
"\M-c": "luafunc:fzf_directory" # Alt+C lists subdirectories; choose one to 'cd /d' to it.
"\M-b": "luafunc:fzf_bindings" # Alt+B lists key bindings; choose one to invoke it.
"\t": "luafunc:fzf_tab" # Tab uses fzf to filter match completions, but only when preceded by '**' (recursive).
"\e[27;5;32~": "luafunc:fzf_complete_force" # Ctrl+Space uses fzf to filter match completions (and supports '**' for recursive).
]]
--
-- The available settings are as follows.
-- The settings can be controlled via 'clink set'.
--
-- fzf.default_bindings Controls whether to apply default bindings.
-- This is false by default, to avoid interference
-- with your existing key bindings.
--
-- fzf.exe_location Specifies the location of fzf.exe if not in the
-- system PATH. This isn't just a directory name,
-- it's the full path name of the exe file.
-- For example, c:\tools\fzf.exe or etc.
--
-- fzf.show_descriptions Show match descriptions when available. Fzf
-- searches in the description text as well.
--
-- fzf.color_descriptions Apply color to match descriptions when shown.
-- Uses the color.description setting, and adds
-- the --ansi flag when invoking fzf.
--
-- fzf.height Height to use for the fzf --height flag. See
-- fzf documentation on --height for values.
--
--
-- Optional: You can set the following environment variables to customize the
-- behavior:
--
-- FZF_DEFAULT_OPTS = fzf options applied to all fzf invocations.
--
-- FZF_CTRL_T_OPTS = fzf options for fzf_file() function.
-- FZF_CTRL_R_OPTS = fzf options for fzf_history() function.
-- FZF_ALT_C_OPTS = fzf options for fzf_directory() function.
-- FZF_BINDINGS_OPTS = fzf options for fzf_bindings() function.
-- FZF_COMPLETION_OPTS = fzf options for the completion functions
-- (fzf_complete, fzf_menucomplete,
-- fzf_selectcomplete, and etc).
-- FZF_COMPLETE_OPTS = an older name for FZF_COMPLETION_OPTS.
--
-- FZF_CTRL_T_COMMAND = command to run for collecting files for
-- fzf_file() function.
-- FZF_ALT_C_COMMAND = command to run for collecting directories for
-- fzf_directory() function.
--
-- FZF_COMPLETION_DIR_COMMANDS = commands that should complete only
-- directories, separated by spaces.
--
-- FZF_ICON_WIDTH = number of cells/spaces to strip from the
-- beginning of each match, to remove icons that
-- inserted by customized FZF_CTRL_T_COMMAND and
-- FZF_ALT_C_COMMAND commands.
--
-- If your terminal supports sixels and you configure fzf to use the
-- fzf-preview.cmd script, then you can set the environment variable
-- CLINK_FZF_PREVIEW_SIXELS to tell the fzf-preview.cmd script to tell
-- chafa to use sixels. (Set it to any value except blank.)
--
-- To get file icons to show up in FZF, you can use DIRX v0.9 or newer with
-- Clink v1.6.5, and set the FZF env vars like this:
--
-- set FZF_CTRL_T_COMMAND=dirx.exe /b /s /X:d /a:-s-h --bare-relative --icons=always --utf8 $dir
-- set FZF_ALT_C_COMMAND=dirx.exe /b /s /X:d /a:d-s-h --bare-relative --icons=always --utf8 $dir
-- set FZF_ICON_WIDTH=2
--
-- If you want it to recurse into hidden directories, then remove the `/X:d`
-- part from the commands in the environment variables.
--
-- If you want it to list hidden files and directories, then remove the `-h`
-- part at the end of the `/a:` flags in the environment variables.
--
-- DIRX is available at https://github.com/chrisant996/dirx
-- Clink is available at https://github.com/chrisant996/clink
--
-- luacheck: pop
--------------------------------------------------------------------------------
-- Compatibility check.
if not io.popenrw then
print('fzf.lua requires a newer version of Clink; please upgrade.')
return
end
-- luacheck: globals fzf_loader_arbiter
fzf_loader_arbiter = fzf_loader_arbiter or {}
if fzf_loader_arbiter.initialized then
local msg = 'fzf.lua was already fully initialized'
if fzf_loader_arbiter.loaded_source then
msg = msg..' ('..fzf_loader_arbiter.loaded_source..')'
end
msg = msg..', but another copy got loaded later'
local info = debug.getinfo(1, "S")
local source = info and info.source or nil
if source then
msg = msg..' ('..source..')'
end
log.info(msg..'.')
return
end
--------------------------------------------------------------------------------
-- Settings available via 'clink set'.
--
-- IMPORTANT: These must be added upon load; attempting to defer this until
-- onbeginedit causes 'clink set' to not know about them. This is the one part
-- of the script that can't fully support the goal of "newest version wins".
local function maybe_add(name, ...)
if settings.get(name) == nil then
settings.add(name, ...)
end
end
maybe_add('fzf.height', '40%', 'Height to use for the --height flag')
maybe_add('fzf.exe_location', '', 'Location of fzf.exe if not on the PATH',
"This isn't just a directory name, it's the full path name of the\n"..
"exe file. For example, c:\\tools\\fzf.exe or etc.")
if console.cellcount and console.plaintext then
maybe_add('fzf.show_descriptions', true, 'Show match descriptions when available',
'When enabled, fzf also searches in the match description text.')
maybe_add('fzf.color_descriptions', false, 'Apply color to match descriptions when shown',
'Uses the color defined in the color.description setting, and adds\n'..
'the --ansi flag when invoking fzf.')
end
if rl.setbinding then
maybe_add(
'fzf.default_bindings',
false,
'Use default key bindings',
'To avoid interference with your existing key bindings, key bindings for\n'..
'fzf are initially not enabled. Set this to true to enable the default\n'..
'key bindings for fzf, or add bindings manually to your .inputrc file.\n\n'..
'Changing this takes effect for the next Clink session.')
end
--------------------------------------------------------------------------------
-- Helpers.
local diag = false
local fzf_complete_intercept = false
local describemacro_list = {}
local interceptor
local function join_str(a, b)
a = a or ''
b = b or ''
if a == '' then
return b
elseif b == '' then
return a
else
return a..' '..b
end
end
local function sgr(code)
if not code then
return '\x1b[m'
elseif string.byte(code) == 0x1b then
return code
else
return '\x1b['..code..'m'
end
end
local function describe_commands()
if describemacro_list then
for _, d in ipairs(describemacro_list) do
rl.describemacro(d.macro, d.desc)
end
describemacro_list = nil
end
end
local function add_help_desc(macro, desc)
if rl.describemacro and describemacro_list then
table.insert(describemacro_list, { macro=macro, desc=desc })
end
end
local function fix_unsafe_quotes(s)
local fixed = ''
local i = 1
while i <= #s do
-- Find open quote. If none, all is well.
local j = string.find(s, '"', i)
if j then
fixed = fixed..s:sub(i, j - 1)
else
fixed = fixed..s:sub(i)
break
end
i = j + 1
-- Find close quote.
local t
local k = string.find(s, '"', i)
if k then
t = s:sub(i, k - 1)
else
t = s:sub(i)
end
if t:find('[ +=;,]') then
-- Convert the quotes, otherwise they can lead to CMD malfunctions
-- if fzf later passes the description to another program (such as
-- a preview script).
if k then
--fixed = fixed.."''"..t.."''"
fixed = fixed.."“"..t.."”"
else
--fixed = fixed.."''"..t
fixed = fixed.."”"..t
end
else
-- The quotes are fine, so don't convert them.
if k then
fixed = fixed..'"'..t..'"'
else
fixed = fixed..'"'..t
end
end
-- Next.
if not k then
break
end
i = k + 1
end
return fixed
end
local function need_cd_drive(dir)
local drive = path.getdrive(dir)
if drive then
local cwd = os.getcwd()
if cwd then
local cwd_drive = path.getdrive(cwd)
if cwd_drive and cwd_drive:lower() == drive:lower() then
return
end
end
end
return drive
end
local function maybe_strip_icon(str)
local width = os.getenv("FZF_ICON_WIDTH")
if width then
width = tonumber(width)
if width and width > 0 then
if unicode.iter then
local iter = unicode.iter(str)
local c = iter()
if c then
return str:sub(#c + (width - 1) + 1)
end
else
if str:byte() == 32 then
return str:sub(width + 1)
elseif width > 1 then
local tmp = str:match("^[^ ]+(.*)$")
if tmp then
return tmp:sub(width)
end
end
end
end
end
return str
end
local function make_query_string(rl_buffer)
local s = rl_buffer:getbuffer()
-- Must strip % because there's no way to escape % when the command line
-- gets processed first by cmd, as it does when using io.popen() and etc.
-- This is the only thing that gets dropped; everything else gets escaped.
s = s:gsub('%%', '')
if #s > 0 then
-- Must double ^ so it roundtrips correctly.
s = s:gsub('%^', '^^')
-- The 2N rule for escaping quotes and backslashes:
--
-- - 2n backslashes followed by a quotation mark produce n backslashes
-- followed by begin/end quote. This does not become part of the
-- parsed argument, but toggles the "in quotes" mode.
-- - (2n) + 1 backslashes followed by a quotation mark again produce n
-- backslashes followed by a quotation mark literal ("). This does not
-- toggle the "in quotes" mode.
-- - n backslashes not followed by a quotation mark simply produce n
-- backslashes.
--
-- https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw
local tmp = ''
local i = 1
while i <= #s do
local pre,suf = s:match('^(.-)(\\*)"', i)
if pre and suf then
tmp = tmp..pre..suf..suf..'\\"'
i = i + #pre + #suf + 1
else
tmp = tmp..s:sub(i)
break
end
end
s = tmp
-- Must double any trailing \ characters and add another, since we're
-- about to append a trailing double quote (same 2N rule as above).
local pre,suf = s:match('^(.-)(\\*)$')
if pre and suf then
s = pre..suf..suf
end
s = '--query "'..s..'"'
end
return s
end
local function get_fzf(mode, addl_options)
local command = settings.get('fzf.exe_location')
if not command or command == '' then
command = 'fzf.exe'
end
command = command:gsub('"', '')
-- It's important to invoke an .exe file, otherwise quoting for --query can
-- malfunction and potentially fall into a code injection situation.
if path.getname(command) ~= command then
local command_path = path.toparent(command)
command = path.join(command_path, path.getbasename(command)..".exe")
else
command = path.getbasename(command)..".exe"
end
command = '"'..command..'"'
local height = settings.get('fzf.height')
if height and height ~= '' then
command = join_str(command, '--height '..height)
end
command = join_str(command, addl_options)
local options = os.getenv('FZF_DEFAULT_OPTS')
if mode == 'complete' then
options = join_str('--reverse', options)
options = join_str(options, os.getenv('FZF_COMPLETION_OPTS') or os.getenv('FZF_COMPLETE_OPTS'))
elseif mode == 'dirs' then
options = join_str('--reverse --scheme=path', options)
options = join_str(options, os.getenv('FZF_ALT_C_OPTS'))
elseif mode == 'path' then
options = join_str('--reverse --scheme=path', options)
options = join_str(options, os.getenv('FZF_CTRL_T_OPTS'))
elseif mode == 'history' then
options = join_str('--scheme=history --bind=ctrl-r:toggle-sort', options)
options = join_str(options, os.getenv('FZF_CTRL_R_OPTS'))
options = join_str(options, '+m')
elseif mode == 'bindings' then
options = join_str(options, os.getenv('FZF_BINDINGS_OPTS'))
options = join_str(options, '-i')
else
error('Unrecognized mode ('..tostring(mode)..').')
end
if options then
command = join_str(command, options)
end
return command
end
local function get_clink()
local exe = CLINK_EXE
if not exe or exe == '' then
return ''
end
return '"'..exe..'"'
end
local function need_quote(word)
return word and word:find("[ &()[%]{}^=;!%%'+,`~]") and true
end
local function maybe_quote(word)
if need_quote(word) then
word = '"' .. word .. '"'
end
return word
end
local function escape_quotes(text)
return text:gsub('"', '\\"')
end
local function chcp(cp)
local ret
if cp == 65001 then
local r = io.popen('2>nul chcp')
if r then
local line = r:read()
ret = line:match('%d+')
r:close()
cp = '65001'
end
end
if type(cp) == 'string' then
os.execute('>nul 2>nul chcp '..cp)
end
return ret
end
local function replace_dir(str, word)
if word == '.' then
word = nil
end
if word then
if word:find('^%.[/\\]') then
word = word:match('^%.[/\\]+(.*)$')
end
word = rl.expandtilde(word)
if not os.isdir(word) then
word = word.."*"
end
word = maybe_quote(word)
end
return str:gsub('$dir', word or '')
end
local function get_word_at_cursor(line_state)
if line_state:getwordcount() > 0 then
local info = line_state:getwordinfo(line_state:getwordcount())
if info then
local line = line_state:getline()
local word = line:sub(info.offset, line_state:getcursor() - 1)
if word and #word > 0 then
word = word:gsub('"', '')
word = word:gsub("'", '')
return word
end
end
end
end
local function get_word_insert_bounds(line_state)
if line_state:getwordcount() > 0 then
local info = line_state:getwordinfo(line_state:getwordcount())
if info then
local first = info.offset
local last = line_state:getcursor() - 1
local quote
local delimit
if info.quoted then
local line = line_state:getline()
first = first - 1
quote = line:sub(first, first)
local eq = line:sub(last + 1, last + 1)
if eq == '' or eq == ' ' or eq == '\t' then
delimit = true
end
end
return first, last, quote, delimit
end
end
end
local function get_ctrl_t_command(dir)
local command = os.getenv('FZF_CTRL_T_COMMAND')
if not command then
command = 'dir /b /s /a:-s $dir'
end
command = replace_dir(command, dir)
return command
end
local function get_alt_c_command(dir)
local command = os.getenv('FZF_ALT_C_COMMAND')
if not command then
command = 'dir /b /s /a:d-s $dir'
end
command = replace_dir(command, dir)
return command
end
local function is_trigger(line_state)
local word = get_word_at_cursor(line_state)
if word and word:sub(#word - 1) == '**' then
return word:sub(1, #word - 2)
end
end
local function is_dir_command(line_state)
local command = line_state:getword(1)
local dir_commands = os.getenv('FZF_COMPLETION_DIR_COMMANDS') or 'cd chdir rd rmdir pushd'
for _,c in ipairs(string.explode(dir_commands)) do
if string.equalsi(c, command) then
return true
end
end
end
local function insert_matches(rl_buffer, first, last, has_quote, matches)
if matches and matches[1] then
local quote = has_quote or '"'
rl_buffer:beginundogroup()
rl_buffer:remove(first, last + 1)
rl_buffer:setcursor(first)
for _,match in ipairs(matches) do
match = maybe_strip_icon(match)
local use_quote = ((has_quote or need_quote(match)) and quote) or ''
rl_buffer:insert(use_quote)
rl_buffer:insert(match)
rl_buffer:insert(use_quote)
rl_buffer:insert(' ')
end
rl_buffer:endundogroup()
end
end
local function fzf_recursive(rl_buffer, line_state, search, dirs_only) -- luacheck: no unused
local dir, word
dir = path.getdirectory(search)
word = path.getname(search)
local command, mode
if dirs_only then
command = get_alt_c_command(dir)
mode = 'dirs'
else
command = get_ctrl_t_command(dir)
mode = 'complete'
end
local first, last, has_quote, delimit = get_word_insert_bounds(line_state) -- luacheck: no unused
local orig_cp = chcp(65001)
local r = io.popen('2>nul '..command..' | '..get_fzf(mode)..' -q "'..word..'"')
if not r then
rl_buffer:ding()
chcp(orig_cp)
return
end
-- Read filtered matches.
local match
while (true) do
local line = r:read('*line')
if not line then
break
end
if not match then
match = line
end
end
r:close()
chcp(orig_cp)
if match then
insert_matches(rl_buffer, first, last, has_quote, { match })
end
end
-- luacheck: globals fzf_complete_internal
function fzf_complete_internal(rl_buffer, line_state, force, completion_command)
local search = is_trigger(line_state)
if completion_command == '' then
completion_command = nil
end
if search then
-- Gather files and/or dirs recursively, and show them in fzf.
local dirs_only = is_dir_command(line_state)
fzf_recursive(rl_buffer, line_state, search, dirs_only)
rl_buffer:refreshline()
elseif not force then
-- Invoke the normal complete command.
rl.invokecommand(completion_command or 'complete')
else
-- Intercept matches Use match filtering to let
fzf_complete_intercept = true
rl.invokecommand(completion_command or 'complete')
if fzf_complete_intercept then
rl_buffer:ding()
end
fzf_complete_intercept = false
rl_buffer:refreshline()
end
end
--------------------------------------------------------------------------------
-- Functions for use with 'luafunc:' key bindings.
-- Get binding for Tab, so that fzf_tab can forward to it.
local tab_binding = "complete"
if rl.getbinding then
local tab = rl.getbinding([["\t"]])
if tab == "complete" or
tab == "menu-complete" or tab == "menu-complete-backward" or
tab == "old-menu-complete" or tab == "old-menu-complete-backward" or
tab == "clink-select-complete" or tab == "clink-popup-complete" then
tab_binding = tab
end
end
local function apply_default_bindings()
if settings.get('fzf.default_bindings') then
tab_binding = rl.getbinding([["\t"]])
rl.setbinding([["\C-t"]], [["luafunc:fzf_file"]])
rl.setbinding([["\C-r"]], [["luafunc:fzf_history"]])
rl.setbinding([["\M-c"]], [["luafunc:fzf_directory"]])
rl.setbinding([["\M-b"]], [["luafunc:fzf_bindings"]])
rl.setbinding([["\t"]], [["luafunc:fzf_tab"]])
rl.setbinding([["\e[27;5;32~"]], [["luafunc:fzf_complete_force"]])
end
end
-- luacheck: globals fzf_complete
add_help_desc("luafunc:fzf_complete",
"Use fzf for completion if ** is immediately before the cursor position")
function fzf_complete(rl_buffer, line_state)
fzf_complete_internal(rl_buffer, line_state, false)
end
-- luacheck: globals fzf_menucomplete
add_help_desc("luafunc:fzf_menucomplete",
"Use fzf for completion after ** otherwise use 'menu-complete' command")
function fzf_menucomplete(rl_buffer, line_state)
fzf_complete_internal(rl_buffer, line_state, false, "menu-complete")
end
-- luacheck: globals fzf_oldmenucomplete
add_help_desc("luafunc:fzf_oldmenucomplete",
"Use fzf for completion after ** otherwise use 'old-menu-complete' command")
function fzf_oldmenucomplete(rl_buffer, line_state)
fzf_complete_internal(rl_buffer, line_state, false, "old-menu-complete")
end
-- luacheck: globals fzf_selectcomplete
add_help_desc("luafunc:fzf_selectcomplete",
"Use fzf for completion after ** otherwise use 'clink-select-complete' command")
function fzf_selectcomplete(rl_buffer, line_state)
fzf_complete_internal(rl_buffer, line_state, false, "clink-select-complete")
end
-- luacheck: globals fzf_complete_force
add_help_desc("luafunc:fzf_complete_force",
"Use fzf for completion")
function fzf_complete_force(rl_buffer, line_state)
fzf_complete_internal(rl_buffer, line_state, true)
end
-- luacheck: globals fzf_tab
add_help_desc("luafunc:fzf_tab",
"Use fzf for completion if ** is immediately before the cursor position")
function fzf_tab(rl_buffer, line_state)
fzf_complete_internal(rl_buffer, line_state, false, tab_binding)
end
-- luacheck: globals fzf_history
add_help_desc("luafunc:fzf_history",
"List history entries; choose one to insert it (press DEL to delete selected history entry)")
function fzf_history(rl_buffer)
local clink_command = get_clink()
if #clink_command == 0 then
rl_buffer:ding()
return
end
-- Build command to get history for the current Clink session.
local history = clink_command..' --session '..clink.getsession()..' history --time-format " "'
if diag then
history = history..' --diag'
end
-- Make key binding for DEL to delete a history entry.
local history_delete = escape_quotes(clink_command..' --session '..clink.getsession()..' history delete {1}')
local history_reload = escape_quotes(history)
local del_binding = '--bind "del:execute-silent('..history_delete..')+reload('..history_reload..')"'
-- This produces a '--query' string by stripping certain problematic
-- characters from the input line. This still does a good job of matching,
-- because fzf uses fuzzy matching.
local qs = make_query_string(rl_buffer)
local r = io.popen('2>nul '..history..' | '..get_fzf('history', del_binding)..' -i --tac '..qs)
if not r then
rl_buffer:ding()
return
end
local str = r:read('*all')
str = str and str:gsub('[\r\n]', '') or ''
r:close()
-- If something was selected, insert it.
if #str > 0 then
rl_buffer:beginundogroup()
rl_buffer:remove(0, -1)
rl_buffer:insert(string.gsub(str, '^%s*%d+%s*(.-)$', '%1'))
rl_buffer:endundogroup()
end
rl_buffer:refreshline()
end
-- luacheck: globals fzf_file
add_help_desc("luafunc:fzf_file",
"List files recursively; choose one or multiple to insert them")
function fzf_file(rl_buffer, line_state)
local dir = get_word_at_cursor(line_state)
local command = get_ctrl_t_command(dir)
local first, last, has_quote, delimit = get_word_insert_bounds(line_state) -- luacheck: no unused
local orig_cp = chcp(65001)
local r = io.popen(command..' 2>nul | '..get_fzf('path')..' -i -m')
if not r then
rl_buffer:ding()
chcp(orig_cp)
return
end
local matches = {}
for str in r:lines() do
str = str and str:gsub('[\r\n]+', ' ') or ''
str = str:gsub(' +$', '')
if #str > 0 then
table.insert(matches, str)
end
end
r:close()
chcp(orig_cp)
insert_matches(rl_buffer, first, last, has_quote, matches)
rl_buffer:refreshline()
end
-- luacheck: globals fzf_directory
add_help_desc("luafunc:fzf_directory",
"List subdirectories; choose one to 'cd /d' to it")
function fzf_directory(rl_buffer, line_state)
local dir = get_word_at_cursor(line_state)
local command = get_alt_c_command(dir)
local orig_cp = chcp(65001)
local r = io.popen(command..' 2>nul | '..get_fzf('dirs')..' -i')
if not r then
rl_buffer:ding()
chcp(orig_cp)
return
end
local str = r:read('*all')
str = str and str:gsub('[\r\n]', '') or ''
r:close()
chcp(orig_cp)
if #str > 0 then
str = maybe_strip_icon(str)
rl_buffer:beginundogroup()
rl_buffer:remove(0, -1)
local drive = need_cd_drive(str)
str = maybe_quote(str)
if drive then
rl_buffer:insert(drive..' & cd '..str)
else
rl_buffer:insert('cd '..str)
end
rl_buffer:endundogroup()
rl_buffer:refreshline()
rl.invokecommand('accept-line')
return
end
rl_buffer:refreshline()
end
-- luacheck: globals fzf_bindings
add_help_desc("luafunc:fzf_bindings",
"List key bindings; choose one to invoke it")
function fzf_bindings(rl_buffer)
if not rl.getkeybindings then
rl_buffer:beginoutput()
print('fzf_bindings() in fzf.lua requires a newer version of Clink; please upgrade.')
return
end
local bindings = rl.getkeybindings()
if #bindings <= 0 then
rl_buffer:refreshline()
return
end
-- Start fzf. Extra quotes are needed to work around CMD quoting issue.
local line
local r,w = io.popenrw('"'..get_fzf('bindings')..'"')
if r and w then
-- Write key bindings to the write pipe.
for _,kb in ipairs(bindings) do
w:write(kb.key..' : '..kb.binding..'\n')
end
w:close()
-- Read filtered matches.
line = r:read('*line')
r:close()
end
rl_buffer:refreshline()
if line and #line > 0 then
local binding = line:sub(#bindings[1].key + 3 + 1)
rl.invokecommand(binding)
end
end
--------------------------------------------------------------------------------
-- Match generator.
local function filter_matches(matches)
if not fzf_complete_intercept then
return
end
if #matches <= 1 then
return
end
local show_descriptions = settings.get('fzf.show_descriptions')
local color_description = settings.get('fzf.color_descriptions') and sgr(settings.get('color.description'))
local norm = sgr()
-- Match text to be displayed.
local strings = {}
local longest = 0
local any_desc
for _,m in ipairs(matches) do
local s
if m.display and console.plaintext then
s = console.plaintext(m.display)
else
s = m.match
end
table.insert(strings, s)
if show_descriptions then
local cells = console.cellcount(s)
if longest < cells then
longest = cells
end
if m.description and m.description ~= '' then
any_desc = true
end
end
end
-- Start fzf. Extra quotes are needed to work around CMD quoting issue.
local addl_options = (color_description and any_desc) and '--ansi' or nil
local r,w = io.popenrw('"'..get_fzf('complete', addl_options)..'"')
if not r or not w then
return
end
-- Write matches to the write pipe.
local which = {}
for i,m in ipairs(matches) do
local text = strings[i]
if show_descriptions and m.description and m.description ~= '' then
local desc = fix_unsafe_quotes(m.description)
text = text..string.rep(' ', longest + 4 - console.cellcount(text))
if color_description then
text = text..color_description..desc..norm
else
text = text..console.plaintext(desc)
end
end
-- Must use plaintext() because fzf always strips ANSI color codes when
-- it writes the results, even when the --ansi flag is used.
local plain = console.plaintext(text)
if not which[plain] then
which[plain] = m
end
w:write(text..'\n')
end
w:close()
-- Read filtered matches.
local ret = {}
while (true) do
local line = r:read('*line')
if not line then
break
end
local m = which[line]
if m then
table.insert(ret, m)
end
end
r:close()
-- Yay, successful; clear it to not ding.
fzf_complete_intercept = false
return ret
end
local function create_generator()
if not interceptor then
interceptor = clink.generator(0)
function interceptor:generate(line_state, match_builder) -- luacheck: no unused
if fzf_complete_intercept then
-- Use two layers of onfiltermatches callbacks:
--
-- The generator runs early. So the onfiltermatches callback
-- function it registers is the first filter function. But then
-- other filter functions (e.g. to remove "hidden" matches) run
-- AFTER fzf is invoked. So fzf shows matches that should be
-- hidden. Oops.
--
-- To compensate, the first onfiltermatches callback function
-- needs to register a second onfiltermatches callback function,
-- which then ends up running LAST. Then fzf doesn't list
-- "hidden" matches.
clink.onfiltermatches(function(matches)
clink.onfiltermatches(filter_matches)
return matches
end)
end
return false
end
end
end
--------------------------------------------------------------------------------
-- Argmatcher helpers (based on modules\arghelper.lua from
-- https://github.com/vladimir-kotikov/clink-completions).
local tmp = clink.argmatcher and clink.argmatcher() or clink.arg.new_parser()
local meta = getmetatable(tmp)
local addexarg
local addexflags
do
local link = "link"..tmp
local meta_link = getmetatable(link)
local function is_parser(x)
return getmetatable(x) == meta
end
local function is_link(x)
return getmetatable(x) == meta_link
end