-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvimrc
1859 lines (1518 loc) · 52.6 KB
/
vimrc
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
" Author: Harrison Katz <[email protected]>
"
" This is my personal vimrc, feel free to ask me questions about anything that
" you may not understand. Thanks for taking a look!
" NOTE: the below MUST be pointed to the correct installation directory for
" vim extras. If you do not know where this is please contact the author.
let g:dotfiles_vim_dir=$HOME.'/.dotfiles-harrison/.vim/'
" lua config in vim, see: https://herrbischoff.com/2022/07/neovim-using-init-vim-and-init-lua-concurrently/
" lua <<EOF
" <lua code>
" EOF
" Note: These must be installed on the system for everything to work properly
" Pre-reqs:
" - Nerd Fonts: https://www.nerdfonts.com/
" - Installed and Configured for Terminal
" Plugins first, then settings
" Plugins ------------------------------- {{{
"""BEGIN PLUG INSTALLATION"""
set nocompatible " required, sets vim to be incompatible with vi
filetype off " required, turns off automatic filetype detection for installation
" Vim Plug
source ~/.dotfiles-harrison/plug.vim
call plug#begin(expand(g:dotfiles_vim_dir.'plugged'))
" fancy icons
Plug 'nvim-tree/nvim-web-devicons'
" repeat everything with '.'
Plug 'tpope/vim-repeat'
" better .swp file handling
" Plug 'chrisbra/Recover.vim'
" planery
Plug 'nvim-lua/plenary.nvim'
" telescope
Plug 'kkharji/sqlite.lua'
Plug 'prochri/telescope-all-recent.nvim'
Plug 'nvim-telescope/telescope.nvim'
" nvim lsp and code completion
Plug 'williamboman/mason.nvim', { 'do': ':MasonUpdate' }
Plug 'williamboman/mason-lspconfig.nvim'
Plug 'neovim/nvim-lspconfig'
Plug 'ray-x/guihua.lua', { 'do': 'cd lua/fzy && make' }
Plug 'ray-x/navigator.lua'
Plug 'hrsh7th/nvim-cmp'
Plug 'hrsh7th/cmp-nvim-lsp'
Plug 'hrsh7th/cmp-nvim-lua'
Plug 'hrsh7th/cmp-buffer'
Plug 'hrsh7th/cmp-nvim-lsp-signature-help'
Plug 'ray-x/lsp_signature.nvim'
Plug 'FelipeLema/cmp-async-path'
" Github Copilot
Plug 'zbirenbaum/copilot.lua'
Plug 'zbirenbaum/copilot-cmp'
" go development
Plug 'ray-x/go.nvim', { 'for': 'go', 'do': ':GoInstallBinaries' }
" easy alignment
Plug 'junegunn/vim-easy-align'
" auto-pairs
Plug 'windwp/nvim-autopairs'
" which-key
Plug 'folke/which-key.nvim'
" Text Object Plugins
" add more builtin text object targets like quotes, tags, braces, etc...
Plug 'wellle/targets.vim'
" text object user denifinitions
Plug 'kana/vim-textobj-user'
" text object for variable segments with 'v'
Plug 'Julian/vim-textobj-variable-segment', { 'branch': 'main' }
" Filetype Plugins
Plug 'sheerun/vim-polyglot'
" tree-sitter
Plug 'nvim-treesitter/nvim-treesitter', { 'do': ':TSUpdate' }
Plug 'nvim-treesitter/nvim-treesitter-refactor'
Plug 'nvim-treesitter/playground'
" adds folding, fancy settings, and more!
Plug 'plasticboy/vim-markdown', { 'for': 'markdown' }
" LaTeX Everything
Plug 'LaTeX-Box-Team/LaTeX-Box', { 'for': 'tex' }
" snippets for code insertion
Plug 'L3MON4D3/LuaSnip', {'tag': 'v1.*'}
" debug print
Plug 'andrewferrier/debugprint.nvim'
" auto-upcase sql terms
Plug 'hjkatz/sql_iabbr.vim', { 'for': 'sql' }
" comment command with 'gc'
Plug 'tpope/vim-commentary'
Plug 'JoosepAlviste/nvim-ts-context-commentstring'
" add ending control statements in languages like bash, zsh, vimscript, etc...
Plug 'tpope/vim-endwise'
" Abolish
" - Abbreviations: :Abolish {despa,sepe}rat{e,es,ed,ing,ely,ion,ions,or} {despe,sepa}rat{}
" - Sbustitution: :%Subvert (or :%S) :%S/facilit{y,ies}/building{,s}/g
" - Coercion: fooBar -> foo_bar --> `crs` (coerce to snake_case)
" - snake_case `crs`
" - MixedCase `crm`
" - camelCase `crc`
" - UPPER_CASE `cru`
" - dash-case `cr-`
" - dot.case `cr.`
" - space case `cr<space>`
" - Title Case `crt`
Plug 'tpope/vim-abolish'
" git in vim
Plug 'tpope/vim-fugitive'
" Plug 'tommcdo/vim-fubitive'
Plug 'tpope/vim-rhubarb'
" act on surrounding items like quotes, tags, braces, etc...
Plug 'tpope/vim-surround'
" undo tree viewer and manipulater
Plug 'mbbill/undotree', { 'on': 'UndotreeToggle' }
" whitespace detection and deletion
Plug 'ntpeters/vim-better-whitespace'
" asks which file you meant to open
Plug 'EinfachToll/DidYouMean'
" quickfix/location list taming
Plug 'folke/trouble.nvim'
" git signs in the gutter
Plug 'lewis6991/gitsigns.nvim'
" tagbar
Plug 'majutsushi/tagbar'
" colorscheme tokyonight
Plug 'folke/tokyonight.nvim'
call plug#end()
filetype plugin indent on " required
" }}}
" 'Set'ings ---------------------------- {{{
set ts=4 " tab spacing is 4 spaces
set sw=4 " shift width is 4 spaces
set expandtab " expand all tabs to spaces
set ai " autoindent a file based on filetype
set cindent " c-style indenting while typing
set background=dark " our backdrop is dark
set number " show line numbers
set ruler " show row,col count on bottom bar
set backspace=eol,start,indent " backspace wraps around indents, start of lines, and end of lines
set ignorecase " ignore case when searching
set smartcase " ...unless we have atleast 1 capital letter
set incsearch " search incrementally
set infercase " infer the case of the completion word
set formatoptions=tcqronj " see :help fo-table for more information
set pastetoggle=<F12> " sets <F12> to toggle paste mode
set hlsearch " highlight search results
set wrap " wrap lines
set scrolloff=10 " leave at least 10 lines at the bottom/top of screen when scrolling
set sidescrolloff=15 " leave at least 15 lines at the right/left of screen when scrolling
set sidescroll=1 " scroll sidways 1 character at a time
set autowrite " autowrite on things like :next, :prev, :etc...
set lazyredraw " redraw the screen lazily
set updatetime=300 " set vim's updatetime
set shortmess-=F " allow filetype-based autocommands to show popup messages
set mouse= " turn off mouse support
" Wildmenu completion {{{
set wildmenu " turn on globing for opening files
set wildmode=longest:full,full " see :help wildmode for more information
set wildignore+=.hg,.git,.svn " Version control
set wildignore+=*.aux,*.out,*.toc " LaTeX intermediate files
set wildignore+=*.jpg,*.bmp,*.gif,*.png,*.jpeg " binary images
set wildignore+=*.o,*.obj,*.exe,*.dll,*.manifest " compiled object files
set wildignore+=*.spl " compiled spelling word lists
set wildignore+=*.sw? " Vim swap files
set wildignore+=*.luac " Lua byte code
set wildignore+=*.pyc " Python byte code
set wildignore+=*.orig " Merge resolution files
" }}}
" }}}
" Functions ---------------------------- {{{
" Pulse Line {{{
function! s:Pulse()
redir => old_hi
silent execute 'hi CursorLine'
redir END
let old_hi = split(old_hi, '\n')[0]
let old_hi = substitute(old_hi, 'xxx', '', '')
let steps = 8
let width = 1
let start = width
let end = steps * width
let color = 233
for i in range(start, end, width)
execute "hi CursorLine ctermbg=" . (color + i)
redraw
sleep 6m
endfor
for i in range(end, start, -1 * width)
execute "hi CursorLine ctermbg=" . (color + i)
redraw
sleep 6m
endfor
execute 'hi ' . old_hi
endfunction
command! -nargs=0 Pulse call s:Pulse()
" }}}
" Persistant undo {{{
if has('persistent_undo')
" create undodir
if isdirectory( g:dotfiles_vim_dir . 'undo' ) == 0
exec 'silent !mkdir -p ' . g:dotfiles_vim_dir . 'undo > /dev/null 2>&1'
endif
let &undodir = expand( g:dotfiles_vim_dir . 'undo' )
set undofile
endif
" }}}
" substring {{{
" from https://gist.github.com/tyru/984296
" Substitute a:from => a:to by string.
" To substitute by pattern, use substitute() instead.
function! s:substring(str, from, to)
if a:str ==# '' || a:from ==# ''
return a:str
endif
let str = a:str
let idx = stridx(str, a:from)
while idx !=# -1
let left = idx ==# 0 ? '' : str[: idx - 1]
let right = str[idx + strlen(a:from) :]
let str = left . a:to . right
let idx = stridx(str, a:from)
endwhile
return str
endfunction
" }}}
" chomp {{{
function! s:chomp(string)
return substitute(a:string, '\n\+$', '', '')
endfunction
" }}}
" check_back_space {{{
function! s:check_back_space() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~# '\s'
endfunction
" }}}
" }}}
" Misc --------------------------------- {{{
" Leader
let mapleader = ','
let maplocalleader = ","
" no longer needed in nvim with treesitter?
" turn on syntax coloring and indentation based on the filetype
" syntax on
" filetype on
" filetype indent on
" easy file reloading
nnoremap <leader>rc :w<CR>:so %<CR>
" show the syntax highlighting group of the object under the cursor
" map <F10> :echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") . '> trans<'
" \ . synIDattr(synID(line("."),col("."),0),"name") . "> lo<"
" \ . synIDattr(synIDtrans(synID(line("."),col("."),1)),"name") . ">"<CR>
" <F5> insert date
inoremap <F5> <C-R>=strftime("%c")<CR>
" keep search pattern in center of screen
nnoremap n nzz
nnoremap N Nzz
nnoremap * *zz
nnoremap # #zz
nnoremap g* g*zz
nnoremap g# g#zz
" toggle cursorline
nnoremap <leader>cc :set cursorline!<CR>
" don't move cursor on '*'
nnoremap <silent> * :let stay_star_view = winsaveview()<cr>*:call winrestview(stay_star_view)<cr>
" move in split windows with ctrl+hjkl
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
" move up/down on wrapped lines !!BEWARE OF MACROS!!
nnoremap j gj
nnoremap k gk
" prevent accidental help
noremap <F1> <Esc>
inoremap <F1> <Esc>
" more intuitive increment/decrement with +/-
nnoremap + <C-a>
nnoremap - <C-x>
" Panic Button
nnoremap <f9> mzggg?G`z
" Use sane regexes.
nnoremap / /\v
vnoremap / /\v
" Remap stupid shift letters
command! Q q
command! W w
command! Wq wq
" Prettify a hunk of JSON with <localleader>j
nnoremap <buffer> <localleader>j ^vg_:!python -m json.tool<cr>
vnoremap <buffer> <localleader>j :!python -m json.tool<cr>
" Move blocks of text while in visual mode
vnoremap K :m '<-2<CR>gv=gv
vnoremap J :m '>+1<CR>gv=gv
vnoremap <S-Up> :m '<-2<CR>gv=gv
vnoremap <S-Down> :m '>+1<CR>gv=gv
" Allow saving of files as sudo when I forgot to start vim using sudo.
cmap w!! w !sudo tee > /dev/null %
" because saving the ';' file is so useful...
cmap w; wq
" I don't think I ever want to use ;
cmap ; q
" except for sometimes
cnoremap :: ;
" Disable that fucking 'Entering Ex mode. Type 'visual' to go to Normal mode.'
map Q <Nop>
" Disable vim command history bullshit
map q: <Nop>
" Ctrl-Y by word
inoremap <expr> <c-y> matchstr(getline(line('.')-1), '\%' . virtcol('.') . 'v\%(\k\+\\|.\)')
" }}}
" Plugin Config ------------------------ {{{
" ray-x/guihua ----------------------------- {{{
lua <<EOF
require("guihua.maps").setup({
maps = {
close_view = 'q',
prev = '<Home>',
next = '<End>',
confirm = '<CR>',
split = '<C-s>',
vsplit = '<C-v>',
tabnew = '<C-t>', -- will be hijacked to use send_qf -> trouble instead
send_qf = '<C-q>',
},
})
function is_win_guihua_floating(win)
-- default to current window
if win ~= false then win = 0 end
-- get the config for the window
local config = vim.api.nvim_win_get_config(win)
-- check if the window is floating
if config.relative == "" then return false end
-- it just so happens that .title of each floating window created by guihua looks like this
-- title = { { "R", "GHRainbow1" }, { "e", "GHRainbow2" }, ... }
-- so let's check for that I guess
if not config.title then return false end
local title = config.title
if #title <= 0 then return false end
local first_item = title[1]
if #first_item < 2 then return false end
local first_string = first_item[2]
if vim.startswith(first_string, "GH") then return true end
return false
end
function hijack_guihua_mappings(buf)
-- get bufmap for the current win
buf = 0
local bufmap = vim.api.nvim_buf_get_keymap(buf, 'n')
-- find the function with lhs = "<C-Q>" (send items to quickfix)
local fn = nil
for _, v in pairs(bufmap) do
if v.lhs and v.lhs == "<C-Q>" then
fn = v.callback
break
end
end
-- -- override the new tab mapping to instead call the send to quickfix callback
vim.keymap.set('n', '<C-t>', fn, { buffer = buf })
vim.keymap.set('i', '<C-t>', fn, { buffer = buf })
end
vim.api.nvim_create_autocmd("WinNew", {
pattern = "*",
callback = function()
if is_win_guihua_floating() then
-- get the current buffer
local buf = vim.api.nvim_win_get_buf(0)
local timer = vim.loop.new_timer()
-- delay the hijack b/c the bufmap is not filled in until after the window is created
timer:start(50, 0, vim.schedule_wrap(hijack_guihua_mappings))
end
end,
})
EOF
" }}}
" nvim-autopairs ----------------------------- {{{
lua <<EOF
require("nvim-autopairs").setup({
disable_filetype = { "TelescopePrompt" , "guihua", "guihua_rust", "clap_input" },
})
EOF
autocmd FileType guihua lua require('cmp').setup.buffer { enabled = false }
autocmd FileType guihua_rust lua require('cmp').setup.buffer { enabled = false }
" }}}
" trouble ----------------------------- {{{
lua <<EOF
require("trouble").setup({
-- keymaps
keys = {
["?"] = "help", -- opens the trouble help
["q"] = "close", -- close the list
["<esc>"] = "cancel", -- cancel the preview and get back to your last window / buffer / cursor
["r"] = "refresh", -- manually refresh
["o"] = "jump_close", -- jump to the item and close the list
["<tab>"] = { -- switch severity (ERROR, WARNING, INFO, HINT, ALL)
action = function(view)
local f = view:get_filter("severity")
local severity = ((f and f.filter.severity or 0) + 1) % 5
view:filter({ severity = severity }, {
id = "severity",
template = "{hl:Title}Filter:{hl} {severity}",
del = severity == 0,
})
end,
desc = "Toggle Severity Filter",
},
["<c-s>"] = "jump_split", -- open buffer in new split
["<c-v>"] = "jump_vsplit", -- open buffer in new vsplit
["zA"] = "fold_toggle",
["zR"] = "fold_toggle",
["<space>"] = "fold_toggle", -- toggle fold of one or all diagnostics
},
cycle_results = true, -- cycle item list when reaching beginning or end
auto_open = false, -- automatically open the list when you have diagnostics
auto_close = false, -- automatically close the list when you have no diagnostics
auto_preview = true, -- automatically preview the location of the diagnostic. <esc> to close preview and go back to last window
auto_fold = false, -- automatically fold a file trouble list at creation
-- auto_jump = true,
warn_no_results = true,
open_no_results = true,
})
local toggle_trouble = function()
local trouble = require("trouble")
-- Check whether we deal with a quickfix or location list buffer, close the window and open the
-- corresponding Trouble window instead.
if vim.fn.getloclist(0, { filewinid = 1 }).filewinid ~= 0 then
vim.defer_fn(function()
vim.cmd.lclose()
trouble.toggle("loclist")
end, 0)
else
vim.defer_fn(function()
vim.cmd.cclose()
trouble.toggle("qflist")
end, 0)
end
end
local trouble_next_item = function()
require("trouble").next({
skip_groups = true,
jump = true,
})
end
local trouble_prev_item = function()
require("trouble").prev({
skip_groups = true,
jump = true,
})
end
-- global mappings
vim.keymap.set('n', '<F5>', toggle_trouble)
vim.keymap.set('n', '<leader>q', toggle_trouble)
vim.keymap.set('n', '<Home>', trouble_prev_item)
vim.keymap.set('n', '<End>', trouble_next_item)
-- hijack quickfix and location lists
local function hijack_qflist()
local trouble = require("trouble")
-- Check whether we deal with a quickfix or location list buffer, close the window and open the
-- corresponding Trouble window instead.
if vim.fn.getloclist(0, { filewinid = 1 }).filewinid ~= 0 then
vim.defer_fn(function()
vim.cmd.lclose()
trouble.open("loclist")
end, 0)
else
vim.defer_fn(function()
vim.cmd.cclose()
trouble.open("qflist")
end, 0)
end
end
local group = vim.api.nvim_create_augroup("HijackQuickfixWithTrouble", {})
vim.api.nvim_create_autocmd("BufWinEnter", {
pattern = "quickfix", -- buf name
group = group,
callback = hijack_qflist,
})
EOF
" }}}
" telescope ----------------------------- {{{
lua <<EOF
require("telescope-all-recent").setup({
debug = false,
scoring = {
recency_modifier = { -- also see telescope-frecency for these settings
[1] = { age = 60, value = 100 }, -- past 1 hour
[2] = { age = 240, value = 90 }, -- past 4 hours
[3] = { age = 1440, value = 80 }, -- past day
[4] = { age = 4320, value = 60 }, -- past 3 days
[5] = { age = 10080, value = 40 }, -- past week
[6] = { age = 43200, value = 20 }, -- past month
[7] = { age = 129600, value = 10 } -- past 90 days
},
-- how much the score of a recent item will be improved.
boost_factor = 0.0001
},
default = {
disable = true, -- disable any unkown pickers (recommended)
use_cwd = false, -- differentiate scoring for each picker based on cwd
sorting = 'frecency' -- sorting: options: 'recent' and 'frecency'
},
pickers = { -- allows you to overwrite the default settings for each picker
man_pages = { -- enable man_pages picker. Disable cwd and use frecency sorting.
disable = false,
use_cwd = false,
sorting = 'frecency',
},
}
})
-- :help telescope.mappings
local telescopeMappings = {
["<C-e>"] = "close",
["<Home>"] = "move_selection_previous",
["<End>"] = "move_selection_next",
["<C-s>"] = "select_horizontal",
["<C-v>"] = "select_vertical",
["<C-k>"] = "preview_scrolling_up",
["<C-j>"] = "preview_scrolling_down",
["<C-l>"] = "preview_scrolling_right",
["<C-h>"] = "preview_scrolling_left",
["<C-t>"] = require("trouble.sources.telescope").open,
}
require("telescope").setup({
defaults = {
prompt_prefix = "❯ ",
selection_caret = "❯ ",
initial_mode = "insert", -- or "normal"
layout_strategy = "vertical",
mappings = {
i = telescopeMappings,
n = telescopeMappings,
},
},
})
-- cache for git rev-parse --is-inside-work-tree by pwd
local is_inside_git_tree = {}
-- returns the git root from the current directory
local get_git_root = function()
local dot_git_path = vim.fn.finddir(".git", ".;")
return vim.fn.fnamemodify(dot_git_path, ":h")
end
-- wraps telescope picker with opts to set cwd if inside git root, otherwise fallback to pwd
local wrap_project_files_fallback_cwd = function(fnPicker)
return function(opts)
if opts == nil then
opts = {}
end
local cwd = vim.fn.getcwd()
if is_inside_git_tree[cwd] == nil then
vim.fn.system("git rev-parse --is-inside-work-tree")
is_inside_git_tree[cwd] = vim.v.shell_error == 0
end
if is_inside_git_tree[cwd] then
opts["cwd"] = get_git_root()
end
fnPicker(opts)
end
end
local picker_find_files = require("telescope.builtin").find_files
local picker_live_grep = require("telescope.builtin").live_grep
-- function to open telescope with horizontal selection mapped to <CR>
local telescope_find_files_horizontal = function(opts)
local picker = wrap_project_files_fallback_cwd(picker_find_files)
picker({
attach_mappings = function(_, map)
map({"i", "n"}, "<CR>", "select_horizontal")
return true
end,
})
end
-- function to open telescope with vertical selection mapped to <CR>
local telescope_find_files_vertical = function(opts)
local picker = wrap_project_files_fallback_cwd(picker_find_files)
picker({
attach_mappings = function(_, map)
map({"i", "n"}, "<CR>", "select_vertical")
return true
end,
})
end
-- keymaps
vim.keymap.set('n', '<leader>ff', wrap_project_files_fallback_cwd(picker_find_files), {})
vim.keymap.set('n', '<leader>fg', wrap_project_files_fallback_cwd(picker_live_grep), {})
vim.keymap.set('n', '<leader>rg', wrap_project_files_fallback_cwd(picker_live_grep), {})
vim.keymap.set('n', '<leader>fh', require("telescope.builtin").help_tags, {}) -- :help
vim.keymap.set('n', '<leader>hh', require("telescope.builtin").help_tags, {}) -- :help
vim.keymap.set('n', 'Sp', require("telescope.builtin").help_tags, {}) -- :help
-- commands
vim.api.nvim_create_user_command( "Sp", telescope_find_files_horizontal, {})
vim.api.nvim_create_user_command( "SP", telescope_find_files_horizontal, {})
vim.api.nvim_create_user_command( "Vsp", telescope_find_files_vertical, {})
vim.api.nvim_create_user_command( "VSp", telescope_find_files_vertical, {})
vim.api.nvim_create_user_command( "VSP", telescope_find_files_vertical, {})
EOF
" }}}
" mason / mason-lspconfig --------------------------- {{{
lua <<EOF
require("mason").setup({
-- :help mason-debugging
-- :MasonLog
-- log_level = vim.log.levels.DEBUG,
install_root_dir = vim.g.dotfiles_vim_dir .. "mason",
ui = {
icons = {
package_installed = "✓",
package_pending = "➜",
package_uninstalled = "✗"
},
},
})
require("mason-lspconfig").setup({
automatic_installation = true,
ensure_installed = {
-- list of lsp mason packages to keep installed
"vimls",
"lua_ls",
"terraformls",
"jqls",
-- "ltex", -- prints too many debug messages
"taplo",
"yamlls",
"helm_ls",
"pyright",
"jsonls",
"gopls",
"golangci_lint_ls", -- golangci-lint + lsp
"dockerls",
"bashls",
"ts_ls",
},
})
EOF
" }}}
" lspconfig / navigator / cmp ----------------------------- {{{
" See: https://github.com/VonHeikemen/lsp-zero.nvim/blob/v2.x/doc/md/lsp.md#you-might-not-need-lsp-zero
" See: https://github.com/ray-x/navigator.lua
lua <<EOF
local has_words_before = function()
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil
end
local feedkey = function(key, mode)
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true)
end
local cmp = require('cmp')
local luasnip = require('luasnip')
-- setup various cmp sources
require("copilot_cmp").setup({})
-- Enable navigator with mason support
-- - disable navigator from installing/setting up lsp (use mason and mason-lsp instead)
-- - disable navigator from configuring keymappings for lsp (use mason instead)
-- See: https://github.com/ray-x/navigator.lua/issues/239#issuecomment-1287949589
require("navigator").setup({
debug = false,
mason = true,
default_mapping = false,
lsp_signature_help = true,
signature_help_cfg = nil, -- configure ray-x/lsp_signature_help on its own
lines_show_prompt = 20, -- when result list is >= number, then show input prompt
prompt_mode = 'normal', -- default mode for prompt
lsp = {
-- Disable all lsp setup including code actions, lens, diagnostics, etc...
-- I will set these up via copy/paste functions from ray-x/navigator.lua
-- into my lsp config below
-- some config settings will still be loaded and respected during require("navigator.*").some_fn calls
enable = false,
disable_lsp = "all",
code_action = {
enable = true,
sign = true,
delay = 5000, -- ms
},
diagnostic_scrollbar_sign = false, -- disable scrollbar symbols
diagnostic_virtual_text = '', -- empty floating text prefix
display_diagnostic_qf = false, -- do not display qf on save
tsserver = {
single_file_support = true,
},
ts_ls = { -- renamed from tsserver
single_file_support = true,
},
format_on_save = false,
},
icons = {
icons = true, -- requires nerd fonts
-- Code action
code_action_icon = ' ',
-- code lens
code_lens_action_icon = ' ',
-- Diagnostics -- appear in the sign column
diagnostic_head = "", -- empty prefix
diagnostic_err = "",
diagnostic_warn = "",
diagnostic_info = "",
diagnostic_hint = "",
-- these icons appear in the floating windows
diagnostic_head_severity_1 = ' ',
diagnostic_head_severity_2 = ' ',
diagnostic_head_severity_3 = ' ',
diagnostic_head_description = '', -- empty description (suffix for severities)
diagnostic_virtual_text = '', -- empty floating text prefix
diagnostic_file = '', -- icon in floating window indicating a file contains diagnostics
-- Values icons appear in floating references view
value_definition = '', -- identifier defined
value_changed = ' ', -- identifier modified
side_panel = {
section_separator = '',
line_num_left = '',
line_num_right = '',
inner_node = '├○',
outer_node = '╰○',
bracket_left = '⟪',
bracket_right = '⟫',
},
-- Treesitter
-- Note: many many more node.type or kind may be available
match_kinds = {
var = ' ', -- variable
const = ' ',
method = 'ƒ ', -- method
['function'] = ' ', -- function
parameter = ' ', -- param/arg
parameters = ' ', -- param/arg
required_parameter = ' ', -- param/arg
-- identifier = ' ', -- param/arg
associated = ' ', -- linked/related
namespace = ' ',
type = '𝐓 ',
field = ' ',
module = ' ',
flag = ' ',
import = ' ',
},
treesitter_defult = ' ',
doc_symbols = ' ',
},
})
-- load diagnostics (disabled by lsp.enabled = false)
require('navigator.diagnostics').config({})
cmp.setup({
-- snippet engine is _required_
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
window = {
-- documentation = cmp.config.window.bordered()
},
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
{ name = 'copilot' },
{ name = 'nvim_lsp_signature_help' },
{ name = 'nvim_lua' },
{ name = 'luasnip' },
{ name = 'async_path', keyword_length = 1 },
{ name = 'buffer', keyword_length = 1 },
}),
-- formatting = {
-- format = lspkind.cmp_format({
-- mode = "symbol",
-- max_width = 50,
-- -- icons for cmp sources
-- symbol_map = {
-- Copilot = "",
-- },
-- })
-- },
preselect = cmp.PreselectMode.None,
mapping = {
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.abort(),
["<CR>"] = cmp.mapping({
i = function(fallback)
if cmp.visible() and cmp.get_active_entry() then
cmp.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = false })
else
fallback()
end
end,
s = cmp.mapping.confirm({ select = true }),
c = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }),
}),
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
cmp.complete()
else
fallback() -- The fallback function sends a already mapped key. In this case, it's probably `<Tab>`.
end
end, { "i", "s" }),
["<S-Tab>"] = cmp.mapping(function()
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { "i", "s" }),
['<Down>'] = cmp.mapping.select_next_item(),
['<Up>'] = cmp.mapping.select_prev_item(),
},
})
-- link autopairs and cmp together so <cr> inserts () on Function and Method
local cmp_autopairs = require('nvim-autopairs.completion.cmp')
cmp.event:on('confirm_done', cmp_autopairs.on_confirm_done())
local lsp_signature = require('lsp_signature').setup({
hint_enable = true,
hint_inline = function() return false end,
hint_prefix = "() ",
floating_window = false,
floating_window_above_cur_line = true,
handler_opts = {
border = "rounded",
},
always_trigger = false,
})
local function toggle_lsp_signature()
require('lsp_signature').toggle_float_win()
end
local lspconfig = require('lspconfig')
local lsp_defaults = lspconfig.util.default_config
local lsp_capabilities = vim.tbl_deep_extend('force', lsp_defaults.capabilities, require('cmp_nvim_lsp').default_capabilities())
local lsp_attach = function(client, bufnr)
local opts = { buffer = bufnr }
require("navigator.dochighlight").documentHighlight(bufnr)
require("navigator.lspclient.highlight").add_highlight()
require("navigator.lspclient.highlight").config_signs()
require('navigator.lspclient.lspkind').init()
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Setup navigator for lsp client
require("navigator.lspclient.mapping").setup({
client = client,
bufnr = bufnr,
})
-- call to show code actions as floating text and gutter icon
local prompt_code_action = function()