-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path.vimrc
More file actions
1654 lines (1435 loc) · 57.2 KB
/
Copy path.vimrc
File metadata and controls
1654 lines (1435 loc) · 57.2 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
" Vim shells out for fzf, gitgutter, ALE and vim-plug's installer, and those
" callers assume a POSIX shell. Fish breaks them. Use :Term for interactive fish.
set shell=/bin/bash
set nocompatible
"-------------------------------------------------------------
" Vim-plug setup {{{1
let data_dir = has('nvim') ? stdpath('data') . '/site' : '~/.vim'
if empty(glob(data_dir . '/autoload/plug.vim'))
silent execute '!curl -fLo '.data_dir.'/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif
"-------------------------------------------------------------
" Plugs {{{1
call plug#begin()
" ALE, syntax highlighting and linting support
Plug 'dense-analysis/ale'
" P lang support and ALE linting
Plug 'kiosion/p-vim'
" vim-svelte-plugin, syntax + indent support for svelte filetypes
Plug 'evanleck/vim-svelte', {'branch': 'main'}
" html5.vim, for html/xml syntax highlighting
Plug 'othree/html5.vim'
" vim-elixir, syntax + lsp for erlang/elixir
Plug 'elixir-editors/vim-elixir'
" coc.nvim, autocompletion and ts stuff
Plug 'neoclide/coc.nvim', {'branch': 'release'}
" Airline status line
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
" CoPilot
Plug 'github/copilot.vim'
" vim-javascript
Plug 'pangloss/vim-javascript'
" NERDTree
Plug 'preservim/nerdtree'
" fzf
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
" fugitive
Plug 'tpope/vim-fugitive'
" Vimagit
Plug 'jreybert/vimagit'
" git-gutter
Plug 'airblade/vim-gitgutter'
" tailwindcss intellisense
Plug 'airblade/vim-tailwind'
" multi-cursors
Plug 'mg979/vim-visual-multi'
" vim-wakatime
Plug 'wakatime/vim-wakatime'
call plug#end()
"-------------------------------------------------------------
" Plugin configs {{{1
" enable P linting
let g:p_lint = 1
" Raise the regexp engine's memory ceiling. Large generated files (bundled JS,
" protobuf output) blow past the 1000KB default and lose syntax highlighting.
set mmp=5000
" vim-svelte-plugin
let g:svelte_preprocessor_tags = [
\ { 'name': 'scss', 'tag': 'style' },
\ { 'name': 'ts', 'tag': 'script', 'as': 'typescript' },
\ ]
let g:svelte_preprocessors = ['typescript', 'scss']
" Search excludes
"
" Both fd and ripgrep already honour .gitignore whenever the search starts
" inside a git repository, and both read .ignore files anywhere. This list is
" only for what is committed and still machine-written, which no ignore file
" covers. Add to the one list and every search below picks it up.
let g:search_exclude = [
\ '*.pb.go', '*.pb.gw.go', '*.gen.go', '*_generated.go',
\ '*_pb.ts', '*_pb.*.ts', '*_pb.js', '*.min.js',
\ 'package-lock.json', 'yarn.lock', '*.snap',
\ ]
" fd spells this --exclude, ripgrep spells it as a negated --glob.
let g:fd_exclude = join(map(copy(g:search_exclude), '"--exclude " . shellescape(v:val)'))
let g:rg_exclude = join(map(copy(g:search_exclude), '"--glob " . shellescape("!" . v:val)'))
" job_start takes an argument list and runs no shell. That form needs no
" quoting.
let g:rg_exclude_args = flattennew(map(copy(g:search_exclude), '["--glob", "!" . v:val]'))
" fzf
let $FZF_DEFAULT_COMMAND='fd --type f --strip-cwd-prefix --hidden --follow --exclude .git --exclude node_modules --exclude dist --exclude build ' . g:fd_exclude
" Enter opens the result in its own tab. The empty key is how fzf.vim spells
" "no expect key was pressed", which is what Enter produces. drop reuses a
" window or tab that already holds the file rather than opening a second copy
" of it, and 'switchbuf' below is what lets it look in other tabs.
let g:fzf_action = {
\ '': 'tab drop',
\ 'ctrl-t': 'tab split',
\ 'ctrl-x': 'split',
\ 'ctrl-v': 'vsplit' }
" Copilot
"
" Copilot hides its ghost text whenever a completion menu is open. That check
" is in copilot.vim itself (autoload/copilot.vim, s:HideDuringCompletion) and
" it defaults on. coc opens a menu on nearly every keystroke. In practice the
" two were never on screen together and each appeared to eat the other.
" Turning it off lets the menu and the ghost text coexist.
let g:copilot_hide_during_completion = 0
" Copilot claims <Tab> by default, which then does nothing useful while coc's
" menu is up. Each gets its own key instead, further down.
let g:copilot_no_tab_map = 1
let g:copilot_ignore_node_version = 1
" ALE
"
" coc owns the language servers. ALE runs only the linters coc does not
" provide, and does the formatting on save. Listing gopls here as well would
" start a second gopls process per project on top of the one coc-go runs.
"
" ALE has no prettier linter for any of these filetypes, only a fixer, so
" prettier belongs in g:ale_fixers alone.
let g:ale_linters = {
\ 'javascript': ['eslint'],
\ 'typescript': ['eslint'],
\ 'typescriptreact': ['eslint'],
\ 'javascriptreact': ['eslint'],
\ 'svelte': ['eslint'],
\ 'go': ['golangci-lint'],
\ 'elixir': ['mix_format'],
\}
let g:ale_fixers = {
\ 'javascript': ['prettier', 'eslint'],
\ 'typescript': ['prettier', 'eslint'],
\ 'typescriptreact': ['prettier', 'eslint'],
\ 'javascriptreact': ['prettier', 'eslint'],
\ 'svelte': ['prettier', 'eslint'],
\ 'html': ['prettier'],
\ 'css': ['prettier'],
\ 'scss': ['prettier'],
\ 'go': ['goimports'],
\ 'elixir': ['mix_format'],
\}
let g:ale_pattern_options = {
\ '.*node_modules.*$': {'ale_enabled': 0},
\ '.*dist.*$': {'ale_enabled': 0},
\ '.*-config.js$': {'ale_enabled': 0},
\ '.*/build/.*$': {'ale_enabled': 0},
\}
let g:ale_fix_on_save = 1
" Show each diagnostic inline, after the code it belongs to. This is already
" the default on a Vim with textprop and popupwin, which this is, but it is the
" behaviour the whole setup leans on so it is worth saying out loud. Set it to
" 'current' for the cursor's line only if every line at once gets noisy.
let g:ale_virtualtext_cursor = 'all'
" goimports on save both removes imports that are no longer used and adds ones
" the file now needs. gopls adds the import by itself when a completion for an
" unimported package is accepted.
" GitGutter
let g:gitgutter_sign_added = '+'
let g:gitgutter_sign_modified = '~'
let g:gitgutter_sign_removed = '-'
" GitGutter claims ]c and [c for hunk navigation by default. Keep those, but
" drop its other default maps so <Leader>g is free for the git group below.
let g:gitgutter_map_keys = 0
" Airline
"
" The bar along the top listed open buffers whenever only one tab existed, and
" silently switched to listing tabs once a second tab appeared. Two different
" things in one strip, which is why it was hard to tell what a chip up there
" referred to. It now always lists tabs, numbered.
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#show_buffers = 0
let g:airline#extensions#tabline#show_tabs = 1
let g:airline#extensions#tabline#tab_nr_type = 1
let g:airline#extensions#tabline#show_tab_type = 0
let g:airline#extensions#tabline#formatter = 'unique_tail'
let g:airline#extensions#hunks#enabled=0
let g:airline#extensions#branch#enabled=1
let g:airline#extensions#branch#icon=''
let g:airline#extensions#coc#enabled=1
let g:airline_powerline_fonts = 1
let g:airline_theme='deus'
"------------------------------------------------------------
" Colour customization {{{1
set termguicolors
colorscheme catppuccin_macchiato
" The macchiato palette. The colourscheme keeps its own copy script-local, so
" without this the groups below would be a wall of hex.
let s:cat = {
\ 'crust': '#181926',
\ 'mantle': '#1E2030',
\ 'base': '#24273A',
\ 'surface0': '#363A4F',
\ 'surface1': '#494D64',
\ 'surface2': '#5B6078',
\ 'overlay0': '#6E738D',
\ 'overlay1': '#8087A2',
\ 'overlay2': '#939AB7',
\ 'subtext0': '#A5ADCB',
\ 'subtext1': '#B8C0E0',
\ 'text': '#CAD3F5',
\ 'lavender': '#B7BDF8',
\ 'blue': '#8AADF4',
\ 'sapphire': '#7DC4E4',
\ 'sky': '#91D7E3',
\ 'teal': '#8BD5CA',
\ 'green': '#A6DA95',
\ 'yellow': '#EED49F',
\ 'peach': '#F5A97F',
\ 'maroon': '#EE99A0',
\ 'red': '#ED8796',
\ 'mauve': '#C6A0F6',
\ 'pink': '#F5BDE6',
\ 'flamingo': '#F0C6C6',
\ }
" Vim's bundled Go syntax highlights keywords and little else. A function name,
" a type name and a struct field all render as plain text, which is why a Go
" file looks so much flatter here than in GoLand. gopls reports what each
" identifier actually is. The CocSem groups below therefore colour most of a
" file, and the syntax file is left with strings, numbers and comments. That
" split is deliberate. gopls sends one flat token for a whole string, where the
" syntax file highlights the escapes and format verbs inside it.
function! s:Colours() abort
let c = s:cat
let groups = {
\ 'CocFloating': 'guibg=' . c.mantle . ' guifg=' . c.text,
\ 'CocFloatSbar': 'guibg=' . c.surface0,
\ 'CocFloatThumb': 'guibg=' . c.overlay0,
\ 'CocFloatDividingLine': 'guifg=' . c.surface1,
\ 'CocMenuSel': 'guibg=' . c.surface1 . ' guifg=' . c.text,
\ 'CocPumSearch': 'guifg=' . c.blue . ' gui=bold',
\ 'CocListLine': 'guibg=' . c.surface0,
\
\ 'CocInlayHint': 'guibg=NONE guifg=' . c.overlay0 . ' gui=italic',
\
\ 'CocSemTypeNamespace': 'guifg=' . c.lavender,
\ 'CocSemTypeType': 'guifg=' . c.yellow,
\ 'CocSemTypeStruct': 'guifg=' . c.yellow,
\ 'CocSemTypeInterface': 'guifg=' . c.yellow,
\ 'CocSemTypeClass': 'guifg=' . c.yellow,
\ 'CocSemTypeEnum': 'guifg=' . c.yellow,
\ 'CocSemTypeTypeParameter': 'guifg=' . c.yellow . ' gui=italic',
\ 'CocSemTypeFunction': 'guifg=' . c.blue,
\ 'CocSemTypeMethod': 'guifg=' . c.blue,
\ 'CocSemTypeParameter': 'guifg=' . c.maroon,
\ 'CocSemTypeVariable': 'guifg=' . c.text,
\ 'CocSemTypeProperty': 'guifg=' . c.lavender,
\ 'CocSemTypeEnumMember': 'guifg=' . c.peach,
\ 'CocSemTypeMacro': 'guifg=' . c.peach,
\ 'CocSemTypeKeyword': 'guifg=' . c.mauve,
\ 'CocSemTypeModifier': 'guifg=' . c.mauve,
\ 'CocSemTypeOperator': 'guifg=' . c.sky,
\ 'CocSemTypeDecorator': 'guifg=' . c.pink,
\ 'CocSemTypeComment': 'guifg=' . c.overlay2,
\
\ 'PanelDoc': 'guifg=' . c.subtext0,
\ 'PanelCounts': 'guifg=' . c.subtext1 . ' gui=bold',
\ 'PanelKeys': 'guifg=' . c.overlay0,
\
\ 'CheatSection': 'guifg=' . c.blue . ' gui=bold',
\ 'CheatKey': 'guifg=' . c.flamingo,
\ }
for [group, spec] in items(groups)
execute 'highlight ' . group . ' ' . spec
endfor
endfunction
" coc installs its own defaults for these groups when it starts and again after
" every :colorscheme, and a plain :highlight in this file was being overridden.
" Running on both events is what makes these stick.
augroup Colours
autocmd!
autocmd VimEnter,ColorScheme * call s:Colours()
augroup END
call s:Colours()
"-------------------------------------------------------------
" Features {{{1
if has('filetype')
filetype indent plugin on
endif
if has('syntax')
syntax on
endif
"------------------------------------------------------------
" Options {{{1
" coc applies cross-file edits (rename, code actions) by loading the other
" buffers. Without 'hidden' those edits fail on any file not already open.
set hidden
" Everything driven by CursorHold reads as broken at the 4000ms default:
" symbol highlighting, diagnostic messages, gitgutter refresh.
set updatetime=300
" gitgutter, ALE and coc all place signs. Pinning the column stops the text
" from shifting sideways every time a sign appears or clears.
set signcolumn=yes
" Airline lives in the status line, and laststatus=1 hides it until a split
" exists.
set laststatus=2
set confirm
set wildmenu
set showcmd
set hlsearch
set ignorecase
set smartcase
set backspace=indent,eol,start
set autoindent
set nostartofline
set ruler
set visualbell
set t_vb=
set cmdheight=1
set nu
set notimeout ttimeout ttimeoutlen=200
set wmh=0
set scrolloff=5
" New splits open where the eye already is.
set splitright
set splitbelow
" Jumping to a file already open somewhere goes to that window or tab instead
" of loading a second copy. Quickfix jumps and :drop both read this.
set switchbuf=useopen,usetab
" A session file records the value of every option and mapping when 'options' is
" included, and restoring it then overrides this vimrc with a stale copy of
" itself. Layout only.
set sessionoptions-=options
if has('mouse')
set mouse=a
" Right click moves the cursor to what was clicked before opening the menu
" defined further down.
set mousemodel=popup_setpos
endif
" Rest the pointer on a symbol and its documentation appears, no click needed.
" This asks the terminal to report every mouse movement, which is a lot of
" traffic and which some terminals mis-report as scroll wheel events. Turn it
" off live with :set noballoonevalterm if it misbehaves.
if has('balloon_eval_term')
set balloonevalterm
set balloondelay=400
set balloonexpr=BalloonHover()
endif
" Folding is built on request from the language server, which knows where a
" function body or an if block actually ends. Nothing starts folded.
set foldlevelstart=99
" Indentation
set shiftwidth=4
set softtabstop=4
set expandtab
" Folding is manual. foldmethod=syntax cost a syntax pass on every edit and
" produced no folds, because none of these filetypes define syntax folds
" without an opt-in flag. This vimrc marks its own sections with {{{1. Those get
" foldmethod=marker instead.
augroup vimrc_folding
autocmd!
autocmd FileType vim setlocal foldmethod=marker foldlevel=0
augroup END
"------------------------------------------------------------
" Keymaps {{{1
"
" The scheme. Every new binding has an obvious home under it:
"
" g<key> go somewhere (LSP navigation, vim's own convention)
" ]x / [x next / previous x
" <Leader>f find
" <Leader>c code
" <Leader>g git
" <Leader>w window
" <Leader>t tab
" <Leader>s session
"
" <Leader>? prints the whole list.
let mapleader = " "
nnoremap <Space> <Nop>
"------------------------------------------------------------
" Keymaps: navigation {{{2
" gd jumps in place, gD opens the definition beside the current file. gD is
" normally go-to-declaration, which for Go and TypeScript is the same location
" as the definition. The key is better spent on the split.
nnoremap <silent> gd :call CocActionAsync('jumpDefinition', g:symbol_open)<CR>
nnoremap <silent> gD :call CocActionAsync('jumpDefinition', 'vsplit')<CR>
nnoremap <silent> gy :call CocActionAsync('jumpTypeDefinition', g:symbol_open)<CR>
nnoremap <silent> gi :call CocActionAsync('jumpImplementation', g:symbol_open)<CR>
nmap <silent> gr <Plug>(coc-references)
" K opens the symbol panel: signature, doc comment, reference and
" implementation counts, and one key per action. gK is the plain hover for
" when the panel is more than the question deserves.
nnoremap <silent> K :call SymbolPanel()<CR>
nnoremap <silent> gK :call ShowDocumentation()<CR>
" Ctrl+click goes to the declaration, or lists usages when already on it.
" Ctrl+right-click walks the jump list back.
nnoremap <silent> <C-LeftMouse> <LeftMouse>:call SmartJump()<CR>
nnoremap <C-RightMouse> <C-o>
" Double click opens the symbol panel on what was clicked, the mouse
" equivalent of K. Shift+click cannot be used: terminals treat Shift with the
" mouse as "bypass the application and let me select text myself". The click
" never reaches Vim. Command+click is unavailable for a related reason,
" the Command key is never forwarded to a terminal program at all.
nnoremap <silent> <2-LeftMouse> :call SymbolPanel()<CR>
" Right click opens this menu at whatever was clicked. <Leader>m opens the
" same menu at the cursor, without the mouse. Every jump here opens in a tab,
" reusing one that already holds the file rather than replacing this buffer.
nnoremenu PopUp.Quick\ documentation :call SymbolPanel()<CR>
nnoremenu PopUp.Go\ to\ definition :call SmartJump()<CR>
nnoremenu PopUp.Find\ usages :call Usages()<CR>
nnoremenu PopUp.Implementations :call CocActionAsync('jumpImplementation', g:symbol_open)<CR>
nnoremenu PopUp.Type\ definition :call CocActionAsync('jumpTypeDefinition', g:symbol_open)<CR>
nnoremenu PopUp.Rename\.\.\. :call CocActionAsync('rename')<CR>
nnoremenu PopUp.Code\ action :call CocActionAsync('codeAction', 'cursor')<CR>
nnoremenu PopUp.Call\ hierarchy :call CocActionAsync('showIncomingCalls')<CR>
nnoremap <silent> <Leader>m :popup PopUp<CR>
" Highlight the other occurrences of whatever the cursor is on.
augroup vimrc_symbol_highlight
autocmd!
autocmd CursorHold * silent call CocActionAsync('highlight')
augroup END
"------------------------------------------------------------
" Keymaps: next and previous {{{2
" Diagnostics come from ALE. coc-settings.json sets diagnostic.displayByAle,
" so the language server's errors arrive through ALE as well.
nnoremap <silent> ]d :ALENextWrap<CR>
nnoremap <silent> [d :ALEPreviousWrap<CR>
" ]c and [c are gitgutter's, left as they are.
" gt and gT already do this in one keystroke and are built in. These exist so
" the bracket family stays complete. Capital T moves the tab instead.
nnoremap <silent> ]t :tabnext<CR>
nnoremap <silent> [t :tabprevious<CR>
nnoremap <silent> ]T :tabmove +1<CR>
nnoremap <silent> [T :tabmove -1<CR>
nnoremap <silent> ]q :cnext<CR>
nnoremap <silent> [q :cprevious<CR>
nnoremap <silent> ]b :bnext<CR>
nnoremap <silent> [b :bprevious<CR>
"------------------------------------------------------------
" Keymaps: find {{{2
nnoremap <silent> <Leader>ff :Files<CR>
nnoremap <silent> <Leader>fg :Rg<CR>
nnoremap <silent> <Leader>fw :Rg <C-r><C-w><CR>
nnoremap <silent> <Leader>fb :Buffers<CR>
nnoremap <silent> <Leader>fl :BLines<CR>
nnoremap <silent> <Leader>fr :History<CR>
nnoremap <silent> <Leader>fc :Commands<CR>
nnoremap <silent> <Leader>fh :Helptags<CR>
nnoremap <silent> <Leader>fm :Maps<CR>
nnoremap <silent> <Leader>fj :Jumps<CR>
" References, implementations and comment mentions of the symbol under the
" cursor, merged into one quickfix list. Same action Ctrl+click reaches.
nnoremap <silent> <Leader>fu :call Usages()<CR>
nnoremap <silent> <Leader>fU :call SmartJump()<CR>
" Project-wide symbol search and the current file's structure.
nnoremap <silent> <Leader>fs :CocList -I symbols<CR>
nnoremap <silent> <Leader>fo :CocList outline<CR>
nnoremap <silent> <Leader>fd :CocList diagnostics<CR>
" fzf's :Rg searches file contents only. Without this it also matches on the
" path. Every hit in a file whose name contains the term then floods the list.
command! -bang -nargs=* Rg
\ call fzf#vim#grep('rg --column --line-number --no-heading --color=always --smart-case '
\ . g:rg_exclude . ' -- ' . shellescape(<q-args>), 1,
\ fzf#vim#with_preview({'options': '--delimiter : --nth 4..'}), <bang>0)
"------------------------------------------------------------
" Keymaps: code {{{2
nmap <Leader>cr <Plug>(coc-rename)
nmap <Leader>ca <Plug>(coc-codeaction-cursor)
xmap <Leader>ca <Plug>(coc-codeaction-selected)
nmap <Leader>cA <Plug>(coc-codeaction-source)
nmap <Leader>cf <Plug>(coc-fix-current)
nmap <Leader>cl <Plug>(coc-codelens-action)
nmap <Leader>cF <Plug>(coc-format)
xmap <Leader>cF <Plug>(coc-format-selected)
nnoremap <silent> <Leader>cs :call ShowDocumentation()<CR>
" Call and type hierarchy. Call hierarchy answers who calls this and what does
" it call. That question only means anything for a function or a method. On a
" type name it fails with "X is not a function". Use ct and cT for types, or
" gi for the concrete implementations of an interface.
nnoremap <silent> <Leader>ci :call CocActionAsync('showIncomingCalls')<CR>
nnoremap <silent> <Leader>co :call CocActionAsync('showOutgoingCalls')<CR>
nnoremap <silent> <Leader>ct :call CocActionAsync('showSuperTypes')<CR>
nnoremap <silent> <Leader>cT :call CocActionAsync('showSubTypes')<CR>
"------------------------------------------------------------
" Keymaps: git {{{2
nnoremap <silent> <Leader>gs :Git<CR>
nnoremap <silent> <Leader>gb :Git blame<CR>
nnoremap <silent> <Leader>gd :Gdiffsplit<CR>
nnoremap <silent> <Leader>gl :Commits<CR>
nnoremap <silent> <Leader>gL :BCommits<CR>
nnoremap <silent> <Leader>gm :Magit<CR>
nnoremap <silent> <Leader>gp :GitGutterPreviewHunk<CR>
nnoremap <silent> <Leader>gu :GitGutterUndoHunk<CR>
nnoremap <silent> <Leader>gS :GitGutterStageHunk<CR>
" Everything uncommitted, with its diff in the preview pane.
nnoremap <silent> <Leader>gc :Changed<CR>
nnoremap <silent> <Leader>gf :GFiles?<CR>
"------------------------------------------------------------
" Keymaps: window {{{2
" Ctrl+hjkl moves focus. <Leader>w plus hjkl moves the window itself.
nnoremap <C-h> <C-w>h
nnoremap <C-l> <C-w>l
" Ctrl+j and Ctrl+k scroll a documentation popup when one is open, and fall
" back to moving between splits when none is.
nnoremap <silent><expr> <C-j> PopupVisible() ? ScrollPopup(3) : "\<C-w>j"
nnoremap <silent><expr> <C-k> PopupVisible() ? ScrollPopup(-3) : "\<C-w>k"
nnoremap <silent> <Leader>wh :wincmd H<CR>
nnoremap <silent> <Leader>wj :wincmd J<CR>
nnoremap <silent> <Leader>wk :wincmd K<CR>
nnoremap <silent> <Leader>wl :wincmd L<CR>
nnoremap <silent> <Leader>wv :vsplit<CR>
nnoremap <silent> <Leader>ws :split<CR>
nnoremap <silent> <Leader>wc :close<CR>
nnoremap <silent> <Leader>wo :only<CR>
nnoremap <silent> <Leader>w= <C-w>=
" Move this window out to its own tab, or pull this tab back into a split.
nnoremap <silent> <Leader>wt :call WindowToTab()<CR>
nnoremap <silent> <Leader>wV :call TabToSplit('vsplit')<CR>
nnoremap <silent> <Leader>wS :call TabToSplit('split')<CR>
" Back to the file edited before this one.
nnoremap <silent> <Leader><Leader> <C-^>
" Resize with the arrow keys.
nnoremap <C-Right> <C-w>>
nnoremap <C-Left> <C-w><
nnoremap <C-Up> <C-w>+
nnoremap <C-Down> <C-w>-
"------------------------------------------------------------
" Keymaps: tab {{{2
nnoremap <silent> <Leader>tn :tabnew<CR>
nnoremap <silent> <Leader>tc :tabclose<CR>
nnoremap <silent> <Leader>to :tabonly<CR>
nnoremap <silent> <Leader>1 :tabn 1<CR>
nnoremap <silent> <Leader>2 :tabn 2<CR>
nnoremap <silent> <Leader>3 :tabn 3<CR>
nnoremap <silent> <Leader>4 :tabn 4<CR>
nnoremap <silent> <Leader>5 :tabn 5<CR>
nnoremap <silent> <Leader>6 :tabn 6<CR>
nnoremap <silent> <Leader>7 :tabn 7<CR>
nnoremap <silent> <Leader>8 :tabn 8<CR>
nnoremap <silent> <Leader>9 :tablast<CR>
"------------------------------------------------------------
" Keymaps: session {{{2
" Save once in a repository and its tabs, windows and splits are then restored by
" a bare vim there, and written back when that Vim quits.
nnoremap <silent> <Leader>ss :call SessionSave()<CR>
nnoremap <silent> <Leader>sl :call SessionLoad()<CR>
nnoremap <silent> <Leader>sd :call SessionDelete()<CR>
" Apply an edit to this file without restarting.
nnoremap <Leader>R :ReloadConfig<CR>
"------------------------------------------------------------
" Keymaps: everything else {{{2
" Yank to end of line, matching D and C. Normal mode only: mapping this with
" :map also rebinds visual Y, which then yanks the selection charwise instead
" of the lines it covers.
nnoremap Y y$
" System clipboard.
vnoremap <Leader>y "+y
vnoremap <Leader>Y "+yg_
nnoremap <Leader>p "+p
nnoremap <Leader>P "+P
" Clear search highlighting. This used to live on <C-l>, where the split
" navigation mapping overwrote it.
nnoremap <silent> <Leader>/ :nohlsearch<CR>
" File tree.
nnoremap <silent> <Leader>e :call ToggleTree()<CR>
nnoremap <silent> <C-b> :call ToggleTree()<CR>
" Build folds from the language server. za, zR and zM take over from there.
nnoremap <silent> <Leader>zf :call BuildFolds()<CR>
" The cheatsheet.
nnoremap <silent> <Leader>? :call Cheatsheet()<CR>
" Interactive fish, since 'shell' is bash for everything Vim runs itself.
command! Term terminal ++curwin fish
" Scroll five lines at a time.
nnoremap <C-e> 5<C-e>
nnoremap <C-y> 5<C-y>
vnoremap <C-e> 5<C-e>
vnoremap <C-y> 5<C-y>
" Option and Alt bindings. macOS sends the composed character for Option plus
" a letter rather than a meta key, which is why these are the glyphs and not
" <A-j>. Option+j is the character below, Option+b is the integral sign.
if has('macunix')
" Move the current line or selection up and down.
xnoremap ˚ :m-2<CR>gv=gv
xnoremap ∆ :m'>+1<CR>gv=gv
nnoremap ˚ :<C-u>m-2<CR>==
nnoremap ∆ :<C-u>m+<CR>==
" Option+b and Option+f jump a word back and forward, in every mode.
nnoremap ∫ b
nnoremap ƒ w
xnoremap ∫ b
xnoremap ƒ w
inoremap ∫ <C-o>b
inoremap ƒ <C-o>w
" Option+Backspace deletes the word behind the cursor, as it does in a shell.
inoremap <M-BS> <C-w>
else
xnoremap <A-Up> :m-2<CR>gv=gv
xnoremap <A-Down> :m'>+1<CR>gv=gv
nnoremap <A-Up> :<C-u>m-2<CR>==
nnoremap <A-Down> :<C-u>m+<CR>==
nnoremap <A-b> b
nnoremap <A-f> w
xnoremap <A-b> b
xnoremap <A-f> w
inoremap <A-b> <C-o>b
inoremap <A-f> <C-o>w
inoremap <A-BS> <C-w>
endif
"------------------------------------------------------------
" Keymaps: insert mode {{{2
" The two completions are now separate, one key each.
"
" Ctrl-n / Ctrl-p move through coc's menu
" Enter take the coc item you moved to
" Ctrl-l take Copilot's ghost text
" Ctrl-] dismiss Copilot
" Tab a tab
"
" suggest.noselect leaves nothing selected until you press Ctrl-n. Enter then
" only ever accepts something you actually chose. Otherwise it is a newline.
inoremap <silent><expr> <Enter>
\ coc#pum#visible() && coc#pum#info()['index'] >= 0
\ ? coc#pum#confirm() : "\<C-g>u\<CR>"
imap <silent><script><expr> <C-l> copilot#Accept("\<C-l>")
" Esc closes coc's menu before it leaves insert mode. This sits in the path of
" every arrow key, since those send Esc-prefixed sequences. It works because
" ttimeoutlen is short. Remove it first if insert mode ever feels laggy.
inoremap <silent><expr> <Esc> coc#pum#visible() ? coc#pum#close() : "\<Esc>"
" Ask for completions without typing another character.
inoremap <silent><expr> <C-Space> coc#refresh()
"------------------------------------------------------------
" Functions {{{1
function! ShowDocumentation() abort
if CocAction('hasProvider', 'hover')
call CocActionAsync('definitionHover')
else
call feedkeys('K', 'in')
endif
endfunction
"------------------------------------------------------------
" Functions: usages {{{2
"------------------------------------------------------------
" Functions: changed files {{{2
" Every path with uncommitted work, staged or not, plus untracked ones. The
" preview pane shows that file's diff rather than the file, which is what a
" source control panel shows.
function! s:ChangedSource() abort
let out = []
for line in systemlist('git status --porcelain=v1 --untracked-files=all')
if len(line) < 4
continue
endif
" A rename reads "old -> new". Keep the name the file has now.
let path = substitute(line[3:], '^.* -> ', '', '')
let path = substitute(path, '^"\(.*\)"$', '\1', '')
call add(out, printf("%s\t%s", line[0:1], path))
endfor
return out
endfunction
function! s:ChangedSink(lines) abort
for line in a:lines
let parts = split(line, "\t")
if len(parts) > 1
execute 'tab drop' fnameescape(parts[1])
endif
endfor
endfunction
command! Changed call fzf#run(fzf#wrap({
\ 'source': s:ChangedSource(),
\ 'sink*': function('s:ChangedSink'),
\ 'options': ['--ansi', '--multi', '--prompt', 'Changed> ',
\ '--delimiter', "\t", '--preview-window', 'right:60%',
\ '--preview',
\ 'if git ls-files --error-unmatch {2} >/dev/null 2>&1; then '
\ . 'git diff --color=always HEAD -- {2} | head -500; '
\ . 'else cat {2} | head -200; fi']}))
"------------------------------------------------------------
" Functions: folding {{{2
" Ask the language server where the folds are and leave them all open. The
" server knows a function body from an if block, which is what indent folding
" gets wrong.
function! BuildFolds() abort
if !s:HasCoc('foldingRange')
echohl WarningMsg | echo 'No folding provider for this filetype' | echohl None
return
endif
call CocAction('fold')
normal! zR
echo 'Folds built. za toggles, zR opens all, zM closes all.'
endfunction
"------------------------------------------------------------
" Functions: windows and tabs {{{2
" Take this window out of its split and give it a tab of its own. <C-w>T does
" the same thing and is native, this is here so the help screen can name it.
function! WindowToTab() abort
if winnr('$') < 2
echohl WarningMsg | echo 'Only one window in this tab' | echohl None
return
endif
wincmd T
endfunction
" The reverse. Close this tab and reopen its file as a split of the tab that
" Vim lands on, which is the one to the left.
function! TabToSplit(cmd) abort
if tabpagenr('$') < 2
echohl WarningMsg | echo 'Only one tab open' | echohl None
return
endif
let buf = bufnr('%')
tabclose
execute a:cmd
execute 'buffer' buf
endfunction
"------------------------------------------------------------
" Functions: symbol panel {{{2
" How every jump started from the panel or the right click menu opens its
" target. drop reuses a window or tab already showing the file, and 'switchbuf'
" further up is what lets it look in other tabs.
let g:symbol_open = 'tab drop'
let s:panel = {'id': 0}
" One blank line between paragraphs, none trailing.
function! s:Squeeze(lines) abort
let out = []
for line in a:lines
if line =~# '^\s*$' && (empty(out) || out[-1] =~# '^\s*$')
continue
endif
call add(out, line)
endfor
while !empty(out) && out[-1] =~# '^\s*$'
call remove(out, -1)
endwhile
return out
endfunction
" Hover text arrives as markdown. A fenced block holds the signature and the doc
" comment follows it as prose. The two are returned separately so that only the
" signature is later highlighted as source. Highlighting the whole panel as Go
" gave the word "for" in a doc comment the keyword colour.
function! s:SplitHover(entries) abort
let code = []
let doc = []
let fenced = 0
for entry in type(a:entries) == v:t_list ? a:entries : []
for line in split(entry, "\n")
if line =~# '^\s*```'
let fenced = !fenced
continue
endif
if fenced
call add(code, line)
continue
endif
if line =~# '^\s*---\+\s*$'
continue
endif
" A hover ends with a link to the symbol on a documentation site. Worth
" having in a browser, noise in a panel that cannot follow it.
if line =~# '^\s*\[[^]]*\]([^)]*)\s*$'
continue
endif
let line = substitute(line, '\[\([^]]*\)\](\([^)]*\))', '\1', 'g')
call add(doc, substitute(line, '`', '', 'g'))
endfor
endfor
return {'code': s:Squeeze(code), 'doc': s:Squeeze(doc)}
endfunction
function! s:PanelCount(n) abort
return a:n < 0 ? '...' : a:n
endfunction
" Builds the panel text and records where each part of it ended up, because the
" syntax rules below address those parts by line number and the signature grows
" once the server answers.
function! s:PanelLines() abort
let lines = copy(s:panel.hover.code)
let s:panel.code = len(lines)
let doc = s:panel.hover.doc
if empty(lines) && empty(doc)
let doc = ['No documentation for ' . s:panel.word]
endif
if !empty(doc)
if !empty(lines)
call add(lines, '')
endif
let lines += doc
endif
let s:panel.doc = len(lines)
call add(lines, '')
call add(lines, printf('%s references %s implementations',
\ s:PanelCount(s:panel.refs), s:PanelCount(s:panel.impls)))
let s:panel.counts = len(lines)
call add(lines, '')
call add(lines, 'd definition y type i implementations r references')
call add(lines, 'R rename a action c calls j k scroll q close')
return lines
endfunction
" syntax include is the mechanism for embedding one language in part of a buffer.
" Every item it reads is marked contained, which is what keeps Go highlighting
" inside the signature region and out of the prose below it.
function! s:PanelSyntax() abort
if s:panel.id == 0
return
endif
let cmds = ['syntax clear']
if !empty(s:panel.ft) && s:panel.code > 0
call extend(cmds, [
\ 'unlet! b:current_syntax',
\ 'syntax include @PanelLang syntax/' . s:panel.ft . '.vim',
\ 'unlet! b:current_syntax',
\ printf('syntax region PanelCode start=/\%%1l/ end=/\%%%dl/ contains=@PanelLang keepend',
\ s:panel.code + 1),
\ ])
endif
call extend(cmds, [
\ printf('syntax match PanelDoc /\%%>%dl\%%<%dl.*/', s:panel.code, s:panel.doc + 1),
\ printf('syntax match PanelCounts /\%%%dl.*/', s:panel.counts),
\ printf('syntax match PanelKeys /\%%>%dl.*/', s:panel.counts),
\ ])
for cmd in cmds
call win_execute(s:panel.id, 'silent! ' . cmd)
endfor
endfunction
function! s:PanelRedraw() abort
if s:panel.id != 0 && !empty(popup_getoptions(s:panel.id))
call popup_settext(s:panel.id, s:PanelLines())
call s:PanelSyntax()
endif
endfunction
function! s:PanelScroll(winid, n) abort
let pos = popup_getpos(a:winid)
if empty(pos)
return
endif
let last = str2nr(trim(win_execute(a:winid, "echo line('$')")))
let first = pos.firstline + a:n
if first < 1
let first = 1
elseif pos.lastline + a:n > last
let first = last + pos.firstline - pos.lastline
endif
call popup_setoptions(a:winid, {'firstline': max([1, first])})
endfunction
function! s:PanelFilter(winid, key) abort
if a:key ==# 'j' || a:key ==# "\<Down>" || a:key ==# "\<ScrollWheelDown>"
call s:PanelScroll(a:winid, a:key ==# "\<ScrollWheelDown>" ? 3 : 1)
return 1
elseif a:key ==# 'k' || a:key ==# "\<Up>" || a:key ==# "\<ScrollWheelUp>"
call s:PanelScroll(a:winid, a:key ==# "\<ScrollWheelUp>" ? -3 : -1)
return 1
elseif a:key ==# "\<C-d>" || a:key ==# "\<PageDown>"
call s:PanelScroll(a:winid, 5)
return 1
elseif a:key ==# "\<C-u>" || a:key ==# "\<PageUp>"
call s:PanelScroll(a:winid, -5)
return 1
endif
if a:key ==# 'q' || a:key ==# "\<Esc>"
call popup_close(a:winid)
return 1
endif
let jumps = {
\ 'd': 'jumpDefinition',
\ 'y': 'jumpTypeDefinition',
\ 'i': 'jumpImplementation',
\ 'D': 'jumpDeclaration',
\ }
if has_key(jumps, a:key)
call popup_close(a:winid)