-
Notifications
You must be signed in to change notification settings - Fork 0
/
config--nvim--init.vim.symlink
1209 lines (1036 loc) · 37 KB
/
config--nvim--init.vim.symlink
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
" init.vim
"{{{ misc options, sane defaults
set modelines=1
" Rely on 'native' Lua plugins.
let g:loaded_python_provider = 0
let g:loaded_python3_provider = 0
let g:loaded_ruby_provider = 0
let g:loaded_node_provider = 0
let g:loaded_perl_provider = 0
set lazyredraw
if exists('+termguicolors')
set termguicolors
endif
let g:matchparen_timeout = 2
let g:matchparen_insert_timeout = 2
" Always display the statusline in all windows
set laststatus=2
" Hide the default mode text (e.g. -- INSERT -- below the statusline)
set noshowmode
" Allow switching to other buffer without saving
set hidden
" Do not wrap on search in order to not miss reaching the end of matches
set nowrapscan
set tabstop=2 softtabstop=2 shiftwidth=2 expandtab shiftround
set wildignore+=*/node_modules/*,*.aux,*.d,*.o,*.pyc
set wildignorecase
" Shamelessly copied from Steve Losh's vimrc
" http://stevelosh.com/blog/2010/09/coming-home-to-vim/
" First off, some standard settings, making vim more 'sane'
set encoding=utf-8
set scrolloff=3
set autoindent
set wildmenu
set ttyfast
" Set both number and relativenumber for hybrid number
" If version is before 7.4, the last setting, i.e. relativenumber persists
set number
set relativenumber
set undofile
set noautochdir
let mapleader = ','
" fix vim's default regex handling / search behavior
set ignorecase
set smartcase
set gdefault
set incsearch
set showmatch
set hlsearch
nnoremap <leader><space> :noh<cr>
" handle lines intelligently
set wrap
" set textwidth=79
set formatoptions+=qrn1
set colorcolumn=81
" set default chars for whitespace in list chars
set list
set listchars=eol:$,tab:>-,trail:~,extends:>,precedes:<
" Allow to delete old characters in insert mode
" Also needed that latex-suite will be able to delete placeholders
set backspace=2
"" Original Source: https://stackoverflow.com/a/22676189/522251
let vimDir = expand('$HOME/.vim')
let &runtimepath.=','.vimDir
" Keep undo history across sessions by storing it in a file
if has('persistent_undo')
let myUndoDir = vimDir . '/undodir'
" Create dirs
if !isdirectory(myUndoDir)
call mkdir(myUndoDir, 'p')
endif
let &undodir = myUndoDir
set undofile
endif
set completeopt=menu,menuone,noselect
set shortmess+=c
"}}}
"{{{ plugins
"
" Specify a directory for plugins
call plug#begin(stdpath('data') . '/plugged')
" Carbon offers:
" - auto update based on file system watchers
" - intuitive addition of new files / directories
" - performance
Plug 'SidOfc/carbon.nvim'
Plug 'stevearc/oil.nvim'
Plug 'vim-scripts/linediff.vim'
Plug 'neovim/nvim-lspconfig'
Plug 'simrat39/rust-tools.nvim'
Plug 'nvim-lua/plenary.nvim'
Plug 'mfussenegger/nvim-dap'
Plug 'udalov/kotlin-vim'
"
" If you don't have nodejs and yarn
" use pre build, add 'vim-plug' to the filetype list so vim-plug can update this plugin
" see: https://github.com/iamcco/markdown-preview.nvim/issues/50
Plug 'iamcco/markdown-preview.nvim', { 'do': ':call mkdp#util#install()', 'for': 'markdown'}
Plug 'hrsh7th/nvim-cmp'
Plug 'hrsh7th/cmp-nvim-lsp'
Plug 'hrsh7th/cmp-buffer'
Plug 'hrsh7th/cmp-vsnip'
Plug 'hrsh7th/vim-vsnip'
Plug 'hrsh7th/vim-vsnip-integ'
Plug 'kaihowl/vim-indent-sentence'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-unimpaired'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-abolish'
Plug 'christoomey/vim-tmux-navigator'
Plug 'lukas-reineke/indent-blankline.nvim'
Plug 'bronson/vim-trailing-whitespace'
Plug 'godlygeek/tabular'
Plug 'justinmk/vim-sneak'
Plug 'airblade/vim-gitgutter'
Plug 'majutsushi/tagbar'
Plug 'MarcWeber/vim-addon-local-vimrc'
Plug 'sainnhe/edge'
Plug 'morhetz/gruvbox'
Plug 'folke/tokyonight.nvim'
Plug 'sonph/onehalf', { 'rtp': 'vim' }
Plug 'NLKNguyen/papercolor-theme'
Plug 'kaiuri/nvim-juliana'
Plug '1612492/github.vim'
" Fugitive browse handlers
Plug 'tommcdo/vim-fubitive' " Bitbucket
Plug 'tpope/vim-rhubarb' " Github
Plug 'tomtom/tcomment_vim'
Plug 'skywind3000/asynctasks.vim'
Plug 'skywind3000/asyncrun.vim'
Plug 'ibhagwan/fzf-lua'
Plug 'gaving/vim-textobj-argument'
" the plug#end automatically calls "filetype plugin indent on" and "syntax enable"
call plug#end()
" }}}
" {{{ early return for bootstrapping
if exists('g:first_time_startup')
finish
end
" }}}
"{{{ color
exe 'source ' . expand('~/.color/') . 'color.vim'
augroup color
autocmd!
autocmd FocusGained * exe 'source ' . expand('~/.color/') . 'color.vim'
augroup END
"}}}
" {{{indent-blankline
lua <<EOF
require("ibl").setup { }
EOF
" }}}
"{{{ vim-trailing-whitespace
let g:extra_whitespace_ignored_filetypes = ['help', 'fzf']
"}}}
"{{{ helper functions
" Sudo after the fact
cmap w!! w !sudo tee % >/dev/null
" Source https://vim.fandom.com/wiki/Search_for_visually_selected_text
vnoremap // y/\V<C-R>=escape(@",'/\')<CR><CR>
" Silent command
command! -nargs=1 Silent
\ execute ':silent '.<q-args>
\ | execute ':redraw!'
" Restore position command
command! -nargs=1 RestoreCurPos
\ let save_cursor = getpos('.')
\ | execute <q-args>
\ | call setpos('.', save_cursor)
"}}}
"{{{ fugitive
function s:diff_to_default_branch()
let defaultbranch = <sid>get_diff_file_master_merge()
exe 'Gvdiffsplit ' . defaultbranch
endfunction
" Fugitive mappings
nnoremap <leader>gs :G<cr>
nnoremap <leader>gd :Gdiff<cr>
nnoremap <leader>gm :call <sid>diff_to_default_branch()<cr>
nnoremap <leader>ge :RestoreCurPos Gedit<cr>
nnoremap <leader>gE :RestoreCurPos Gtabedit<cr>
nnoremap <leader>gb :Git blame<cr>
nnoremap <leader>gru :Git rebase @{u}<cr>
nnoremap <leader>gri :Git rebase -i @{u}<cr>
nnoremap <leader>g- :Silent Git stash -u<cr>:windo e<cr>
nnoremap <leader>g+ :Silent Git stash pop<cr>:windo e<cr>
" Git snapshot (stash everything, and apply again immediately)
nnoremap <leader>g0 :Silent ! git-stash-push ""<left>
" Git diff mapping 'push and next'
nnoremap <leader>n dp]c
" Git diff compare merge to base
nnoremap <leader>g2 :RestoreCurPos Gedit :2<cr>:Gvdiff :1<cr>
nnoremap <leader>g3 :RestoreCurPos Gedit :3<cr>:Gvdiff :1<cr>
" Fugitive git push / fetch mappings
nnoremap <leader>gp :Git! push<cr>
nnoremap <leader>gP :Git! pub<cr>
nnoremap <leader>gf :Git! fetch --verbose<cr>
augroup nolist_filtypes
autocmd!
autocmd! FileType qf,git set nolist
augroup END
" Git mapping for finding conflict markers
nnoremap <leader>c /\m\(<<<<<<< \\|=======\n\\|>>>>>>> \)<cr>
" configure vim-fubitive GBrowse handler for bitbucket
let g:fubitive_domain_pattern = 'bitbucket\.tomtomgroup\.com'
"}}}
"{{{ fzf-lua
let g:fzf_history_dir = expand('~/.local/share/fzf-history')
lua <<EOF
local separator = ' '
function commit_and_path()
local fugitive_path = vim.fn.FugitiveFind()
local is_special_git_file = vim.startswith(fugitive_path, string.format('%s/', vim.fn.FugitiveGitDir()))
if vim.o.buftype ~= '' or fugitive_path == '' or is_special_git_file then
return {"HEAD", "."}
end
local parsed = vim.fn.FugitiveParse(fugitive_path)
if parsed[2] ~= '' then -- we parsed a fugitive:// url
local commit, path = unpack(vim.fn.split(parsed[1], ':'))
if string.match(commit, "^[0-3]$") then -- special fugitive commit
-- Reset to HEAD to match fugitive's gclog function's behavior.
-- There is no obvious, public function to restore the actual commit hash from.
-- For "0", there would not be a matching commit hash (other than HEAD anyhow).
commit = "HEAD"
end
local worktree = vim.fn.FugitiveWorkTree()
local abs_path = path and worktree .. '/' .. path or worktree
return {commit or "HEAD", abs_path}
else
return {"HEAD", fugitive_path}
end
end
function make_git_log_command(commit, path, line_range)
local opts = {
'log',
'--color',
'--pretty=tformat:%C(yellow)%h%Creset' .. separator .. '%C(green)(%cr)%Creset %s %C(blue)<%an>%Creset',
commit
}
if line_range then
table.insert(opts, '--no-patch')
table.insert(opts, '-L' .. line_range.startline .. ',' .. line_range.endline .. ':' .. path)
else
table.insert(opts, '--follow')
table.insert(opts, '--summary')
table.insert(opts, '--')
table.insert(opts, path)
end
return vim.fn.FugitiveShellCommand(opts)
end
function make_git_preview_command()
local is_not_first_commit = vim.fn.FugitiveShellCommand({'rev-parse', '--quiet', '--verify', '--end-of-options', '{2}~1'})
local show_diff = vim.fn.FugitiveShellCommand({'log', '--format=fuller', '-p', '--color', '--word-diff', '{2}~1..{2}'}) .. " -- {1}"
local show_single_commit = vim.fn.FugitiveShellCommand({'show', '{2}'}) .. " -- {1}"
return "if " .. is_not_first_commit .. " > /dev/null; then " .. show_diff .. "; else " .. show_single_commit .. "; fi"
end
local sel_to_qf = function(selected, _opts)
local qf_list = {}
for _, selection in ipairs(selected) do
local file, commit, text_offset = string.match(selection, "^([^" .. separator .. "]*)" .. separator .. "(%x+)" .. separator .. "()%(")
local fugitive_path = vim.fn.FugitiveFind(commit .. ':' .. file)
table.insert(qf_list, {
filename = fugitive_path,
lnum = 1,
col = 1,
text = string.sub(selection, text_offset)
})
end
return qf_list
end
function git_edit_or_qf(cursorpos, selected, opts, is_loclist)
if #selected == 1 then
git_cmd_with_selection(cursorpos, selected, opts, 'edit')
else
git_set_qf(selected, opts)
end
end
-- TODO(kaihowl) test for vsplit, etc.
function git_cmd_with_selection(cursorpos, selected, opts, cmd)
local converted = sel_to_qf(selected, opts)
for _, selection in ipairs(converted) do
vim.cmd(cmd .. ' ' .. selection.filename)
vim.api.nvim_win_set_cursor(0, cursorpos)
end
end
function git_set_qf(selected, opts)
local converted = sel_to_qf(selected, opts)
vim.fn.setqflist({}, " ", {
nr = "$",
items = converted,
title = require('fzf-lua').get_last_query()
})
vim.cmd("copen")
end
function git_split(cursorpos, selected, opts)
git_cmd_with_selection(cursorpos, selected, opts, 'Gdiffsplit')
end
function git_vsplit(cursorpos, selected, opts)
git_cmd_with_selection(cursorpos, selected, opts, 'Gvdiffsplit')
end
function git_tab(cursorpos, selected, opts)
git_cmd_with_selection(cursorpos, selected, opts, 'tabedit')
end
-- Parse a line of the --summary from git log
-- Could be of form 'before.txt => after.txt (100%)' OR
-- the terse 'somedir/{before => after}/somefile.txt (100%)'
-- Returns the from_filename and to_filename.
function parse_renamecopy_line(line)
-- Due to missing regex alternative syntax '|', cheat with a character class
-- for "rename" vs "copy"
local prefix, left, right, suffix = string.match(line, "^ [renamecopy]* ([^{]*){?(.*) => ([^}]*)}?(.*) %(")
if left == "" and suffix == "" then -- short form, no braces matched
return prefix, right
end
return prefix .. left .. suffix, prefix .. right .. suffix
end
function shortened_path(path, n_chars)
if #path <= n_chars then
return path
end
return require('fzf-lua.path').shorten(path, 1)
end
function buffer_commits(opts)
local original_cursorpos = vim.api.nvim_win_get_cursor(0)
function curry_with_original_cursorpos(fun)
return function(...)
fun(original_cursorpos, ...)
end
end
local line_range = nil
if opts and opts.count ~= -1 then
line_range = { startline = opts.line1, endline = opts.line2 }
end
if #vim.fn.FugitiveGitDir() == 0 then
vim.notify("Not in a git directory. Aborting.", vim.log.levels.WARN)
return
end
-- for git status / non-file buffer: {}
-- for directory: {"HEAD", "/home/.../NERD_tree_1"}
local comm_path = commit_and_path()
local commit, abs_path = unpack(comm_path)
local workspace_root = vim.fn.FugitiveWorkTree()
local rel_path = require'fzf-lua'.path.relative_to(abs_path or '', workspace_root)
local parsing_state = {filename = rel_path}
local command = make_git_log_command(commit, abs_path, line_range)
require'fzf-lua'.fzf_exec(command, {
prompt = shortened_path(workspace_root, 32) .. '/',
fn_transform = function(line)
-- Possible lines, see https://github.com/git/git/blob/07330a41d66a2c9589b585a3a24ecdcf19994f19/diff.c#L6091-L6119
if vim.startswith(line, ' rename') or vim.startswith(line, ' copy') then
local from, to = parse_renamecopy_line(line)
if parsing_state.filename == to then
parsing_state.filename = from
end
return
end
if line == ''
or vim.startswith(line, ' create')
or vim.startswith(line, ' mode')
or vim.startswith(line, ' delete')
or vim.startswith(line, ' rewrite') then
-- discard unintersting summary line
return
elseif vim.startswith(line, ' ') then
-- unexpected summary line
return 'unexpected summary line: ' .. line
end
return parsing_state.filename .. separator .. line
end,
fzf_opts = {
['--delimiter'] = separator,
['--no-sort'] = "",
['--multi'] = true,
},
preview = make_git_preview_command(),
actions={
['default'] = curry_with_original_cursorpos(git_edit_or_qf),
['ctrl-s'] = curry_with_original_cursorpos(git_split),
['ctrl-v'] = curry_with_original_cursorpos(git_vsplit),
['ctrl-t'] = curry_with_original_cursorpos(git_tab),
}})
end
vim.api.nvim_create_user_command('BufferCommits',
buffer_commits,
{ range = -1 })
EOF
nnoremap <leader>gl :BufferCommits<cr>
vnoremap <leader>gl :BufferCommits<cr>
" Create dirs
if !isdirectory(g:fzf_history_dir)
call mkdir(g:fzf_history_dir, 'p')
endif
lua <<EOF
require('fzf-lua').setup{
winopts = {
preview = {
layout = 'vertical',
}
},
fzf_opts = {
-- Remove default reverse layout to get prompt at bottom
['--layout'] = false,
['--history'] = vim.g.fzf_history_dir .. '/' .. 'history',
['--keep-right'] = '',
},
grep= {
rg_opts = '--hidden --column --line-number --no-heading --color=always --smart-case --max-columns=512',
},
files = {
rg_opts = '--hidden --files --color=never --glob ""',
},
buffers = {
},
git = {
branches = {
cmd = "git branch --color --sort=-committerdate",
cwd = "%:p:h"
}
},
lsp = {
jump_to_single_result = true,
},
previewers = {
builtin = {
-- Show full file name and not just tail
title_fnamemodify = function(s) return s end,
},
},
}
EOF
nnoremap <leader>s :FzfLua files<cr>
nnoremap <leader>d :FzfLua buffers<cr>
nnoremap <leader>f<space> :FzfLua<space>
nnoremap <leader>fr :FzfLua resume<cr>
nnoremap <leader>fc :FzfLua changes<cr>
nnoremap <leader>fj :FzfLua jumps<cr>
nnoremap <leader>fb :FzfLua git_branches<cr>
nnoremap <leader>R :FzfLua live_grep<cr>
" Set no_esc=true to pass \b as boundary markers and not backspace. A cword is
" unlikely to require escaping.
nnoremap <leader>rr :lua require('fzf-lua').grep({search = "\\b"..vim.fn.expand('<cword>').."\\b", no_esc = true})<cr>
vnoremap <leader>rr :lua require('fzf-lua').grep_visual({})<cr>
"}}}
"{{{ mode escaping
" Normal mode commands
" easier escaping
inoremap jj <ESC>
" join two lines
inoremap JJ <esc>Ji
" Exit terminal mode with the same shortcut as normal mode
tnoremap jj <C-\><C-n>
"}}}
"{{{ python
" python pep8 compliance
augroup python_ft
autocmd!
autocmd BufEnter *.py set sw=4 ts=4 sta et fo=croql
augroup END
"}}}
"{{{ asynctasks / asyncrun
" Call asynctask with pwd: for submodules with individual task files, only the
" task file from the current working directory should count.
function! SimpleAsyncTaskComplete(Arg, Ignore1, Ignore2)
return join(map(asynctasks#list('.'), 'v:val["name"]'), "\n")
endfunction
function! SimpleAsyncTaskLast()
if g:asynctasks_last ==# ''
echoerr 'no task history'
return -1
endif
call asynctasks#start('', g:asynctasks_last, '.')
endfunction
function! SimpleAsyncTask(taskname)
let g:asynctasks_last = a:taskname
call asynctasks#start('', a:taskname, '.')
endfunction
function! SimpleAsyncStop()
AsyncStop
let original_splitright = &splitright
vert copen
wincmd =
let &splitright = original_splitright
call cursor(1,1)
call search('error:')
call feedkeys("\<cr>", 'tx')
endfunction
" TODO(kaihowl) this loses the templating functionality
function! SimpleAsyncTaskEdit()
edit .tasks
endfunction
command! -bang -nargs=* -range=0 -complete=custom,SimpleAsyncTaskComplete SimpleAsyncTask
\ call SimpleAsyncTask(<q-args>)
command! -bang -nargs=* -range=0 SimpleAsyncTaskLast
\ call SimpleAsyncTaskLast()
command! -bang -nargs=0 -range=0 SimpleAsyncTaskEdit
\ call SimpleAsyncTaskEdit()
command! -bang -nargs=0 -range=0 SimpleAsyncStop
\ call SimpleAsyncStop()
nnoremap <leader>mm :SimpleAsyncTaskLast<cr>
nnoremap <leader>mx :SimpleAsyncStop<cr>
nnoremap <leader>M :SimpleAsyncTaskEdit<cr>
nnoremap <leader>m<space> :SimpleAsyncTask<space>
let g:asynctasks_term_pos = 'tab' " Run terminal tasks in new, internal tab window
let g:asyncrun_auto = 'make'
let g:asynctasks_confirm = 0 " Do not confirm filename when edit task config file
let g:asynctasks_template = {}
let g:asynctasks_template.cpp = [
\ '[file-build-run]',
\ 'command=clang++ -std=c++17 $(VIM_FILEPATH) -o $(VIM_FILEDIR)/$(VIM_FILENOEXT) && $(VIM_FILEDIR)/$(VIM_FILENOEXT)',
\ ]
augroup asynctasks
autocmd!
autocmd User AsyncRunStart set splitright | vert copen | wincmd = | wincmd p | set nosplitright
augroup END
augroup CleanUpMatchAll
autocmd!
" We do not want the local errorformat to drop all non matched lines
" Otherwise, asyncrun will not show the output.
" Fixes #367
autocmd FileType * setlocal errorformat-=%-G%.%#
augroup END
"}}}
"{{{ latex
" For latex file run latex instead of makefile
augroup latex_ft
autocmd!
autocmd FileType tex nnoremap <buffer> <leader>mm :silent! call Tex_RunLaTeX()<CR>
augroup END
" Make sure latex-suite is invoked for plaintex files
let g:tex_flavor='latex'
" Configure pdf format for latex-suite
let g:Tex_DefaultTargetFormat = 'pdf'
let g:Tex_CompileRule_pdf = 'pdflatex -synctex=1 --interaction=nonstopmode $*'
let g:Tex_ViewRule_pdf = 'Skim'
" Set more sensible ignore warning level for latex-suite
" ensures that missing numbers, undefined references, and citations are shown
let g:Tex_IgnoreLevel = 4
" Change default alt mappings for latex-suite to mac friendly ones
imap <leader>lb <Plug>Tex_MathBF
imap <leader>lc <Plug>Tex_MathCal
imap <leader>ll <Plug>Tex_LeftRight
imap <leader>li <Plug>Tex_InsertItemOnThisLine
" Blindly robbed from Janus vim.rc
" https://github.com/rdeits/janus/blob/master/vimrc
" Calculate the number of screen lines needed to display a file with folds at
" the given fold_level. This is used to set the initial fold level of a file
" in order to display the entire file on screen if possible without closing
" any unnecessary folds.
function! ScreenLines(fold_level)
let line_num = 1
let screen_lines = 0
let prev_fold_level = 0
let cur_fold_level = 0
let buf_length = line('$')
while line_num <= buf_length
let fold_expr = foldlevel(line_num)
let prev_fold_level = cur_fold_level
let cur_fold_level = fold_expr
if (cur_fold_level <= a:fold_level) || ((cur_fold_level != prev_fold_level) && (prev_fold_level <= a:fold_level))
let screen_lines = screen_lines + 1
endif
let line_num = line_num+1
endwhile
return screen_lines
endfunction
" Increase the fold level until the entire file will fit on the screen or
" foldlevel reaches 10, whichever comes first.
function! FoldToScreen()
let ndx = 0
set foldlevel=0
while ndx < 10
let ndx = ndx + 1
if ScreenLines(ndx) > &lines
break
endif
set foldlevel+=1
endwhile
endfunction
augroup tex_fold_function
autocmd!
autocmd BufWinEnter *.tex call FoldToScreen()
augroup END
" Function to break lines in tex files on period(.) and wrap to colorcolumn
" This makes version control for latex files easier since git is line-based
command! -range LineBreakTexSource :silent! <line1>,<line2>s/\. /.\r/g | :<line1>,<line2>normal gw | :noh<cr>
" Comment out, if you need to debug latex-suite
"let g:Tex_Debug=1
"let g:Tex_DebugLog="texdebug.log"
"}}}
"{{{ spellchecking
" enable spellchecking for git commits
augroup spellchecking
autocmd!
autocmd FileType gitcommit setlocal spell
autocmd FileType gitcommit setlocal textwidth=71 colorcolumn=+1
" and for markdown files
autocmd FileType markdown setlocal spell
" and for tex files
autocmd FileType tex setlocal spell
autocmd FileType tex syntax spell toplevel
augroup END
"}}}
"{{{ vim-indent-sentence
" For paragraph, restore position using register T
nnoremap <leader>ip i//CURSOR//<esc>vip :call g:IndentSentence()<cr>:%s/\/\/CURSOR\/\///<cr>
vnoremap <leader>is :call g:IndentSentence()<cr>
"}}}
"{{{ gitgutter
" gitgutter configuration
" explicitly set hunk navigation commands
nmap [h <Plug>(GitGutterPrevHunk)
nmap ]h <Plug>(GitGutterNextHunk)
"}}}
"{{{ tagbar
" open tagbar (and focus) (or jump to if open)
nnoremap <leader>o :TagbarOpen fj<cr>
" show line numbers in tagbar
let g:tagbar_show_linenumbers=-1
"}}}
"{{{ filetypes
" Add yaml file type for salt sls files
augroup salt_ft
autocmd!
autocmd BufEnter *.sls set ft=yaml
augroup END
augroup groovy_filetype
autocmd!
autocmd FileType groovy set sw=4 ts=4 sta et fo=croql
augroup END
augroup markdown
autocmd!
autocmd FileType markdown nmap <leader>P <Plug>MarkdownPreview
augroup END
setglobal commentstring=//\ %s
augroup cpp_comments
autocmd!
autocmd FileType cpp setlocal commentstring=//\ %s
augroup END
"}}}
"{{{ conventional-commits
" https://www.reddit.com/r/vim/comments/dj37wt/plugin_for_conventional_commits/
augroup commit
autocmd!
autocmd FileType gitcommit nnoremap <buffer> i i<C-r>=<sid>commit_type()<CR>
autocmd FileType gitcommit inoreabbrev <buffer> BB BREAKING CHANGE:
augroup END
fun! s:commit_type()
" Redraw added to make neovim/neovim#14565 a dormant fault
" Otherwise, opening the commit message buffer and entering insert mode in
" quick succession will lead to a segfault.
redraw
call complete(1, ['fix: ', 'feat: ', 'refactor: ', 'docs: ', 'test: ', 'ci: ', 'chore: ', 'perf: '])
nunmap <buffer> i
return ''
endfun
"}}}
"{{{ diffopt
" Generally enable the second stage diff added in nvim 0.9
set diffopt+=linematch:60
" https://github.com/tommcdo/vimfiles/blob/master/config/diffopt.vim
" Provide a function to toggle iwhite (ignore whitespace)
function! s:toggle_iwhite(opt)
if a:opt == -1 || (a:opt == 0 && &diffopt =~# 'iwhite')
echo ':set diffopt-=iwhite'
set diffopt-=iwhite
elseif a:opt == 1 || (a:opt == 0 && &diffopt !~# 'iwhite')
echo ':set diffopt+=iwhite'
set diffopt+=iwhite
endif
endfunction
" Add mappings for toggling and setting iwhite (in the style of unimpaired.vim)
nnoremap coD :call <SID>toggle_iwhite(0)<CR>
nnoremap [oD :call <SID>toggle_iwhite(1)<CR>
nnoremap ]oD :call <SID>toggle_iwhite(-1)<CR>
"}}}
"{{{ pull request handling
function! Get_default_branch() abort
" Source: https://stackoverflow.com/questions/28666357/git-how-to-get-default-branch
" let defaultbranch = execute("Git symbolic-ref refs/remotes/origin/HEAD")
let defaultbranch = split(execute('Git rev-parse --abbrev-ref origin/HEAD'), "\n")[0]
let output = execute('Git rev-parse --abbrev-ref origin/HEAD')
if output =~? '.*fatal: .*'
echohl WarningMsg
echom 'Could not detect default branch, using origin/master.'
echom 'Maybe .git/refs/remotes/origin/HEAD is missing as this repo has not been cloned?'
echom 'Set symbolic ref manually: git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master.'
echom 'Using default origin/master.'
let defaultbranch = 'origin/master'
echohl None
else
let defaultbranch = split(output, "\n")[0]
endif
return defaultbranch
endfunction
function! s:get_diff_file_master_merge() abort
let defaultbranch = Get_default_branch()
let common_revision = split(execute('Git merge-base ' . defaultbranch . ' HEAD'), "\n")[0]
return common_revision
endfunction
command! -nargs=1 DiffRev call s:get_diff_files(<q-args>)
nnoremap <leader>gD :call <SID>view_merge_request()<cr>
command! DiffHistory call s:view_merge_request()
" Source / Inspiration
" https://github.com/tpope/vim-fugitive/issues/132#issuecomment-649516204
function! s:view_merge_request() abort
let revision = <sid>get_diff_file_master_merge()
execute 'Git difftool --numstat ' . revision . '..HEAD --find-renames=50\%'
if len(getqflist()) > 0
call s:diff_current_quickfix_entry()
endif
" Bind <CR> for current quickfix window to properly set up diff split layout after selecting an item
" There's probably a better way to map this without changing the window
copen
nnoremap <buffer> <CR> <CR><BAR>:call <sid>diff_current_quickfix_entry()<CR>
wincmd p
endfunction
function s:diff_current_quickfix_entry()
" Cleanup windows
for window in getwininfo()
if window.winnr !=? winnr() && bufname(window.bufnr) =~? '^fugitive:'
exe 'bdelete' window.bufnr
endif
endfor
cc
call s:add_mappings()
let qf = getqflist({'context': 0, 'idx': 0})
if get(qf, 'idx') && type(get(qf, 'context')) == type({}) && type(get(qf.context, 'items')) == type([])
let diff = get(qf.context.items[qf.idx - 1], 'diff', [])
for i in reverse(range(len(diff)))
exe (i ? 'rightbelow' : 'leftabove') 'vert diffsplit' fnameescape(diff[i].filename)
call s:add_mappings()
endfor
endif
endfunction
function! s:add_mappings()
nnoremap <buffer>]q :cnext <BAR> :call <sid>diff_current_quickfix_entry()<CR>
nnoremap <buffer>[q :cprevious <BAR> :call <sid>diff_current_quickfix_entry()<CR>
" Reset quickfix height. Sometimes it messes up after selecting another item
11copen
wincmd p
endfunction
"}}}
"{{{status line
function! FormattedAsyncRun()
let colors = { 'running': 'DiffText',
\'success': 'DiffAdd',
\'failure': 'DiffDelete'}
if g:asyncrun_status ==? ''
return ''
endif
if g:asynctasks_last ==? ''
return ''
endif
return '%#' . colors[g:asyncrun_status] . '# %1.15{g:asynctasks_last} %*'
endfunction
" source: https://shapeshed.com/vim-statuslines
set statusline=
set statusline+=\ %f
set statusline+=\ %m
set statusline+=%=
set statusline+=%#PmenuSel#
set statusline+=\ %y
set statusline+=\ %{&fileencoding?&fileencoding:&encoding}
set statusline+=\[%{&fileformat}\]
set statusline+=\ %p%%
set statusline+=\ %l:%c
set statusline+=\
set statusline+=\ %{%FormattedAsyncRun()%}
"}}}
"{{{ Carbon
lua <<EOF
-- Ensure that out-of-pwd directories can still reveal their file correctly.
function OpenParent()
local parent = vim.fn.expand("%:p:h")
local cwd = vim.fn.getcwd()
local root = cwd
if not (parent == '') and not vim.startswith(parent .. '/', cwd) then
root = parent
end
local fargs = {}
fargs[1] = root
require("carbon").explore({fargs=fargs, bang=true})
end
require("carbon").setup({auto_open=false})
vim.keymap.set("n", "-", OpenParent, { desc = "Open parent directory" })
EOF
"}}}
"{{{ Todo functionality
function! GetTodoUserName()
return trim(system('id -un'))
endfunction
function! s:SearchForToDo()
lua require('fzf-lua').grep({search = 'todo(' .. vim.fn.GetTodoUserName()})
endfunction
function! s:GenerateToDo()
let user = GetTodoUserName()
return 'TODO(' . user . ')'
endfunction
inoremap <expr> <leader>t <sid>GenerateToDo()
nnoremap <leader>t :call <sid>SearchForToDo()<cr>
"}}}
"{{{vim-addon-local-vimrc
let g:local_vimrc = {'names':['.vimrc', '.nvimrc'],'hash_fun':'LVRHashOfFile'}
"}}}
"{{{ lsp + vsnip config
lua <<EOF
local configs = require('lspconfig')
-- This is grabbing into internals of lspconfig. If this breaks, this is on me.
local util = require 'lspconfig/util'
local root_pattern = util.root_pattern('compile_commands.json')
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
-- Enable completion triggered by <c-x><c-o>
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd> lua require("fzf-lua").lsp_declarations()<cr>', opts)
buf_set_keymap('n', 'gd', '<cmd> lua require("fzf-lua").lsp_definitions()<cr>', opts)
buf_set_keymap('n', '<c-]>', '<cmd> lua require("fzf-lua").lsp_definitions()<cr>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd> lua require("fzf-lua").lsp_implementations()<cr>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<leader>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<leader>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<leader>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
buf_set_keymap('n', '<leader>D', '<cmd> lua require("fzf-lua").lsp_typedefs()<cr>', opts)
buf_set_keymap('n', '<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<leader>ca', '<cmd> lua require("fzf-lua").lsp_code_actions()<cr>', opts)
buf_set_keymap('n', 'gr', '<cmd> lua require("fzf-lua").lsp_references()<cr>', opts)
buf_set_keymap('n', '<leader>e', '<cmd>lua vim.diagnostic.open_float()<CR>', opts)
buf_set_keymap('n', '[d', '<cmd>lua vim.diagnostic.goto_prev()<CR>', opts)
buf_set_keymap('n', ']d', '<cmd>lua vim.diagnostic.goto_next()<CR>', opts)
buf_set_keymap('n', '<leader>q', '<cmd> lua require("fzf-lua").diagnostics_document()<cr>', opts)
buf_set_keymap('n', '<leader>Q', '<cmd> lua require("fzf-lua").diagnostics_workspace()<cr>', opts)
buf_set_keymap('n', '<leader>fd', '<cmd> lua require("fzf-lua").lsp_document_symbols()<cr>', opts)
buf_set_keymap('n', '<leader>fD', '<cmd> lua require("fzf-lua").lsp_workspace_symbols()<cr>', opts)
end
-- The nvim-cmp almost supports LSP's capabilities so You should advertise it to LSP servers..
local capabilities = require('cmp_nvim_lsp').default_capabilities()
-- Get compile_commands.json based on current working directory in case there are multiple available, e.g., conan workspaces with the workspace vs the single package build
-- Supply an invalid dir to clangd in case that no compile_commands.json can be found in the current working dir. This restores the original behavior.
configs.clangd.setup{root_dir=function(fname)
return root_pattern(vim.loop.cwd()) or util.path.dirname(fname)
end,