-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathfzf_git.lua
More file actions
1189 lines (1055 loc) · 42.3 KB
/
Copy pathfzf_git.lua
File metadata and controls
1189 lines (1055 loc) · 42.3 KB
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 git integration for Clink.
-- Based on https://github.com/junegunn/fzf-git.sh
--
--
-- This provides Clink key bindings for git objects, powered by fzf.
--
-- Each key binding allows you to browse through git objects of a certain type,
-- and select the objects you want to insert into your command line.
--
-- Ctrl-G,? : Show key bindings for fzf_git
-- Ctrl-G,Ctrl-F : Use fzf for Files
-- Ctrl-G,Ctrl-B : Use fzf for Branches
-- Ctrl-G,Ctrl-T : Use fzf for Tags
-- Ctrl-G,Ctrl-R : Use fzf for Remotes
-- Ctrl-G,Ctrl-H : Use fzf for commit Hashes
-- Ctrl-G,Ctrl-S : Use fzf for Stashes
-- Ctrl-G,Ctrl-L : Use fzf for reflogs
-- Ctrl-G,Ctrl-W : Use fzf for Worktrees
-- Ctrl-G,Ctrl-E : Use fzf for Each ref (git for-each-ref)
--
--
-- REQUIREMENTS:
--
-- This requires Clink, FZF, and git:
--
-- - Clink is available at https://chrisant996.github.io/clink
-- - FZF is available from https://github.com/junegunn/fzf
-- (version 0.67.0 or newer work; older versions may or may not work)
-- - Git is available from https://git-scm.com/install
-- (version 2.48.1 or newer work; older versions may or may not work)
--
--
-- DEFAULT KEY BINDINGS:
--
-- The default key bindings are listed below in a format suitable for pasting
-- into your .inputrc file for convenience, for example if you want to modify
-- any of the bindings. The default bindings can be disabled by running
-- 'clink set fzf_git.default_bindings false'.
--
-- luacheck: no max line length
--[[
# Default key bindings for fzf_git with Clink.
# Help bindings.
"\C-g?": "luafunc:fzf_git_help" # Ctrl-G,?
"\C-g\e[27;5;191~": "luafunc:fzf_git_help" # Ctrl-G,Ctrl-/
# Ctrl-Letter bindings.
"\C-g\C-f": "luafunc:fzf_git_files" # Ctrl-G,Ctrl-F
"\C-g\C-b": "luafunc:fzf_git_branches" # Ctrl-G,Ctrl-B
"\C-g\C-t": "luafunc:fzf_git_tags" # Ctrl-G,Ctrl-T
"\C-g\C-r": "luafunc:fzf_git_remotes" # Ctrl-G,Ctrl-R
"\C-g\C-h": "luafunc:fzf_git_commit_hashes" # Ctrl-G,Ctrl-H
"\C-g\C-s": "luafunc:fzf_git_stashes" # Ctrl-G,Ctrl-S
"\C-g\C-l": "luafunc:fzf_git_reflogs" # Ctrl-G,Ctrl-L
"\C-g\C-w": "luafunc:fzf_git_worktrees" # Ctrl-G,Ctrl-W
"\C-g\C-e": "luafunc:fzf_git_eachref" # Ctrl-G,Ctrl-E
# Plain Letter bindings.
"\C-g\f": "luafunc:fzf_git_files" # Ctrl-G,F
"\C-g\b": "luafunc:fzf_git_branches" # Ctrl-G,B
"\C-g\t": "luafunc:fzf_git_tags" # Ctrl-G,T
"\C-g\r": "luafunc:fzf_git_remotes" # Ctrl-G,R
"\C-g\h": "luafunc:fzf_git_commit_hashes" # Ctrl-G,H
"\C-g\s": "luafunc:fzf_git_stashes" # Ctrl-G,S
"\C-g\l": "luafunc:fzf_git_reflogs" # Ctrl-G,L
"\C-g\w": "luafunc:fzf_git_worktrees" # Ctrl-G,W
"\C-g\e": "luafunc:fzf_git_eachref" # Ctrl-G,E
]]
-- CLINK SETTINGS:
--
-- The available settings are as follows.
-- These settings can be controlled via 'clink set'.
--
-- fzf_git.default_bindings Controls whether to apply default
-- bindings. This is true by default.
--
-- fzf_git.height Height to use for the fzf --height flag.
-- (See fzf documentation on --height.)
--
-- 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.
--
-- NOTE: the fzf.exe_location setting is shared by
-- multiple fzf scripts.
--
--
-- ENVIRONMENT VARIABLES:
--
-- You can optionally set the following environment variables to customize the
-- behavior.
--
-- FZF_GIT_CAT = Defines the preview command used for
-- displaying the file.
-- FZF_GIT_COLOR = Control colors in the list:
-- 'always' (default) shows colors.
-- 'never' suppresses colors.
-- FZF_GIT_PAGER = Specifies the pager command for the
-- preview window.
-- FZF_GIT_PREVIEW_COLOR = Control colors in the preview window:
-- 'always' (default) shows colors.
-- 'never' suppresses colors.
--
-- FZF_GIT_DEFAULT_COLORS = Defines the default colors for fzf.
-- This is passed to fzf via the --color
-- flag.
-- FZF_GIT_EDITOR = Defines the command for editing a file.
-- Falls back to %EDITOR% or notepad.exe if
-- not set.
--
--
-- KNOWN ISSUES:
--
-- - Ctrl-D in fzf_git_commit_hashes prints no output and doesn't allow
-- input to the pager. This is an fzf bug, which is tracked in:
-- https://github.com/junegunn/fzf/issues/4260#issuecomment-3931448651
-- - In a shallow clone, fzf_git_files expands the sparse index to a full
-- index. I'd like to somehow scope fzf_git_files better, but I'm not sure
-- what would be a good solution.
-- - If multiple copies of this script are loaded in the same Clink session,
-- the last one loaded takes responsibility to initialize itself, and the
-- others are ignored.
--------------------------------------------------------------------------------
-- Compatibility check.
if (clink.version_encoded or 0) < 10070000 then
-- The git functions are needed from v1.7.0.
print('fzf_git.lua requires a newer version of Clink; please upgrade.')
return
end
-- luacheck: globals fzf_git_loader_arbiter
fzf_git_loader_arbiter = fzf_git_loader_arbiter or {}
if fzf_git_loader_arbiter.initialized then
local msg = 'fzf_git.lua was already fully initialized'
if fzf_git_loader_arbiter.loaded_source then
msg = msg..' ('..fzf_git_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 type(name) == "string" and settings.get(name) == nil then
settings.add(name, ...)
end
end
-- fzf.exe_location is in common with fzf.lua.
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 exe file.
For example, c:\tools\fzf.exe or etc.]])
maybe_add("fzf_git.height", "50%",
"Height to use for the --height flag",
[[See fzf documentation on --height for possible values.]])
maybe_add(rl.setbinding and "fzf_git.default_bindings", true,
"Use default key bindings for fzf_git integration",
[[Set this to false if it interferes with your existing key bindings, and
you can add bindings manually to your .inputrc file.
Changing this takes effect for the next Clink session.]])
--------------------------------------------------------------------------------
-- REVIEW: what does the $(__fzf_git_pager) usage accomplish in fzf-git.sh?
--[=[
__fzf_git_pager() {
local pager
pager="${FZF_GIT_PAGER:-${GIT_PAGER:-$(git config --get core.pager 2> /dev/null)}}"
echo "${pager:-cat}"
}
--]=]
--------------------------------------------------------------------------------
-- Helpers.
local diag
local describemacro_list = {}
local specific_hash
local __fzf_git_sh_path
local __fzf_git_cmd_path
local __fzf_git_cat_command
local function __fzf_git_color(preview)
if os.getenv("NO_COLOR") then
return "never"
elseif preview and os.getenv("FZF_GIT_PREVIEW_COLOR") then
return os.getenv("FZF_GIT_PREVIEW_COLOR")
else
local color = os.getenv("FZF_GIT_COLOR")
return (color ~= "" and color or "always")
end
end
local function __fzf_git_editor()
return os.getenv("FZF_GIT_EDITOR") or os.getenv("EDITOR") or "notepad.exe"
end
local function search_in_paths(name)
local paths = (os.getenv("path") or ""):explode(";")
for _, dir in ipairs(paths) do
local file = path.join(dir, name)
if os.isfile(file) then
return file, dir
end
end
end
local function get_git_bin_dir()
local name = "git.exe"
local paths = (os.getenv("path") or ""):explode(";")
for _, dir in ipairs(paths) do
local file = path.join(dir, name)
if os.isfile(file) then
local usrbin = path.join(path.toparent(dir), "usr\\bin")
if os.isfile(path.join(usrbin, "bash.exe")) then
return usrbin
end
end
end
end
local function ensure_script_paths()
if not __fzf_git_sh_path then
local info = debug.getinfo(1, "S")
if info.source and info.source:sub(1, 1) == "@" then
local dir = path.toparent(info.source:sub(2))
__fzf_git_sh_path = path.join(dir, "fzf_git_helper.sh")
if not os.isfile(__fzf_git_sh_path) then
log.info(string.format("File does not exist at '%s'.", __fzf_git_sh_path))
__fzf_git_sh_path = nil
end
__fzf_git_cmd_path = path.join(dir, "fzf_git_helper.cmd")
if not os.isfile(__fzf_git_cmd_path) then
log.info(string.format("File does not exist at '%s'.", __fzf_git_cmd_path))
__fzf_git_cmd_path = nil
end
elseif info.source then
log.info(string.format("Unexpected source path '%s'.", info.source))
else
log.info(string.format("Unable to get source path for script."))
end
end
return __fzf_git_sh_path and __fzf_git_cmd_path and true or nil
end
local function __fzf_git_sh()
ensure_script_paths()
return __fzf_git_sh_path
end
local function __fzf_git_cmd()
ensure_script_paths()
return __fzf_git_cmd_path
end
local function __fzf_git_cat()
local cat = os.getenv("FZF_GIT_CAT")
if cat then
return cat
end
if __fzf_git_cat_command == nil then
local def_color = __fzf_git_color(true)
local def_opts = table.concat({
(os.getenv("BAT_STYLE") and "" or "--style=full"),
"--color="..def_color,
"--pager=never",
}, " ")
-- Sometimes bat is installed as batcat
cat = search_in_paths("batcat.exe")
if not cat then
cat = search_in_paths("bat.exe")
end
if cat then
cat = cat.." "..def_opts
else
cat = "type"
end
__fzf_git_cat_command = cat
end
return __fzf_git_cat_command
end
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 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 get_fzf()
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..'"'
return command
end
local function _fzf_git_fzf(args)
-- The fzf command path.
local command = get_fzf()
local height = settings.get('fzf_git.height') or ''
if height ~= '' then
height = '--height '..height
end
-- The fzf_git options for fzf.
-- luacheck: globals __fzf_git_fzf
local opts
local def_colors = os.getenv("FZF_GIT_DEFAULT_COLORS") or "label:blue"
local def_opts = table.concat({
height,
'--tmux 90%,70%',
'--layout reverse --multi --min-height 20+ --border rounded',
'--no-separator --header-border horizontal',
'--border-label-pos 2',
'--color "'..def_colors..'"',
'--preview-window "right,50%" --preview-border line',
'--bind "ctrl-/:change-preview-window(down,50%|hidden|)"',
'--bind "shift-down:preview-down+preview-down,shift-up:preview-up+preview-up,preview-scroll-up:preview-up+preview-up,preview-scroll-down:preview-down+preview-down"',
}, ' ')
if type(__fzf_git_fzf) == "function" then
opts = __fzf_git_fzf(def_opts)
elseif type(__fzf_git_fzf) == "string" then
opts = __fzf_git_fzf
end
opts = opts or def_opts
-- The additional args for fzf.
opts = join_str(opts, args)
return command, opts
end
local function git_check()
-- git_check is the first thing to run in every command, so this is a
-- great place to reinitialize the diag variable.
diag = (tonumber(os.getenv("DEBUG_FZF_GIT") or "0") or 0) > 0
local gitdir = git.getgitdir()
if gitdir and path.getname(gitdir) == ".git" then
return true
end
end
local function need_quote(word)
return word and word:find("[ &()[%]{}^=;!%%'+,`~]") and true
end
local function maybe_quote(word)
if need_quote(word) then
if word:sub(-1) == "\\" then
-- Double any trailing backslashes, per Windows quoting rules.
word = word..word:match("\\+$")
end
word = '"'..word..'"'
end
return word
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 save_var(vars, name, value, append)
vars[name] = os.getenv(name) or ""
if append and vars[name] ~= "" then
value = vars[name].." "..value
end
os.setenv(name, value)
end
local function restore_vars(vars)
for name, value in pairs(vars) do
os.setenv(name, (value ~= "") and value or nil)
end
end
local function insert_matches(rl_buffer, matches, post_process, expect)
if matches and matches[1] then
rl_buffer:beginundogroup()
for _,match in ipairs(matches) do
local text
if not post_process then
text = match
else
text = post_process(match, expect)
-- nil = ignore the match.
-- false = stop inserting matches.
if text == false then
break
end
end
if text then
local q = need_quote(text) and '"' or ''
rl_buffer:insert(q..text..q..' ')
end
expect = nil
end
rl_buffer:endundogroup()
end
end
local function fix_single_quotes(s)
local in_quote
local ignore_quote
local double_single_quote = 0
local out = ""
for i = 1, #s do
local c = string.byte(s, i)
if c == 39 then -- Single quote.
ignore_quote = nil
if in_quote then
if double_single_quote > 0 then
double_single_quote = double_single_quote - 1
out = out..'\\"\\"'
else
out = out..'\\"'
end
else
out = out..'"'
end
elseif c == 92 then -- Backslash.
out = out..string.char(c)
ignore_quote = (string.byte(s, i + 1) == 34)
else
out = out..string.char(c)
if c == 34 and not ignore_quote then
in_quote = not in_quote
elseif c == 32 and in_quote and (string.byte(s, i + 1) == 39) then
double_single_quote = 2
end
ignore_quote = nil
end
end
return out
end
local function apply_replacements(command, fix_single_quotes_in_command)
-- print("APPLY_REPLACEMENTS chkpt 1", command)
if fix_single_quotes_in_command then
command = fix_single_quotes(command)
-- print("APPLY_REPLACEMENTS chkpt 2", command)
end
if not command:find("preview \"%$helper") then
command = command:gsub("preview \"(.+[^\\])\"", "preview \"bash -c '%1'\"")
end
command = command:gsub("%$shell", "bash")
command = command:gsub("%$helper", __fzf_git_cmd():gsub("\\", "\\\\"))
command = command:gsub("/dev/tty", "con")
command = command:gsub("%$__fzf_git", __fzf_git_sh():gsub("\\", "\\\\"))
command = command:gsub("%$%(__fzf_git_color%)", __fzf_git_color())
command = command:gsub("%$%(__fzf_git_color %.%)", __fzf_git_color(true))
command = command:gsub("\\\n%s*", "")
-- print("APPLY_REPLACEMENTS chkpt 3", command)
return command
end
local function run_command(command, expect)
if diag then
print("RUN_COMMAND", command)
end
local r = io.popen(command)
if not r then
log.info("failed to run command: "..command)
return
end
local matches = {}
for str in r:lines() do
str = str and str:gsub('[\r\n]+', ' ') or ''
str = str:gsub(' +$', '')
if expect or str ~= "" then
table.insert(matches, str)
end
expect = nil
end
r:close()
return matches
end
local function do_fzf_git(rl_buffer, line_state, pipe_command, fzf_args, post_process) -- luacheck: no unused
if not git_check() then
rl_buffer:ding()
return
end
if not ensure_script_paths() then
rl_buffer:beginoutput()
print("fzf_git error: Unable to find support scripts; see clink.log for details.")
return
end
local usrbin = get_git_bin_dir()
if not usrbin then
rl_buffer:beginoutput()
print("fzf_git error: Unable to find git\\usr\\bin directory.")
return
end
local expect = fzf_args:find("%-%-expect=") and true or nil
fzf_args = apply_replacements(fzf_args)--, true--[[fix_single_quotes]])
local program, options = _fzf_git_fzf(fzf_args)
local orig_cp = chcp(65001)
local old_vars = {}
local old_path = os.getenv("PATH")
save_var(old_vars, "__fzf_git_color", __fzf_git_color())
save_var(old_vars, "__fzf_git_color_", __fzf_git_color(true))
save_var(old_vars, "__fzf_git_cat", __fzf_git_cat())
save_var(old_vars, "__fzf_git_editor", __fzf_git_editor())
save_var(old_vars, "__fzf_git_sh", __fzf_git_sh())
save_var(old_vars, "FZF_DEFAULT_OPTS", options, true--[[append]])
-- Prepend the Git bin dir to the system PATH so that bash, awk, sed, and
-- so on can be found automatically, without needing to adjust the command
-- syntax copied from the fzf-git.sh script.
save_var(old_vars, "PATH", usrbin..";"..old_path)
if diag then
print("FZF_DEFAULT_OPTS", os.getenv("FZF_DEFAULT_OPTS"))
end
local matches
if type(pipe_command) == "function" then
if diag then
print("POPENRW", program)
end
-- Start fzf first so its UI shows up immediately; otherwise any delay
-- looks like the input wasn't registered.
local r,w = io.popenrw(program)
if r and w then
-- Write matches to the write pipe.
local input = pipe_command()
if input then
if type(input) == "function" then
for line in input() do
w:write(line..'\n')
end
else
for _, s in ipairs(input) do
w:write(s..'\n')
end
end
end
w:close()
-- Read filtered matches.
local keep_blank = expect
matches = {}
for line in r:lines() do
if keep_blank or line ~= "" then
table.insert(matches, line)
end
keep_blank = nil
end
r:close()
end
elseif pipe_command then
pipe_command = apply_replacements(pipe_command)
matches = run_command(pipe_command..' | '..program, expect)
else
matches = run_command(program, expect)
end
restore_vars(old_vars)
chcp(orig_cp)
if matches then
insert_matches(rl_buffer, matches, post_process, expect)
rl_buffer:refreshline()
else
rl_buffer:ding()
end
end
--------------------------------------------------------------------------------
-- Functions for use with 'luafunc:' key bindings.
-- IMPORTANT: Using execute-silent is part of a workaround for a known bug in
-- fzf which eats the next character of input (e.g. the leading ESC from ESC[A
-- i.e. the Up arrow key). Using execute has others problems anyway, at least
-- on Windows -- for example, nano and other terminal based editors can't run
-- because stdin is still redirected (fzf#4260). So, the helper script uses the
-- start command as part of the workaround.
local bind_alt_e_edit_file = [[--bind "alt-e:execute-silent:$helper edit_file {}" ]]
local bind_alt_e_edit_tree_file = [[--bind "alt-e:execute-silent:$helper edit_tree_file {}" ]]
local bind_alt_e_edit_git_show = [[--bind "alt-e:execute-silent:$helper edit_git_show {2}" ]]
-- luacheck: globals fzf_git_commit_hashes
fzf_git_commit_hashes = nil
local function rl_setbinding_both(key, binding, keymap)
rl.setbinding(key, binding, keymap)
local key_no_ctrl = key:match([[^("\C%-g)\C%-(.)"$]])
if key_no_ctrl then
rl.setbinding(key_no_ctrl, binding, keymap)
end
end
local function apply_default_bindings()
if settings.get('fzf_git.default_bindings') then
for _, keymap in ipairs({"emacs", "vi-command", "vi-insert"}) do
rl.setbinding([["\C-g?"]], [["luafunc:fzf_git_help"]], keymap)
rl.setbinding([["\C-g\e[27;5;191~"]], [["luafunc:fzf_git_help"]], keymap)
rl_setbinding_both([["\C-g\C-f"]], [["luafunc:fzf_git_files"]], keymap)
rl_setbinding_both([["\C-g\C-b"]], [["luafunc:fzf_git_branches"]], keymap)
rl_setbinding_both([["\C-g\C-t"]], [["luafunc:fzf_git_tags"]], keymap)
rl_setbinding_both([["\C-g\C-r"]], [["luafunc:fzf_git_remotes"]], keymap)
rl_setbinding_both([["\C-g\C-h"]], [["luafunc:fzf_git_commit_hashes"]], keymap)
rl_setbinding_both([["\C-g\C-s"]], [["luafunc:fzf_git_stashes"]], keymap)
rl_setbinding_both([["\C-g\C-l"]], [["luafunc:fzf_git_reflogs"]], keymap)
rl_setbinding_both([["\C-g\C-w"]], [["luafunc:fzf_git_worktrees"]], keymap)
rl_setbinding_both([["\C-g\C-e"]], [["luafunc:fzf_git_eachref"]], keymap)
end
end
end
-- luacheck: globals fzf_git_help
add_help_desc("luafunc:fzf_git_help",
"Show key bindings for fzf_git")
function fzf_git_help(rl_buffer, line_state) -- luacheck: no unused
local bindings = { kcols=0 }
local function get_best_binding(command, affinity)
local best, desc
local t = rl.getcommandbindings(command)
if t then
desc = t.desc
if t.keys then
for _, k in ipairs(t.keys) do
if command:find("commit_hashes") then
k = k:gsub("Bkspc", "C-h")
end
if affinity and k:find(affinity, 1, true) then
best = k
break
elseif k:match("^C%-g,C%-") and not affinity then
best = k
break
elseif not best then
best = k
end
end
end
end
local b = { key=(best or "not bound"), desc=(desc or command) }
b.kcols = console.cellcount(b.key)
table.insert(bindings, b)
bindings.kcols = math.max(bindings.kcols, b.kcols)
end
rl_buffer:beginoutput()
get_best_binding([["luafunc:fzf_git_help"]], "?")
get_best_binding([["luafunc:fzf_git_files"]])
get_best_binding([["luafunc:fzf_git_branches"]])
get_best_binding([["luafunc:fzf_git_tags"]])
get_best_binding([["luafunc:fzf_git_remotes"]])
get_best_binding([["luafunc:fzf_git_commit_hashes"]])
get_best_binding([["luafunc:fzf_git_stashes"]])
get_best_binding([["luafunc:fzf_git_reflogs"]])
get_best_binding([["luafunc:fzf_git_worktrees"]])
get_best_binding([["luafunc:fzf_git_eachref"]])
local width = console.getwidth()
clink.print("\x1b[7mfzf_git Key Bindings\x1b[m")
for _, b in ipairs(bindings) do
local d = b.desc
if console.ellipsify then
d = console.ellipsify(d, width - 3 - bindings.kcols)
end
clink.print(string.format("%s%s : %s", b.key, string.rep(" ", bindings.kcols - b.kcols), d))
end
if settings.get('fzf.default_bindings') then
print()
print("Note: Each default key binding is bound to both Ctrl-G,Ctrl-Letter and also")
print("simply Ctrl-G,Letter. If your terminal intercepts a Ctrl-Letter binding then")
print("try the Ctrl-G,Letter binding instead.")
end
end
-- luacheck: globals fzf_git_files
add_help_desc("luafunc:fzf_git_files",
"Use fzf for Files")
function fzf_git_files(rl_buffer, line_state)
if not git_check() then
rl_buffer:ding()
return
end
local _, _, root = git.getgitdir()
root = root and root:lower()
local function list_files()
local files = {}
-- Get changed files.
local changed_files = run_command("git -c core.quotePath=false -c color.status="..__fzf_git_color().." status --short --no-branch --untracked-files=all")
if not changed_files then
return
end
for _, s in ipairs(changed_files) do
if not s:match("^...%.%./") then
table.insert(files, s)
end
end
-- Get all files, but filter out changed files.
local all_files = run_command("git -c core.quotePath=false ls-files "..maybe_quote(root))
local filter_files = run_command("git -c core.quotePath=false status --short --untracked-files=no")
local seen = {}
if not all_files or not filter_files then
return
end
for _, s in ipairs(filter_files) do
seen[s:sub(4)] = true
end
for _, s in ipairs(all_files) do
if not seen[s] and not s:match("^%.%./") then
table.insert(files, " "..s)
end
end
-- Return the generated list of files.
return files
end
local function post_process(item)
return item:match("^...(.*)$") -- | cut -c4-
:gsub("^.* -> ", "") -- | sed 's/.* -> //'
end
local args = table.concat({
[[-m --ansi --nth 2..,..]],
[[--border-label '📁 Files ']],
[[--header 'CTRL-O (open in browser) ╱ ALT-E (open in editor)']],
[[--bind "ctrl-o:execute-silent:$helper list_file {}"]],
bind_alt_e_edit_file,
[[--preview "$helper files {}"]],
}, " ")
do_fzf_git(rl_buffer, line_state, list_files, args, post_process)
end
-- luacheck: globals fzf_git_branches
add_help_desc("luafunc:fzf_git_branches",
"Use fzf for Branches")
function fzf_git_branches(rl_buffer, line_state)
if not git_check() then
rl_buffer:ding()
return
end
local alt_enter
local alt_h
local hash
local function post_process(item, expect)
if expect then
item = item:lower()
alt_enter = (item == "alt-enter")
alt_h = (item == "alt-h")
else
item = item:gsub("^%* ", "") -- | sed 's/^\* //'
:match("([^%s]+)") -- | awk '{print $1}' # Slightly modified to work with hashes as well
if alt_enter then
-- Strip everything up to and including the last / character.
item = item:gsub("^.*/([^/]+)$", "%1") -- printf '%s\n' {+} | cut -c3- | sed 's@[^/]*/@@'
elseif alt_h then
-- IMPORTANT: fzf-git uses
-- --bind "alt-h:become:LIST_OPTS=\$(cut -c3- <<< {} | cut -d' ' -f1) $shell \"$__fzf_git\" --run hashes"
-- but :become does not work on Windows. To work around that,
-- instead --except= is used to enable post-processing to
-- massage the selected item appropriately. And here is where
-- the massaging is performed.
hash = item
return false -- Cancels inserting matches.
end
return item
end
end
local input_command = [[bash "]]..__fzf_git_sh():gsub("\\", "/")..[[" --list branches]]
local args = table.concat({
[[--ansi]],
[[--border-label '🌲 Branches ']],
[[--header-lines 2]],
[[--tiebreak begin]],
[[--preview-window down,border-top,40%]],
[[--color hl:underline,hl+:underline]],
[[--no-hscroll]],
-- IMPORTANT: This 'reload' bind supplies the input without harming
-- the console mode. Using GNU tools like bash and column result in
-- the ESC and Arrow keys not working until a letter is pressed.
-- But having fzf spawn the command works fine.
[[--bind "start:reload:]]..input_command:gsub("\"", "\\\"")..[["]],
[[--bind 'ctrl-/:change-preview-window(down,70%|hidden|)']],
[[--bind "ctrl-o:execute-silent:bash \"$__fzf_git\" --list branch {}"]],
[[--bind "alt-a:change-border-label(🌳 All branches)+reload:bash \"$__fzf_git\" --list all-branches"]],
[[--bind "alt-h:accept"]],
[[--bind "alt-enter:accept"]],
[[--expect=alt-enter,alt-h]],
[[--preview "$helper branches {}"]],
}, " ")
do_fzf_git(rl_buffer, line_state, nil, args, post_process)
if alt_h and hash then
specific_hash = hash
fzf_git_commit_hashes(rl_buffer, line_state)
specific_hash = nil
end
end
-- luacheck: globals fzf_git_tags
add_help_desc("luafunc:fzf_git_tags",
"Use fzf for Tags")
function fzf_git_tags(rl_buffer, line_state)
local command = [[git tag --sort -version:refname]]
local args = table.concat({
[[--preview-window right,70%]],
[[--border-label '📛 Tags ']],
[[--header 'CTRL-O (open in browser)']],
[[--bind "ctrl-o:execute-silent:bash \"$__fzf_git\" --list tag {}"]],
[[--bind 'alt-r:toggle-raw']],
[[--preview "git show --color=$(__fzf_git_color .) {}"]],
}, " ")
do_fzf_git(rl_buffer, line_state, command, args)
end
-- luacheck: globals fzf_git_remotes
add_help_desc("luafunc:fzf_git_remotes",
"Use fzf for Remotes")
function fzf_git_remotes(rl_buffer, line_state)
if not git_check() then
rl_buffer:ding()
return
end
local function list_remotes()
-- PROBLEM:
-- fzf-git uses
-- git remote -v | awk '{print $1 "\t" $2}' | uniq
-- to generate the input for fzf. But awk and/or uniq are
-- corrupting the console mode, which causes fzf to be unable to
-- respond to ESC or Arrow keys until after a letter is typed.
-- WORKAROUND:
-- Do post-processing in Lua instead of using GNU tools.
-- OR AN ALTERNATE WORKAROUND:
-- The other solution is to use a start:reload: bind to make fzf
-- run the query itself instead of piping input.
local uniq = {}
local remotes = run_command("git remote -v")
if not remotes then
return
end
for _, r in ipairs(remotes) do
if not remotes[r] then
local fields = string.explode(r)
table.insert(uniq, fields[1].."\t"..fields[2])
remotes[r] = true
end
end
return uniq
end
local function post_process(item)
return item:match("^([^\t]*)\t") -- | cut -d$'\t' -f1
end
local args = table.concat({
[[--tac]],
[[--border-label '📡 Remotes ']],
[[--header 'CTRL-O (open in browser)']],
[[--bind "ctrl-o:execute-silent:bash \"$__fzf_git\" --list remote {1}"]],
[[--preview-window right,70%]],
-- IMPORTANT: fzf-git uses
-- --preview "git log --oneline --graph --date=short --color=$(__fzf_git_color .) --pretty='format:%C(auto)%cd %h%d %s' '{1}/$(git rev-parse --abbrev-ref HEAD)' --"]],
-- which has been encapsulated into the helper script to port the
-- use of $(...) into something that works on Windows.
[[--preview "$helper remotes {1}"]],
}, " ")
do_fzf_git(rl_buffer, line_state, list_remotes, args, post_process)
end
local function fzf_git_tree_files(rl_buffer, line_state, ...)
local diff_args = {}
local seen = {}
for _, treeish in ipairs({...}) do
if not seen[treeish] then
seen[treeish] = true
table.insert(diff_args, maybe_quote(treeish))
end
end
diff_args = table.concat(diff_args, " ")
-- NOTE: fzf-git.sh applies `sort -u`. The -u part is implemented above,
-- but I see no value in sorting by hash.
local command = [[git diff-tree --no-commit-id --name-only ]]..diff_args..[[ -r]]
local args = table.concat({
[[-m]],
[[--border-label "📂 Files in $* "]],
[[--header 'CTRL-O (open in browser) ╱ ALT-E (open in editor)']],
[[--bind "ctrl-o:execute-silent:bash \"$__fzf_git\" --list file {}"]],
bind_alt_e_edit_tree_file,
[[--preview "$helper tree_files {}"]],
}, " ")
do_fzf_git(rl_buffer, line_state, command, args)
end
-- luacheck: globals fzf_git_commit_hashes
add_help_desc("luafunc:fzf_git_commit_hashes",
"Use fzf for commit Hashes")
fzf_git_commit_hashes = function(rl_buffer, line_state) -- luacheck: no unused
if not git_check() then
rl_buffer:ding()