-
-
Notifications
You must be signed in to change notification settings - Fork 585
/
vim.vim
executable file
·1817 lines (1614 loc) · 55.8 KB
/
vim.vim
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
" Copyright (c) 2023 Junegunn Choi
"
" MIT License
"
" Permission is hereby granted, free of charge, to any person obtaining
" a copy of this software and associated documentation files (the
" "Software"), to deal in the Software without restriction, including
" without limitation the rights to use, copy, modify, merge, publish,
" distribute, sublicense, and/or sell copies of the Software, and to
" permit persons to whom the Software is furnished to do so, subject to
" the following conditions:
"
" The above copyright notice and this permission notice shall be
" included in all copies or substantial portions of the Software.
"
" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
" NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
" LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
let s:cpo_save = &cpo
set cpo&vim
" ------------------------------------------------------------------
" Common
" ------------------------------------------------------------------
function! s:conf(name, default)
let conf = get(g:, 'fzf_vim', {})
return get(conf, a:name, get(g:, 'fzf_' . a:name, a:default))
endfunction
let s:winpath = {}
function! s:winpath(path)
if has_key(s:winpath, a:path)
return s:winpath[a:path]
endif
let winpath = split(system('for %A in ("'.a:path.'") do @echo %~sA'), "\n")[0]
let s:winpath[a:path] = winpath
return winpath
endfunction
let s:warned = 0
function! s:bash()
if exists('s:bash')
return s:bash
endif
let custom_bash = s:conf('preview_bash', '')
let git_bash = 'C:\Program Files\Git\bin\bash.exe'
let scoop_git_bash = exists('$GIT_INSTALL_ROOT') ? $GIT_INSTALL_ROOT . '\bin\bash.exe' : ''
let candidates = filter(s:is_win ? [custom_bash, git_bash, scoop_git_bash, 'bash'] : [custom_bash, 'bash'], 'len(v:val)')
let found = filter(map(copy(candidates), 'exepath(v:val)'), 'len(v:val)')
if empty(found)
if !s:warned
call s:warn(printf('Preview window not supported (%s not found)', join(candidates, ', ')))
let s:warned = 1
endif
let s:bash = ''
return s:bash
endif
let s:bash = found[0]
" Make 8.3 filename via cmd.exe
if s:is_win
let s:bash = s:winpath(s:bash)
endif
return s:bash
endfunction
function! s:escape_for_bash(path)
if !s:is_win
return fzf#shellescape(a:path)
endif
if !exists('s:is_linux_like_bash')
call system(s:bash . ' -c "ls /mnt/[A-Za-z]"')
let s:is_linux_like_bash = v:shell_error == 0
endif
let path = substitute(a:path, '\', '/', 'g')
if s:is_linux_like_bash
let path = substitute(path, '^\([A-Z]\):', '/mnt/\L\1', '')
endif
return escape(path, ' ')
endfunction
let s:min_version = '0.53.0'
let s:is_win = has('win32') || has('win64')
let s:is_wsl_bash = s:is_win && (exepath('bash') =~? 'Windows[/\\]system32[/\\]bash.exe$')
let s:layout_keys = ['window', 'up', 'down', 'left', 'right']
let s:bin_dir = expand('<sfile>:p:h:h:h').'/bin/'
let s:bin = {
\ 'preview': s:bin_dir.'preview.sh',
\ 'tags': s:bin_dir.'tags.pl' }
let s:TYPE = {'bool': type(0), 'dict': type({}), 'funcref': type(function('call')), 'string': type(''), 'list': type([])}
let s:wide = 120
let s:checked = 0
function! s:check_requirements()
if s:checked
return
endif
if !exists('*fzf#run')
throw "fzf#run function not found. You also need Vim plugin from the main fzf repository (i.e. junegunn/fzf *and* junegunn/fzf.vim)"
endif
if !exists('*fzf#exec')
throw "fzf#exec function not found. You need to upgrade Vim plugin from the main fzf repository ('junegunn/fzf')"
endif
let s:checked = !empty(fzf#exec(s:min_version))
endfunction
function! s:extend_opts(dict, eopts, prepend)
if empty(a:eopts)
return
endif
if has_key(a:dict, 'options')
if type(a:dict.options) == s:TYPE.list && type(a:eopts) == s:TYPE.list
if a:prepend
let a:dict.options = extend(copy(a:eopts), a:dict.options)
else
call extend(a:dict.options, a:eopts)
endif
else
let all_opts = a:prepend ? [a:eopts, a:dict.options] : [a:dict.options, a:eopts]
let a:dict.options = join(map(all_opts, 'type(v:val) == s:TYPE.list ? join(map(copy(v:val), "fzf#shellescape(v:val)")) : v:val'))
endif
else
let a:dict.options = a:eopts
endif
endfunction
function! s:merge_opts(dict, eopts)
return s:extend_opts(a:dict, a:eopts, 0)
endfunction
function! s:prepend_opts(dict, eopts)
return s:extend_opts(a:dict, a:eopts, 1)
endfunction
" [spec to wrap], [preview window expression], [toggle-preview keys...]
function! fzf#vim#with_preview(...)
" Default spec
let spec = {}
let window = ''
let args = copy(a:000)
" Spec to wrap
if len(args) && type(args[0]) == s:TYPE.dict
let spec = copy(args[0])
call remove(args, 0)
endif
if !executable(s:bash())
return spec
endif
" Placeholder expression (TODO/TBD: undocumented)
let placeholder = get(spec, 'placeholder', '{}')
" g:fzf_preview_window
if empty(args)
let preview_args = s:conf('preview_window', ['', 'ctrl-/'])
if empty(preview_args)
let args = ['hidden']
else
" For backward-compatiblity
let args = type(preview_args) == type('') ? [preview_args] : copy(preview_args)
endif
endif
if len(args) && type(args[0]) == s:TYPE.string
if len(args[0]) && args[0] !~# '^\(up\|down\|left\|right\|hidden\)'
throw 'invalid preview window: '.args[0]
endif
let window = args[0]
call remove(args, 0)
endif
let preview = []
if len(window)
let preview += ['--preview-window', window]
endif
if s:is_win
if empty($MSWINHOME)
let $MSWINHOME = $HOME
endif
if s:is_wsl_bash && $WSLENV !~# '[:]\?MSWINHOME\(\/[^:]*\)\?\(:\|$\)'
let $WSLENV = 'MSWINHOME/u:'.$WSLENV
endif
endif
let preview_cmd = s:bash() . ' ' . s:escape_for_bash(s:bin.preview)
if len(placeholder)
let preview += ['--preview', preview_cmd.' '.placeholder]
end
if &ambiwidth ==# 'double'
let preview += ['--no-unicode']
end
if len(args)
call extend(preview, ['--bind', join(map(args, 'v:val.":toggle-preview"'), ',')])
endif
call s:merge_opts(spec, preview)
return spec
endfunction
function! s:remove_layout(opts)
for key in s:layout_keys
if has_key(a:opts, key)
call remove(a:opts, key)
endif
endfor
return a:opts
endfunction
function! s:reverse_list(opts)
let tokens = map(split($FZF_DEFAULT_OPTS, '[^a-z-]'), 'substitute(v:val, "^--", "", "")')
if index(tokens, 'reverse') < 0
return extend(['--layout=reverse-list'], a:opts)
endif
return a:opts
endfunction
function! s:wrap(name, opts, bang)
" fzf#wrap does not append --expect if sink or sink* is found
let opts = copy(a:opts)
let options = ''
if has_key(opts, 'options')
let options = type(opts.options) == s:TYPE.list ? join(opts.options) : opts.options
endif
if options !~ '--expect' && has_key(opts, 'sink*')
let Sink = remove(opts, 'sink*')
let wrapped = fzf#wrap(a:name, opts, a:bang)
let wrapped['sink*'] = Sink
else
let wrapped = fzf#wrap(a:name, opts, a:bang)
endif
return wrapped
endfunction
function! s:strip(str)
return substitute(a:str, '^\s*\|\s*$', '', 'g')
endfunction
function! s:rstrip(str)
return substitute(a:str, '\s*$', '', 'g')
endfunction
function! s:chomp(str)
return substitute(a:str, '\n*$', '', 'g')
endfunction
function! s:escape(path)
let path = fnameescape(a:path)
return s:is_win ? escape(path, '$') : path
endfunction
if v:version >= 704
function! s:function(name)
return function(a:name)
endfunction
else
function! s:function(name)
" By Ingo Karkat
return function(substitute(a:name, '^s:', matchstr(expand('<sfile>'), '<SNR>\d\+_\zefunction$'), ''))
endfunction
endif
function! s:get_color(attr, ...)
let gui = has('termguicolors') && &termguicolors
let fam = gui ? 'gui' : 'cterm'
let pat = gui ? '^#[a-f0-9]\+' : '^[0-9]\+$'
for group in a:000
let code = synIDattr(synIDtrans(hlID(group)), a:attr, fam)
if code =~? pat
return code
endif
endfor
return ''
endfunction
let s:ansi = {'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36}
function! s:csi(color, fg)
let prefix = a:fg ? '38;' : '48;'
if a:color[0] == '#'
return prefix.'2;'.join(map([a:color[1:2], a:color[3:4], a:color[5:6]], 'str2nr(v:val, 16)'), ';')
endif
return prefix.'5;'.a:color
endfunction
function! s:ansi(str, group, default, ...)
let fg = s:get_color('fg', a:group)
let bg = s:get_color('bg', a:group)
let color = (empty(fg) ? s:ansi[a:default] : s:csi(fg, 1)) .
\ (empty(bg) ? '' : ';'.s:csi(bg, 0))
return printf("\x1b[%s%sm%s\x1b[m", color, a:0 ? ';1' : '', a:str)
endfunction
for s:color_name in keys(s:ansi)
execute "function! s:".s:color_name."(str, ...)\n"
\ " return s:ansi(a:str, get(a:, 1, ''), '".s:color_name."')\n"
\ "endfunction"
endfor
function! s:buflisted()
return filter(range(1, bufnr('$')), 'buflisted(v:val) && getbufvar(v:val, "&filetype") != "qf"')
endfunction
function! s:fzf(name, opts, extra)
call s:check_requirements()
let [extra, bang] = [{}, 0]
if len(a:extra) <= 1
let first = get(a:extra, 0, 0)
if type(first) == s:TYPE.dict
let extra = first
else
let bang = first
endif
elseif len(a:extra) == 2
let [extra, bang] = a:extra
else
throw 'invalid number of arguments'
endif
let extra = copy(extra)
let eopts = has_key(extra, 'options') ? remove(extra, 'options') : ''
let merged = extend(copy(a:opts), extra)
call s:merge_opts(merged, eopts)
return fzf#run(s:wrap(a:name, merged, bang))
endfunction
let s:default_action = {
\ 'ctrl-t': 'tab split',
\ 'ctrl-x': 'split',
\ 'ctrl-v': 'vsplit' }
function! s:execute_silent(cmd)
silent keepjumps keepalt execute a:cmd
endfunction
" [key, [filename, [stay_on_edit: 0]]]
function! s:action_for(key, ...)
let Cmd = get(get(g:, 'fzf_action', s:default_action), a:key, '')
let cmd = type(Cmd) == s:TYPE.string ? Cmd : ''
" See If the command is the default action that opens the selected file in
" the current window. i.e. :edit
let edit = stridx('edit', cmd) == 0 " empty, e, ed, ..
" If no extra argument is given, we just execute the command and ignore
" errors. e.g. E471: Argument required: tab drop
if !a:0
if !edit
normal! m'
silent! call s:execute_silent(cmd)
endif
else
" For the default edit action, we don't execute the action if the
" selected file is already opened in the current window, or we are
" instructed to stay on the current buffer.
let stay = edit && (a:0 > 1 && a:2 || fnamemodify(a:1, ':p') ==# expand('%:p'))
if !stay
normal! m'
call s:execute_silent((len(cmd) ? cmd : 'edit').' '.s:escape(a:1))
endif
endif
endfunction
function! s:open(target)
if fnamemodify(a:target, ':p') ==# expand('%:p')
return
endif
execute 'edit' s:escape(a:target)
endfunction
function! s:align_lists(lists)
let maxes = {}
for list in a:lists
let i = 0
while i < len(list)
let maxes[i] = max([get(maxes, i, 0), len(list[i])])
let i += 1
endwhile
endfor
for list in a:lists
call map(list, "printf('%-'.maxes[v:key].'s', v:val)")
endfor
return a:lists
endfunction
function! s:warn(message)
echohl WarningMsg
echom a:message
echohl None
return 0
endfunction
function! s:fill_quickfix(name, list)
if len(a:list) > 1
let Handler = s:conf('listproc_'.a:name, s:conf('listproc', function('fzf#vim#listproc#quickfix')))
call call(Handler, [a:list], {})
return 1
endif
return 0
endfunction
function! fzf#vim#_uniq(list)
let visited = {}
let ret = []
for l in a:list
if !empty(l) && !has_key(visited, l)
call add(ret, l)
let visited[l] = 1
endif
endfor
return ret
endfunction
" ------------------------------------------------------------------
" Files
" ------------------------------------------------------------------
function! s:shortpath()
let short = fnamemodify(getcwd(), ':~:.')
if !has('win32unix')
let short = pathshorten(short)
endif
let slash = (s:is_win && !&shellslash) ? '\' : '/'
return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)
endfunction
function! fzf#vim#files(dir, ...)
let args = {}
if !empty(a:dir)
if !isdirectory(expand(a:dir))
return s:warn('Invalid directory')
endif
let slash = (s:is_win && !&shellslash) ? '\\' : '/'
let dir = substitute(a:dir, '[/\\]*$', slash, '')
let args.dir = dir
else
let dir = s:shortpath()
endif
let args.options = ['-m', '--prompt', strwidth(dir) < &columns / 2 - 20 ? dir : '> ']
call s:merge_opts(args, s:conf('files_options', []))
return s:fzf('files', args, a:000)
endfunction
" ------------------------------------------------------------------
" Lines
" ------------------------------------------------------------------
function! s:line_handler(lines)
if len(a:lines) < 2
return
endif
let qfl = []
for line in a:lines[1:]
let chunks = split(line, "\t", 1)
call add(qfl, {'bufnr': str2nr(chunks[0]), 'lnum': str2nr(chunks[2]), 'text': join(chunks[3:], "\t")})
endfor
call s:action_for(a:lines[0])
if !s:fill_quickfix('lines', qfl)
let chunks = split(a:lines[1], '\t')
execute 'buffer' chunks[0]
execute chunks[2]
endif
normal! ^zvzz
endfunction
function! fzf#vim#_lines(all)
let cur = []
let rest = []
let buf = bufnr('')
let longest_name = 0
let display_bufnames = &columns > s:wide
if display_bufnames
let bufnames = {}
for b in s:buflisted()
let bufnames[b] = pathshorten(fnamemodify(bufname(b), ":~:."))
let longest_name = max([longest_name, len(bufnames[b])])
endfor
endif
let len_bufnames = min([15, longest_name])
for b in s:buflisted()
let lines = getbufline(b, 1, "$")
if empty(lines)
let path = fnamemodify(bufname(b), ':p')
let lines = filereadable(path) ? readfile(path) : []
endif
if display_bufnames
let bufname = bufnames[b]
if len(bufname) > len_bufnames + 1
let bufname = '…' . bufname[-len_bufnames+1:]
endif
let bufname = printf(s:green("%".len_bufnames."s", "Directory"), bufname)
else
let bufname = ''
endif
let linefmt = s:blue("%2d\t", "TabLine")."%s".s:yellow("\t%4d ", "LineNr")."\t%s"
call extend(b == buf ? cur : rest,
\ filter(
\ map(lines,
\ '(!a:all && empty(v:val)) ? "" : printf(linefmt, b, bufname, v:key + 1, v:val)'),
\ 'a:all || !empty(v:val)'))
endfor
return [display_bufnames, extend(cur, rest)]
endfunction
function! fzf#vim#lines(...)
let [display_bufnames, lines] = fzf#vim#_lines(1)
let nth = display_bufnames ? 3 : 2
let [query, args] = (a:0 && type(a:1) == type('')) ?
\ [a:1, a:000[1:]] : ['', a:000]
return s:fzf('lines', {
\ 'source': lines,
\ 'sink*': s:function('s:line_handler'),
\ 'options': s:reverse_list(['--tiebreak=index', '--prompt', 'Lines> ', '--ansi', '--extended', '--nth='.nth.'..', '--tabstop=1', '--query', query, '--multi'])
\}, args)
endfunction
" ------------------------------------------------------------------
" BLines
" ------------------------------------------------------------------
function! s:buffer_line_handler(lines)
if len(a:lines) < 2
return
endif
let qfl = []
for line in a:lines[1:]
let chunks = split(line, "\t", 1)
let ln = chunks[0]
let ltxt = join(chunks[1:], "\t")
call add(qfl, {'filename': expand('%'), 'lnum': str2nr(ln), 'text': ltxt})
endfor
call s:action_for(a:lines[0])
if !s:fill_quickfix('blines', qfl)
execute split(a:lines[1], '\t')[0]
endif
normal! ^zvzz
endfunction
function! s:buffer_lines(query)
let linefmt = s:yellow(" %4d ", "LineNr")."\t%s"
let fmtexpr = 'printf(linefmt, v:key + 1, v:val)'
let lines = getline(1, '$')
if empty(a:query)
return map(lines, fmtexpr)
end
return filter(map(lines, 'v:val =~ a:query ? '.fmtexpr.' : ""'), 'len(v:val)')
endfunction
function! fzf#vim#buffer_lines(...)
let [query, args] = (a:0 && type(a:1) == type('')) ?
\ [a:1, a:000[1:]] : ['', a:000]
return s:fzf('blines', {
\ 'source': s:buffer_lines(query),
\ 'sink*': s:function('s:buffer_line_handler'),
\ 'options': s:reverse_list(['+m', '--tiebreak=index', '--multi', '--prompt', 'BLines> ', '--ansi', '--extended', '--nth=2..', '--tabstop=1'])
\}, args)
endfunction
" ------------------------------------------------------------------
" Colors
" ------------------------------------------------------------------
function! s:colors_exit(code)
if exists('s:colors_name')
if a:code > 0 && s:colors_name != g:colors_name
execute 'colo' s:colors_name
endif
unlet s:colors_name
endif
call fzf#vim#ipc#stop()
endfunction
function! fzf#vim#colors(...)
let colors = split(globpath(&rtp, "colors/*.vim"), "\n")
if has('packages')
let colors += split(globpath(&packpath, "pack/*/opt/*/colors/*.vim"), "\n")
endif
let colors = fzf#vim#_uniq(map(colors, "fnamemodify(v:val, ':t')[:-5]"))
" Put the current colorscheme at the top
if exists('g:colors_name')
let s:colors_name = g:colors_name
let colors = [g:colors_name] + filter(colors, 'g:colors_name != v:val')
endif
let spec = {
\ 'source': colors,
\ 'sink': 'colo',
\ 'options': ['+m', '--prompt', 'Colors> ']
\}
if !a:1 " We can't set up IPC in fullscreen mode in Vim
let fifo = fzf#vim#ipc#start({ msg -> execute('colo '.msg) })
if len(fifo)
call extend(spec.options, ['--no-tmux', '--no-padding', '--no-margin', '--bind', 'focus:execute-silent:echo {} > '.fifo])
let spec.exit = s:function('s:colors_exit')
let maxwidth = max(map(copy(colors), 'strwidth(v:val)'))
let spec.window = { 'width': maxwidth + 8, 'height': len(colors) + 5 }
endif
endif
call s:fzf('colors', spec, a:000)
endfunction
" ------------------------------------------------------------------
" Locate
" ------------------------------------------------------------------
function! fzf#vim#locate(query, ...)
return s:fzf('locate', {
\ 'source': 'locate '.a:query,
\ 'options': '-m --prompt "Locate> "'
\}, a:000)
endfunction
" ------------------------------------------------------------------
" History[:/]
" ------------------------------------------------------------------
function! fzf#vim#_recent_files()
return fzf#vim#_uniq(map(
\ filter([expand('%')], 'len(v:val)')
\ + filter(map(fzf#vim#_buflisted_sorted(), 'bufname(v:val)'), 'len(v:val)')
\ + filter(copy(v:oldfiles), "filereadable(fnamemodify(v:val, ':p'))"),
\ 'fnamemodify(v:val, ":~:.")'))
endfunction
function! s:history_source(type)
let max = histnr(a:type)
if max <= 0
return ['No entries']
endif
let fmt = s:yellow(' %'.len(string(max)).'d ', 'Number')
let list = filter(map(range(1, max), 'histget(a:type, - v:val)'), '!empty(v:val)')
return extend([' :: Press '.s:magenta('CTRL-E', 'Special').' to edit'],
\ map(list, 'printf(fmt, len(list) - v:key)." ".v:val'))
endfunction
nnoremap <plug>(-fzf-vim-do) :execute g:__fzf_command<cr>
nnoremap <plug>(-fzf-/) /
nnoremap <plug>(-fzf-:) :
function! s:history_sink(type, lines)
if len(a:lines) < 2
return
endif
let prefix = "\<plug>(-fzf-".a:type.')'
let key = a:lines[0]
let item = matchstr(a:lines[1], ' *[0-9]\+ *\zs.*')
if key == 'ctrl-e'
call histadd(a:type, item)
redraw
call feedkeys(a:type."\<up>", 'n')
else
if a:type == ':'
call histadd(a:type, item)
endif
let g:__fzf_command = "normal ".prefix.item."\<cr>"
call feedkeys("\<plug>(-fzf-vim-do)")
endif
endfunction
function! s:cmd_history_sink(lines)
call s:history_sink(':', a:lines)
endfunction
function! fzf#vim#command_history(...)
return s:fzf('history-command', {
\ 'source': s:history_source(':'),
\ 'sink*': s:function('s:cmd_history_sink'),
\ 'options': '+m --ansi --prompt="Hist:> " --header-lines=1 --expect=ctrl-e --tiebreak=index'}, a:000)
endfunction
function! s:search_history_sink(lines)
call s:history_sink('/', a:lines)
endfunction
function! fzf#vim#search_history(...)
return s:fzf('history-search', {
\ 'source': s:history_source('/'),
\ 'sink*': s:function('s:search_history_sink'),
\ 'options': '+m --ansi --prompt="Hist/> " --header-lines=1 --expect=ctrl-e --tiebreak=index'}, a:000)
endfunction
function! fzf#vim#history(...)
return s:fzf('history-files', {
\ 'source': fzf#vim#_recent_files(),
\ 'options': ['-m', '--header-lines', !empty(expand('%')), '--prompt', 'Hist> ']
\}, a:000)
endfunction
" ------------------------------------------------------------------
" GFiles[?]
" ------------------------------------------------------------------
function! s:get_git_root(dir)
let dir = len(a:dir) ? a:dir : substitute(split(expand('%:p:h'), '[/\\]\.git\([/\\]\|$\)')[0], '^fugitive://', '', '')
let root = systemlist('git -C ' . fzf#shellescape(dir) . ' rev-parse --show-toplevel')[0]
return v:shell_error ? '' : (len(a:dir) ? fnamemodify(a:dir, ':p') : root)
endfunction
function! s:version_requirement(val, min)
for idx in range(0, len(a:min) - 1)
let v = get(a:val, idx, 0)
if v < a:min[idx] | return 0
elseif v > a:min[idx] | return 1
endif
endfor
return 1
endfunction
function! s:git_version_requirement(...)
if !exists('s:git_version')
let s:git_version = map(split(split(system('git --version'))[2], '\.'), 'str2nr(v:val)')
endif
return s:version_requirement(s:git_version, a:000)
endfunction
function! fzf#vim#gitfiles(args, ...)
let dir = get(get(a:, 1, {}), 'dir', '')
let root = s:get_git_root(dir)
if empty(root)
return s:warn('Not in git repo')
endif
let prefix = 'git -C ' . fzf#shellescape(root) . ' '
if a:args != '?'
let source = prefix . 'ls-files -z ' . a:args
if s:git_version_requirement(2, 31)
let source .= ' --deduplicate'
endif
return s:fzf('gfiles', {
\ 'source': source,
\ 'dir': root,
\ 'options': '-m --read0 --prompt "GitFiles> "'
\}, a:000)
endif
" Here be dragons!
" We're trying to access the common sink function that fzf#wrap injects to
" the options dictionary.
let bar = s:is_win ? '^|' : '|'
let diff_prefix = 'git -C ' . s:escape_for_bash(root) . ' '
let preview = printf(
\ s:bash() . ' -c "if [[ {1} =~ M ]]; then %s; else %s {-1}; fi"',
\ executable('delta')
\ ? diff_prefix . 'diff -- {-1} ' . bar . ' delta --width $FZF_PREVIEW_COLUMNS --file-style=omit ' . bar . ' sed 1d'
\ : diff_prefix . 'diff --color=always -- {-1} ' . bar . ' sed 1,4d',
\ s:escape_for_bash(s:bin.preview))
let wrapped = fzf#wrap({
\ 'source': prefix . '-c color.status=always status --short --untracked-files=all',
\ 'dir': root,
\ 'options': ['--ansi', '--multi', '--nth', '2..,..', '--tiebreak=index', '--prompt', 'GitFiles?> ', '--preview', preview]
\})
call s:remove_layout(wrapped)
let wrapped.common_sink = remove(wrapped, 'sink*')
function! wrapped.newsink(lines)
let lines = extend(a:lines[0:0], map(a:lines[1:], 'substitute(v:val[3:], ".* -> ", "", "")'))
return self.common_sink(lines)
endfunction
let wrapped['sink*'] = remove(wrapped, 'newsink')
return s:fzf('gfiles-diff', wrapped, a:000)
endfunction
" ------------------------------------------------------------------
" Buffers
" ------------------------------------------------------------------
function! s:find_open_window(b)
let [tcur, tcnt] = [tabpagenr() - 1, tabpagenr('$')]
for toff in range(0, tabpagenr('$') - 1)
let t = (tcur + toff) % tcnt + 1
let buffers = tabpagebuflist(t)
for w in range(1, len(buffers))
let b = buffers[w - 1]
if b == a:b
return [t, w]
endif
endfor
endfor
return [0, 0]
endfunction
function! s:jump(t, w)
execute a:t.'tabnext'
execute a:w.'wincmd w'
endfunction
function! s:bufopen(lines)
if len(a:lines) < 2
return
endif
let b = matchstr(a:lines[1], '\[\zs[0-9]*\ze\]')
if empty(a:lines[0]) && s:conf('buffers_jump', 0)
let [t, w] = s:find_open_window(b)
if t
call s:jump(t, w)
return
endif
endif
call s:action_for(a:lines[0])
execute 'buffer' b
endfunction
function! fzf#vim#_format_buffer(b)
let name = bufname(a:b)
let line = exists('*getbufinfo') ? getbufinfo(a:b)[0]['lnum'] : 0
let fullname = empty(name) ? '' : fnamemodify(name, ":p:~:.")
let dispname = empty(name) ? '[No Name]' : name
let flag = a:b == bufnr('') ? s:blue('%', 'Conditional') :
\ (a:b == bufnr('#') ? s:magenta('#', 'Special') : ' ')
let modified = getbufvar(a:b, '&modified') ? s:red(' [+]', 'Exception') : ''
let readonly = getbufvar(a:b, '&modifiable') ? '' : s:green(' [RO]', 'Constant')
let extra = join(filter([modified, readonly], '!empty(v:val)'), '')
let target = empty(name) ? '' : (line == 0 ? fullname : fullname.':'.line)
return s:rstrip(printf("%s\t%d\t[%s] %s\t%s\t%s", target, line, s:yellow(a:b, 'Number'), flag, dispname, extra))
endfunction
function! s:sort_buffers(...)
let [b1, b2] = map(copy(a:000), 'get(g:fzf#vim#buffers, v:val, v:val)')
" Using minus between a float and a number in a sort function causes an error
return b1 < b2 ? 1 : -1
endfunction
function! fzf#vim#_buflisted_sorted()
return sort(s:buflisted(), 's:sort_buffers')
endfunction
" [query (string)], [bufnrs (list)], [spec (dict)], [fullscreen (bool)]
function! fzf#vim#buffers(...)
let [query, args] = (a:0 && type(a:1) == type('')) ?
\ [a:1, a:000[1:]] : ['', a:000]
if len(args) && type(args[0]) == s:TYPE.list
let [buffers; args] = args
else
let buffers = s:buflisted()
endif
let sorted = sort(buffers, 's:sort_buffers')
let header_lines = '--header-lines=' . (bufnr('') == get(sorted, 0, 0) ? 1 : 0)
let tabstop = len(max(sorted)) >= 4 ? 9 : 8
return s:fzf('buffers', {
\ 'source': map(sorted, 'fzf#vim#_format_buffer(v:val)'),
\ 'sink*': s:function('s:bufopen'),
\ 'options': ['+m', '-x', '--tiebreak=index', header_lines, '--ansi', '-d', '\t', '--with-nth', '3..', '-n', '2,1..2', '--prompt', 'Buf> ', '--query', query, '--preview-window', '+{2}-/2', '--tabstop', tabstop]
\}, args)
endfunction
" ------------------------------------------------------------------
" Ag / Rg
" ------------------------------------------------------------------
function! s:ag_to_qf(line)
let parts = matchlist(a:line, '\(.\{-}\)\s*:\s*\(\d\+\)\%(\s*:\s*\(\d\+\)\)\?\%(\s*:\(.*\)\)\?')
let file = &acd ? fnamemodify(parts[1], ':p') : parts[1]
if has('win32unix') && file !~ '/'
let file = substitute(file, '\', '/', 'g')
endif
let dict = {'filename': file, 'lnum': parts[2], 'text': parts[4]}
if len(parts[3])
let dict.col = parts[3]
endif
return dict
endfunction
function! s:ag_handler(name, lines)
if len(a:lines) < 2
return
endif
let multi_line = min([s:conf('grep_multi_line', 0), 2])
let lines = []
if multi_line && executable('perl')
for idx in range(1, len(a:lines), multi_line + 1)
call add(lines, join(a:lines[idx:idx + multi_line], ''))
endfor
else
let lines = a:lines[1:]
endif
let list = map(filter(lines, 'len(v:val)'), 's:ag_to_qf(v:val)')
if empty(list)
return
endif
call s:action_for(a:lines[0], list[0].filename, len(list) > 1)
if s:fill_quickfix(a:name, list)
return
endif
" Single item selected
let first = list[0]
try
execute first.lnum
if has_key(first, 'col')
call cursor(0, first.col)
endif
normal! zvzz
catch
endtry
endfunction
" query, [ag options], [spec (dict)], [fullscreen (bool)]
function! fzf#vim#ag(query, ...)
if type(a:query) != s:TYPE.string
return s:warn('Invalid query argument')
endif
let query = empty(a:query) ? '^(?=.)' : a:query
let args = copy(a:000)
let ag_opts = len(args) > 1 && type(args[0]) == s:TYPE.string ? remove(args, 0) : ''
let command = ag_opts . ' -- ' . fzf#shellescape(query)
return call('fzf#vim#ag_raw', insert(args, command, 0))
endfunction
" ag command suffix, [spec (dict)], [fullscreen (bool)]
function! fzf#vim#ag_raw(command_suffix, ...)
if !executable('ag')
return s:warn('ag is not found')
endif
return call('fzf#vim#grep', extend(['ag --nogroup --column --color '.a:command_suffix, 1], a:000))
endfunction
function! s:grep_multi_line(opts)
" TODO: Non-global option
let multi_line = s:conf('grep_multi_line', 0)
if multi_line && executable('perl')
let opts = copy(a:opts)
let opts.options = extend(copy(opts.options), ['--read0', '--highlight-line'])
let delim = multi_line > 1 ? '\n\0' : '\0'
return [opts, printf(" | perl -pe 's/\\n/%s/; s/^([^:]+:){2,3}/$&\\n /'", delim)]
endif
return [a:opts, '']
endfunction
" command (string), [spec (dict)], [fullscreen (bool)]
function! fzf#vim#grep(grep_command, ...)
let args = copy(a:000)
let words = []
for word in split(a:grep_command)
if word !~# '^[a-z]'
break
endif
call add(words, word)
endfor
let words = empty(words) ? ['grep'] : words
let name = join(words, '-')
let capname = join(map(words, 'toupper(v:val[0]).v:val[1:]'), '')
let opts = {
\ 'options': ['--ansi', '--prompt', capname.'> ',
\ '--multi', '--bind', 'alt-a:select-all,alt-d:deselect-all',
\ '--delimiter', ':', '--preview-window', '+{2}-/2']
\}
if len(args) && type(args[0]) == s:TYPE.bool
call remove(args, 0)
endif
function! opts.sink(lines) closure
return s:ag_handler(get(opts, 'name', name), a:lines)
endfunction
let opts['sink*'] = remove(opts, 'sink')
let [opts, suffix] = s:grep_multi_line(opts)
let command = a:grep_command . suffix
try
let prev_default_command = $FZF_DEFAULT_COMMAND
let $FZF_DEFAULT_COMMAND = command
return s:fzf(name, opts, args)
finally
let $FZF_DEFAULT_COMMAND = prev_default_command
endtry
endfunction
" command_prefix (string), initial_query (string), [spec (dict)], [fullscreen (bool)]
function! fzf#vim#grep2(command_prefix, query, ...)
let args = copy(a:000)
let words = []
for word in split(a:command_prefix)
if word !~# '^[a-z]'
break
endif
call add(words, word)
endfor
let words = empty(words) ? ['grep'] : words
let name = join(words, '-')
let fallback = s:is_win ? '' : ' || :'
let opts = {