-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path.vimrc
1615 lines (1450 loc) · 52.2 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
""" Options {{{1
silent! set confirm
silent! set notimeout
silent! set hidden
silent! set foldlevelstart=99
silent! set colorcolumn=+1
silent! set helpheight=10
silent! set laststatus=2
silent! set mouse=a
silent! set number
silent! set pumheight=16
silent! set ruler
silent! set showcmd
silent! set scrolloff=4
silent! set sidescrolloff=8
silent! set sidescroll=1
silent! set showtabline=1
silent! set splitright
silent! set splitbelow
silent! set nostartofline
silent! set noswapfile
silent! set undofile
silent! set updatetime=10
silent! set nowrap
silent! set linebreak
silent! set breakindent
silent! set smoothscroll
silent! set ignorecase
silent! set smartcase
silent! set completeopt=menuone
silent! set wildmenu
silent! set wildoptions+=fuzzy,pum
silent! set hlsearch
silent! set incsearch
silent! set ttimeout
silent! set ttimeoutlen=0
silent! set autoindent
silent! set shortmess-=S
silent! set sessionoptions+=globals
silent! set viminfo=!,'100,<50,s10,h
silent! set diffopt+=algorithm:histogram,indent-heuristic
silent! set clipboard^=unnamedplus
silent! set formatoptions+=nor
silent! set jumpoptions=stack
" Enable 'exrc' only when 'secure' is working
if exists('+secure')
silent! set secure
silent! set exrc
endif
" Spell check options
silent! set spellcapcheck=''
silent! set spelllang=en_us
silent! set spelloptions=camel
silent! set spellsuggest=best,9
" Focus events
silent! let &t_fe = "\<Esc>[?1004h"
silent! let &t_fd = "\<Esc>[?1004l"
" Set editor to vim
silent! let $EDITOR = 'vim'
silent! let $VISUAL = 'vim'
" Align columns in quickfix window
silent! set quickfixtextfunc=Qftf
" param: info dict
" return: string[]
function! Qftf(info) abort
let qflist = a:info['quickfix']
\ ? getqflist(#{id: a:info.id, items: 0}).items
\ : getloclist(a:info.winid, #{id: a:info.id, items: 0}).items
if len(qflist) == 0
return []
endif
let fname_width = 0
let lnum_width = 0
let col_width = 0
let type_width = 0
let nr_width = 0
let max_width = &columns / 2
let fname_str_cache = []
let lnum_str_cache = []
let col_str_cache = []
let type_str_cache = []
let nr_str_cache = []
let fname_width_cache = []
let lnum_width_cache = []
let col_width_cache = []
let type_width_cache = []
let nr_width_cache = []
for item in qflist
let fname = get(item, 'module')
\ ? item.module : (get(item, 'filename')
\ ? item.filename : fnamemodify(bufname(item.bufnr), ':~:.'))
let lnum = item.lnum == item.end_lnum || item.end_lnum == 0
\ ? item.lnum
\ : item.lnum . '-' . item.end_lnum
let col = item.col == item.end_col
\ ? item.col
\ : item.col . '-' . item.end_col
let type = trim(item.type) != '' ? ' ' .. trim(item.type) : ''
let nr = item.nr > 0 ? ' ' .. item.nr : ''
let fname_cur_width = strdisplaywidth(fname)
let lnum_cur_width = strdisplaywidth(lnum)
let col_cur_width = strdisplaywidth(col)
let type_cur_width = strdisplaywidth(type)
let nr_cur_width = strdisplaywidth(nr)
let fname_width = min([max_width, max([fname_width, fname_cur_width])])
let lnum_width = min([max_width, max([lnum_width, lnum_cur_width])])
let col_width = min([max_width, max([col_width, col_cur_width])])
let type_width = min([max_width, max([type_width, type_cur_width])])
let nr_width = min([max_width, max([nr_width, nr_cur_width])])
call add(fname_str_cache, fname)
call add(lnum_str_cache, lnum)
call add(col_str_cache, col)
call add(type_str_cache, type)
call add(nr_str_cache, nr)
call add(fname_width_cache, fname_cur_width)
call add(lnum_width_cache, lnum_cur_width)
call add(col_width_cache, col_cur_width)
call add(type_width_cache, type_cur_width)
call add(nr_width_cache, nr_cur_width)
endfor
let result = []
for idx in range(len(qflist))
let item = qflist[idx]
if !item.valid
continue
endif
let fname = fname_str_cache[idx]
let fname_cur_width = fname_width_cache[idx]
if item.lnum == 0 && item.col == 0 && item.text == ''
call add(result, fname)
continue
endif
let lnum = lnum_str_cache[idx]
let col = col_str_cache[idx]
let type = type_str_cache[idx]
let nr = nr_str_cache[idx]
let lnum_cur_width = lnum_width_cache[idx]
let col_cur_width = col_width_cache[idx]
let type_cur_width = type_width_cache[idx]
let nr_cur_width = nr_width_cache[idx]
call add(result, printf('%s|%s:%s%s%s| %s',
\ fname . repeat(' ', fname_width - fname_cur_width),
\ repeat(' ', lnum_width - lnum_cur_width) . lnum,
\ col . repeat(' ', col_width - col_cur_width),
\ type . repeat(' ', type_width - type_cur_width),
\ nr . repeat(' ', nr_width - nr_cur_width),
\ item.text))
endfor
return result
endfunction
silent! set backup
silent! set backupdir=~/.vimbackup
let s:backupdir = expand('~/.vimbackup')
if !isdirectory(s:backupdir)
if filereadable(s:backupdir)
call delete(s:backupdir)
endif
call mkdir(s:backupdir)
endif
silent! set fillchars=fold:·,diff:╱
syntax on
filetype plugin indent on
" }}}1
""" Abbreviations {{{1
" Set abbreviation that only when the trigger is at the position of a command
" param: trig string
" param: command string
" param: a:1 flags string? '<expr>'/'<buffer>',etc
function! s:command_abbrev(trig, command, ...) abort
if exists('*getcmdcompltype')
exe printf(
\ 'cnoreabbrev %s %s getcmdcompltype() ==# "command" ? "%s" : "%s"',
\ '<expr>' . substitute(get(a:, 1, ''), '<expr>', '', ''),
\ a:trig,
\ escape(a:command, '"\'),
\ escape(a:trig, '"\'))
endif
endfunction
" Set keymap that only when the trigger is at the position of a command
" param: trig string
" param: command string
" param: a:1 flags string? '<expr>'/'<buffer>',etc
function! s:command_map(trig, command, ...) abort
if exists('*getcmdcompltype')
exe printf(
\ 'cnoremap %s %s getcmdcompltype() ==# "command" ? "%s" : "%s"',
\ '<expr>' . substitute(get(a:, 1, ''), '<expr>', '', ''),
\ a:trig,
\ escape(a:command, '"\'),
\ escape(a:trig, '"\'))
endif
endfunction
call s:command_map(':', 'lua ')
call s:command_abbrev('tt', 'tab ter')
call s:command_abbrev('bt', 'bot ter')
call s:command_abbrev('ht', 'hor ter')
call s:command_abbrev('vt', 'vert ter')
call s:command_abbrev('rm', '!rm')
call s:command_abbrev('mv', '!mv')
call s:command_abbrev('git', '!git')
call s:command_abbrev('tree', '!tree')
call s:command_abbrev('mkdir', '!mkdir')
call s:command_abbrev('touch', '!touch')
call s:command_abbrev('chmod', '!chmod')
abbrev ture true
abbrev Ture True
abbrev flase false
abbrev fasle false
abbrev Flase False
abbrev Fasle False
runtime ftplugin/man.vim
call s:command_abbrev('man', 'Man')
" }}}
""" Autocmds {{{1
" Check if an event or a list of events are supported
" param: events string|string[] event or list of events
" return: 0/1
function! s:supportevents(events) abort
if type(a:events) == v:t_string
return exists('##' . a:events)
endif
if type(a:events) == v:t_list
for event in a:events
if !exists('##' . event)
return 0
endif
endfor
return 1
endif
return 0
endfunction
" Autosave on focus lost, window/buf leave, etc. {{{2
if s:supportevents(['BufLeave', 'WinLeave', 'FocusLost'])
function! s:auto_save(buf, file) abort
if getbufvar(a:buf, '&bt', '') ==# ''
silent! update
endif
endfunction
augroup AutoSave
au!
if has('patch-8.1113')
au BufLeave,WinLeave,FocusLost * ++nested
\ :call s:auto_save(expand('<abuf>'), expand('<afile>'))
else
au BufLeave,WinLeave,FocusLost *
\ :call s:auto_save(expand('<abuf>'), expand('<afile>'))
endif
augroup END
endif
" }}}2
" Open quickfix/location list automatically when set with commands {{{2
if s:supportevents('QuickFixCmdPost') && exists('*timer_start')
function! s:defer_open_qflist(type) abort
if expand(a:type) =~# '^l'
call timer_start(0, {-> execute('bel lwindow')})
else
call timer_start(0, {-> execute('bot cwindow')})
endif
endfunction
augroup QuickFixAutoOpen
au!
au QuickFixCmdPost * if len(getqflist()) > 1 |
\ call s:defer_open_qflist(expand('<amatch>')) |
\ endif
augroup END
endif
" }}} 2
" Make all widnows the same height/width on vim resized {{{2
if s:supportevents('VimResized')
augroup EqualWinSize
au!
au VimResized * wincmd =
augroup END
endif
" }}}
" Restore last position when opening a file {{{2
if s:supportevents('BufReadPost')
augroup LastPosJmp
au!
au BufReadPost * if &ft !=# 'gitcommit' && &ft !=# 'gitrebase' |
\ exe 'silent! normal! g`"zvzz' |
\ endif
augroup END
endif
" }}}2
" Jump to last accessed window on closing the current one {{{2
if s:supportevents('WinClosed')
augroup WinCloseJmp
au!
if has('patch-8.1113')
au WinClosed * ++nested if expand('<amatch>') == win_getid() |
\ wincmd p |
\ endif
else
au WinClosed * if expand('<amatch>') == win_getid() |
\ wincmd p |
\ endif
endif
augroup END
endif
" }}}2
" Automatically setting cwd to the root directory {{{2
if s:supportevents([
\ 'BufReadPost',
\ 'BufWinEnter',
\ 'WinEnter',
\ 'FileChangedShellPost'
\ ])
" Compute project directory for given path.
" param: fpath string
" param: a:1 patterns string[]? root patterns
" return: string returns path of project root directory if found,
" else returns empty string
function! s:proj_dir(fpath, ...) abort
if a:fpath == ''
return ''
endif
let patterns = get(a:, 1, [
\ '.git',
\ '.svn',
\ '.bzr',
\ '.hg',
\ '.project',
\ '.pro',
\ '.sln',
\ '.vcxproj',
\ 'Makefile',
\ 'makefile',
\ 'MAKEFILE',
\ 'venv',
\ 'env',
\ '.venv',
\ '.env',
\ '.gitignore',
\ '.editorconfig'])
let dirpath = fnamemodify(a:fpath, ':p:h') . ';'
for pattern in patterns
if pattern =~# '/$'
let target_path = finddir(pattern, dirpath)
if target_path !=# ''
return fnamemodify(target_path, ':p:h:h')
endif
else
let target_path = findfile(pattern, dirpath)
if target_path !=# ''
return fnamemodify(target_path, ':p:h')
endif
endif
endfor
return ''
endfunction
" Change current working directory to project root directory.
" param: fpath string path to current file
function! s:autocwd(fpath) abort
let fpath = fnamemodify(a:fpath, ':p')
if fpath ==# '' || !isdirectory(fpath) && !filereadable(fpath)
return
endif
let proj_dir = s:proj_dir(fpath)
if proj_dir !=# ''
exe 'silent! lcd ' . proj_dir
return
endif
let dirname = fnamemodify(fpath, ':p:h')
if isdirectory(dirname)
exe 'silent! lcd ' . dirname
endif
endfunction
augroup AutoCwd
au!
autocmd BufEnter * ++nested
\ if &bt == '' && &ma | call <SID>autocwd(expand('<afile>')) | endif
augroup END
endif
" }}}2
" Colorscheme persistence over restarts {{{2
"
" Restore and switch background from viminfo file,
" for this autocmd to work properly, 'viminfo' option must contain '!'
if ($COLORTERM ==# 'truecolor' || has('gui_running'))
\ && s:supportevents(['VimEnter', 'OptionSet', 'ColorScheme'])
" Restore &background and colorscheme from viminfo file
function! s:theme_restore() abort
let BACKGROUND = get(g:, 'BACKGROUND', '')
if BACKGROUND !=# '' && BACKGROUND !=# &background
let &background=BACKGROUND
endif
let colors_name = get(g:, 'colors_name', '')
let COLORSNAME = get(g:, 'COLORSNAME', '')
if colors_name ==# '' || COLORSNAME != colors_name
exe 'silent! colorscheme ' . COLORSNAME
call s:theme_fix_hlspell()
endif
endfunction
" Save current &background and colorscheme to global variables
function! s:theme_save() abort
let g:BACKGROUND = &background
let g:COLORSNAME = get(g:, 'colors_name', '')
silent! wviminfo
endfunction
" Override hl-SpellBad, hl-SpellCap, hl-SpellRare, and hl-SpellLocalA
function! s:theme_fix_hlspell() abort
hi clear SpellBad
hi! SpellBad term=underline gui=underline
hi! link SpellCap SpellBad
hi! link SpellRare SpellBad
hi! link SpellLocal SpellBad
endfunction
augroup ThemeSwitch
au!
au VimEnter * :call s:theme_restore()
au ColorScheme * :call s:theme_save()
au ColorScheme * :call s:theme_fix_hlspell()
augroup END
endif
" }}}2
" Clear strange escape sequence shown when using alt keys to navigate away {{{2
" from tmux panes running vim
if s:supportevents('FocusLost')
augroup FocusLostClearScreen
au!
au FocusLost * :silent! redraw!
augroup END
endif
if s:supportevents(['CursorMoved', 'ModeChanged'])
augroup FixVirtualEditCursorPos
au!
" Record cursor position in visual mode if virtualedit is set and
" contains 'all' or 'block'
au CursorMoved * if &ve =~# 'all' |
\ let w:ve_cursor = getcurpos() |
\ endif
" Keep cursor position after finishing visual mode replacement when virtual
" edit is enabled
au ModeChanged [vV\x16]*:n if &ve =~# 'all' && exists('w:ve_cursor') |
\ call cursor([w:ve_cursor[1], w:ve_cursor[2] + w:ve_cursor[3]]) |
\ endif
augroup END
endif
" }}}2
" Consistent &iskeyword in Ex command-line {{{2
if s:supportevents(['CmdlineEnter', 'CmdlineLeave'])
augroup FixCmdLineIskeyword
au!
au CmdlineEnter [:>/?=@] let g:_isk_lisp_buf = str2nr(expand('<abuf>')) |
\ let g:_isk_save = getbufvar(g:_isk_lisp_buf, '&isk', '') |
\ let g:_lisp_save = getbufvar(g:_isk_lisp_buf, '&lisp', 0) |
\ setlocal isk& lisp&
au CmdlineLeave [:>/?=@] if
\ exists('g:_isk_lisp_buf') && bufexists(g:_isk_lisp_buf) |
\ call setbufvar(g:_isk_lisp_buf, '&isk', g:_isk_save) |
\ call setbufvar(g:_isk_lisp_buf, '&lisp', g:_lisp_save) |
\ unlet g:_isk_save g:_lisp_save g:_isk_lisp_buf |
\ endif
endif
" }}}2
" Close empty windows after loading session {{{2
if s:supportevents('SessionLoadPost')
function! s:clear_invalid_buffers()
for tab in gettabinfo()
let wins = filter(tabpagewinnr(tab.tabnr, '$')->range(), 'win_gettype(win_getid(v:val, tab.tabnr)) == ""')
if len(wins) <= 1
continue
endif
for win in wins
let winid = win_getid(win, tab.tabnr)
let buf = winbufnr(winid)
let line_count = line('$', winid)
if (line_count == 0 ||
\ line_count == 1 && getbufline(buf, 1)[0] == '') &&
\ !filereadable(bufname(buf))
call win_execute(winid, 'close')
endif
endfor
endfor
endfunction
augroup SessionCloseEmptyWins
autocmd!
autocmd SessionLoadPost * call s:clear_invalid_buffers()
augroup END
endif
" }}}2
" }}}1
""" Keymaps {{{1
" Leader & localleader keys {{{2
let g:mapleader = ' '
let g:maplocalleader = ' '
" }}}2
" Past with correct indentation in insert mode {{{2
inoremap <C-r> <C-r><C-p>
" }}}
" Delete selection in select mode {{{2
snoremap <BS> <C-o>s
snoremap <C-h> <C-o>s
" }}}
" Moving up & down in visual line {{{2
nnoremap <expr> j v:count ? "j" : "gj"
xnoremap <expr> j v:count ? "j" : "gj"
nnoremap <expr> k v:count ? "k" : "gk"
xnoremap <expr> k v:count ? "k" : "gk"
nnoremap <expr> <Down> v:count ? "<Down>" : "g<Down>"
xnoremap <expr> <Down> v:count ? "<Down>" : "g<Down>"
nnoremap <expr> <Up> v:count ? "<Up>" : "g<Up>"
xnoremap <expr> <Up> v:count ? "<Up>" : "g<Up>"
inoremap <Down> <C-o>g<Down>
inoremap <Up> <C-o>g<Up>
" }}}2
" Switching buffers {{{2
nnoremap <silent> ]b :exec v:count1 . 'bn'<CR>
nnoremap <silent> [b :exec v:count1 . 'bp'<CR>
" }}}
" Switching between quickfix/location list items {{{2
nnoremap <silent> [q :exec v:count1 . 'cp'<CR>
nnoremap <silent> [l :exec v:count1 . 'lp'<CR>
nnoremap <silent> ]p :exec v:count1 . 'lne'<CR>
nnoremap <silent> ]l :exec v:count1 . 'cne'<CR>
nnoremap <silent> [Q :exec v:count1 . 'cfir'<CR>
nnoremap <silent> [L :exec v:count1 . 'lfir'<CR>
nnoremap <silent> ]Q :exec (v:count ? v:count : '') . 'cla'<CR>
nnoremap <silent> ]L :exec (v:count ? v:count : '') . 'lla'<CR>
" }}}
" Tabpages {{{2
" param: tab_action tab switch command 'tabnext'|'tabprev'
" param: a:1 default_count number? default to v:count
" return: 0
function! TabSwitch(tab_action, ...) abort
let cnt = get(a:, 1, v:count)
let num_tabs = tabpagenr('$')
if num_tabs >= cnt
exe printf('silent! %s %s', a:tab_action, cnt == 0 ? '' : string(cnt))
return
endif
tablast
for _ in range(cnt - num_tabs)
tabnew
endfor
endfunction
nnoremap <silent> gt :<C-u>call TabSwitch('tabnext')<CR>
nnoremap <silent> gT :<C-u>call TabSwitch('tabprev')<CR>
xnoremap <silent> gt :<C-u>call TabSwitch('tabnext')<CR>
xnoremap <silent> gT :<C-u>call TabSwitch('tabprev')<CR>
" }}}2
" Spell {{{2
inoremap <C-g>+ <Esc>[szg`]a
inoremap <C-g>= <C-g>u<Esc>[s1z=`]a<C-G>u
" }}}
" Selecting around quotes without extra spaces {{{2
xmap a" 2i"
xmap a' 2i'
xmap a` 2i`
omap a" 2i"
omap a' 2i'
omap a` 2i`
" }}}2
" Edit current file path {{{2
nnoremap <expr> - isdirectory(expand('%:p:h')) ? ':e%:p:h<CR>' : '<Cmd>e ' . fnameescape(getcwd(0)) . '<CR>'
xnoremap <expr> - '<C-\><C-n>' . isdirectory(expand('%:p:h')) ? ':e%:p:h<CR>' : '<Cmd>e ' . fnameescape(getcwd(0)) . '<CR>'
" }}}2
" Enter insert mode with a space after the cursor {{{2
nnoremap <Esc>i i<Space><Left>
xnoremap <Esc>I I<Space><Left>
nnoremap <Esc>a a<Space><Left>
xnoremap <Esc>A A<Space><Left>
" }}}2
" Jump to the fisrt/last line in paragraph {{{2
" Return key seq to jump to the first line in paragraph
" return: 0
function! s:paragraph_first_line() abort
let chunk_size = 10
let init_linenr = line('.')
let linenr = init_linenr
let cnt = v:count1
" If current line is the first line of paragraph, move one line
" upwards first to goto the first line of previous paragraph
if linenr >= 2
let lines = getbufline(bufname(), linenr - 1, linenr)
if lines[0] =~# '^$' && lines[1] =~# '\S'
let linenr -= 1
endif
endif
while linenr >= 1
let chunk = getbufline(
\ bufname(),
\ max([0, linenr - chunk_size - 1]),
\ linenr - 1,
\ )
let i = 0
for line in reverse(chunk)
let i += 1
let current_linenr = linenr - i
if line =~# '^$'
let cnt -= 1
if cnt <= 0
return "m'" . (init_linenr - current_linenr - 1) . 'k'
endif
elseif current_linenr <= 1
return "m'gg"
endif
endfor
let linenr -= chunk_size
endwhile
endfunction
" Return key seq to jump to the last line in paragraph
" return: 0
function! s:paragraph_last_line() abort
let chunk_size = 10
let init_linenr = line('.')
let linenr = init_linenr
let buf_line_count = line('$')
let cnt = v:count1
" If current line is the last line of paragraph, move one line
" downwards first to goto the last line of next paragraph
if buf_line_count - linenr >= 1
let lines = getbufline(bufname(), linenr, linenr + 1)
if lines[0] =~# '\S' && lines[1] =~# '^$'
let linenr += 1
end
end
while linenr <= buf_line_count
let chunk = getbufline(
\ bufname(),
\ linenr + 1,
\ linenr + chunk_size + 1,
\ )
let i = 0
for line in chunk
let i += 1
let current_linenr = linenr + i
if line =~# '^$'
let cnt -= 1
if cnt <= 0
return "m'" . (current_linenr - init_linenr - 1) . 'j'
endif
elseif current_linenr >= buf_line_count
return "m'G"
endif
endfor
let linenr += chunk_size
endwhile
endfunction
" Use 'g{' or 'g}' to move to the first/last line of a paragraph
nmap <silent><expr> g{ <SID>paragraph_first_line()
nmap <silent><expr> g} <SID>paragraph_last_line()
xmap <silent><expr> g{ <SID>paragraph_first_line()
xmap <silent><expr> g} <SID>paragraph_last_line()
omap <silent> g{ :silent! normal Vg{<CR>
omap <silent> g} :silent! normal Vg}<CR>
" }}}2
" Text objects {{{2
" Current buffer (file)
xmap <silent> af :<C-u>silent! keepjumps normal! ggVG<CR>
xmap <silent> if :<C-u>silent! keepjumps normal! ggVG<CR>
omap <silent> af :silent! normal m`Vaf<CR>:silent! normal! ``<CR>
omap <silent> if :silent! normal m`Vif<CR>:silent! normal! ``<CR>
" Folds
" Returns the key sequence to select around/inside a fold,
" supposed to be called in visual mode
" param: motion 'i'|'a'
" return: string
function! s:textobj_fold(motion) abort
let lnum = line('.')
let sel_start = line('v')
let foldlev = foldlevel(lnum)
let foldlev_prev = foldlevel(lnum - 1)
" Multi-line selection with cursor on top of selection
if sel_start > lnum
return (foldlev == 0 ? 'zk'
\ : (foldlev > foldlev_prev && foldlev_prev ? 'k' : ''))
\ . (a:motion ==# 'i' ? ']zkV[zj' : ']zV[z')
endif
return (foldlev == 0 ? 'zj'
\ : (foldlev > foldlev_prev ? 'j' : ''))
\ . (a:motion ==# 'i' ? '[zjV]zk' : '[zV]z')
endfunction
xmap <silent><expr> iz ':<C-u>silent! keepjumps normal! ' . <SID>textobj_fold('i') . '<CR>'
xmap <silent><expr> az ':<C-u>silent! keepjumps normal! ' . <SID>textobj_fold('a') . '<CR>'
omap <silent> iz :silent! normal Viz<CR>
omap <silent> az :silent! normal Vaz<CR>
" }}}2
" Nvim default mappings {{{2
nnoremap Y y$
inoremap <C-u> <C-g>u<C-u>
inoremap <C-w> <C-g>u<C-w>
nnoremap <silent> & :&&<CR>
xnoremap <silent> * y/\V<C-R>=escape(@",'/')<CR><CR>
xnoremap <silent> # y?\V<C-R>=escape(@",'/')<CR><CR>
nnoremap <silent> <C-l> :nohlsearch\|diffupdate<CR><C-l>
" }}}2
" Window keymaps {{{2
for map in ['nnoremap', 'xnoremap']
exe map . '<Esc>w <C-w>W'
exe map . '<Esc>h <C-w>H'
exe map . '<Esc>J <C-w>J'
exe map . '<Esc>K <C-w>K'
exe map . '<Esc>L <C-w>L'
exe map . '<Esc>= <C-w>='
exe map . '<Esc>_ <C-w>_'
exe map . '<Esc><Bar> <C-w>|'
exe map . '<Esc>p <C-w>p'
exe map . '<Esc>r <C-w>r'
exe map . '<Esc>v <C-w>v'
exe map . '<Esc>s <C-w>s'
exe map . '<Esc>x <C-w>x'
exe map . '<Esc>z <C-w>z'
exe map . '<Esc>c <C-w>c'
exe map . '<Esc>q <C-w>q'
exe map . '<Esc>n <C-w>n'
exe map . '<Esc>o <C-w>o'
exe map . '<Esc>t <C-w>t'
exe map . '<Esc>T <C-w>T'
exe map . '<Esc>^ <C-w>^'
exe map . '<Esc>b <C-w>b'
exe map . '<Esc>d <C-w>d'
exe map . '<Esc>f <C-w>f'
exe map . '<Esc>} <C-w>}'
exe map . '<Esc>g] <C-w>g]'
exe map . '<Esc>g} <C-w>g}'
exe map . '<Esc>gf <C-w>gf'
exe map . '<Esc>gF <C-w>gF'
exe map . '<Esc>gt <C-w>gt'
exe map . '<Esc>gT <C-w>gT'
exe map . '<Esc>w <C-w><C-w>'
exe map . '<Esc>h <C-w><C-h>'
exe map . '<Esc>j <C-w><C-j>'
exe map . '<Esc>k <C-w><C-k>'
exe map . '<Esc>l <C-w><C-l>'
exe map . '<Esc><Left> <C-w><Left>'
exe map . '<Esc><Down> <C-w><Down>'
exe map . '<Esc><Up> <C-w><Up>'
exe map . '<Esc><Right> <C-w><Right>'
exe map . '<Esc>g<Esc>] <C-w>g<C-]>'
exe map . '<Esc>g<Tab> <C-w>g<Tab>'
exe map . '<expr> <Esc>+ v:count ? "<C-w>+" : "2<C-w>+"'
exe map . '<expr> <Esc>- v:count ? "<C-w>-" : "2<C-w>-"'
exe map . '<expr> <C-w>+ v:count ? "<C-w>+" : "2<C-w>+"'
exe map . '<expr> <C-w>- v:count ? "<C-w>-" : "2<C-w>-"'
if has('patch-8.1.1140')
exe map . '<expr> <Esc>> (v:count ? "" : 4) . (winnr() == winnr("l") ? "<C-w><" : "<C-w>>")'
exe map . '<expr> <Esc>< (v:count ? "" : 4) . (winnr() == winnr("l") ? "<C-w>>" : "<C-w><")'
exe map . '<expr> <Esc>. (v:count ? "" : 4) . (winnr() == winnr("l") ? "<C-w><" : "<C-w>>")'
exe map . '<expr> <Esc>, (v:count ? "" : 4) . (winnr() == winnr("l") ? "<C-w>>" : "<C-w><")'
exe map . '<expr> <C-w>> (v:count ? "" : 4) . (winnr() == winnr("l") ? "<C-w><" : "<C-w>>")'
exe map . '<expr> <C-w>< (v:count ? "" : 4) . (winnr() == winnr("l") ? "<C-w>>" : "<C-w><")'
exe map . '<expr> <C-w>. (v:count ? "" : 4) . (winnr() == winnr("l") ? "<C-w><" : "<C-w>>")'
exe map . '<expr> <C-w>, (v:count ? "" : 4) . (winnr() == winnr("l") ? "<C-w>>" : "<C-w><")'
else
exe map . '<expr> <Esc>> (v:count ? "" : 4) . "<C-w>>"'
exe map . '<expr> <Esc>< (v:count ? "" : 4) . "<C-w><"'
exe map . '<expr> <Esc>. (v:count ? "" : 4) . "<C-w>>"'
exe map . '<expr> <Esc>, (v:count ? "" : 4) . "<C-w><"'
exe map . '<expr> <C-w>> (v:count ? "" : 4) . "<C-w>>"'
exe map . '<expr> <C-w>< (v:count ? "" : 4) . "<C-w><"'
exe map . '<expr> <C-w>. (v:count ? "" : 4) . "<C-w>>"'
exe map . '<expr> <C-w>, (v:count ? "" : 4) . "<C-w><"'
endif
endfor
" Workaround for strange characters '0000/0000/0000^G' or '1818/1818/1919^G' in
" cmdline on entering vim in some terminals (e.g. vim's builtin terminal,
" termux, etc.)
" See https://github.com/vim/vim/issues/15458
" https://stackoverflow.com/questions/21618614/vim-shows-garbage-characters
" https://stackoverflow.com/questions/51129631/vim-8-1-garbage-printing-on-screen
" https://gentoo-user.gentoo.narkive.com/IpR4CjNN/vim-puts-command-in-when-starting-up
" https://github.com/neovim/neovim/issues/11393
autocmd TextChangedI,BufReadPost,StdinReadPost * ++once
\ nnoremap <Esc>] <C-w>] |
\ xnoremap <Esc>] <C-w>] |
\ xnoremap <nowait> <Esc> <Esc>
" }}}2
" Readline keymaps {{{2
" Match non-empty string
" param: str string
" vararg: string patterns to match
" return: string
function! s:match_nonempty(str, ...) abort
let capture = ''
for pattern in a:000
let capture = matchstr(a:str, pattern)
if capture =~# '\S'
return capture
endif
endfor
return capture
endfunction
" Get current line
" return: string
function! s:get_current_line() abort
return mode() ==# 'c' ? getcmdline() : getline('.')
endfunction
" Get current column number
" return: integer
function! s:get_current_col() abort
return mode() ==# 'c' ? getcmdpos() : col('.')
endfunction
" Get character relative to cursor
" param: offset number from cursor
" return: string character
function! s:get_char(offset) abort
return s:get_current_line()[s:get_current_col() + a:offset - 1]
endfunction
" Get word after cursor
" param: a:1 str string? content of the line, default to current line
" param: a:2 colnr integer? column number, default to current column
" return: string
function! s:get_word_after(...) abort
let str = get(a:, 1, s:get_current_line())
let colnr = get(a:, 2, s:get_current_col())
return s:match_nonempty(str[colnr - 1:],
\ '^\s*[[:keyword:]]*', '^\s*[^[:keyword:] ]*')
endfunction
" Get word before cursor
" param: a:1 str string? content of the line, default to current line
" param: a:2 colnr integer? column number, default to current column - 1
" return: string
function! s:get_word_before(...) abort
let str = get(a:, 1, s:get_current_line())
let colnr = get(a:, 2, s:get_current_col() - 1)
return colnr == 0 ? '' : s:match_nonempty(
\ str[:colnr - 1],
\ '[[:keyword:]]*\s*$',
\ '[^[:keyword:] ]*\s*$')
endfunction
" Check if current line is the last line
" return: 0/1
function! s:last_line() abort
return mode() ==# 'c' || line('.') == line('$')
endfunction
" Check if current line is the first line
" return: 0/1
function! s:first_line() abort
return mode() ==# 'c' || line('.') == 1
endfunction
" Check if cursor is at the end of the line
" return: 0/1
function! s:end_of_line() abort
return s:get_current_col() == strlen(s:get_current_line()) + 1
endfunction
" Check if cursor is at the start of the line
" return: 0/1
function! s:start_of_line() abort
return s:get_current_col() == 1
endfunction
" Check if cursor is at the middle of the line
" return: 0/1
function! s:mid_of_line() abort
let current_col = s:get_current_col()
return current_col > 1 && current_col <= strlen(s:get_current_line())
endfunction
function! s:i_ctrl_b() abort
if s:first_line() && s:start_of_line()
return "\<Ignore>"
endif
return s:start_of_line() ? "\<Up>\<End>" : "\<Left>"
endfunction
function! s:i_ctrl_f() abort
if s:last_line() && s:end_of_line()
return "\<Ignore>"
endif
return s:end_of_line() ? "\<Down>\<Home>" : "\<Right>"
endfunction
function! s:ic_meta_b() abort
let word_before = s:get_word_before()
if word_before =~# '\S' || mode() ==# 'c'
return repeat("\<Left>", strlen(word_before))
endif
" No word before cursor and is in insert mode
let current_linenr = line('.')
let target_linenr = prevnonblank(current_linenr - 1)
let target_linenr = target_linenr ? target_linenr : 1
let line_str = getline(target_linenr)
return (current_linenr == target_linenr ? '' : "\<End>")
\ . repeat("\<Up>", current_linenr - target_linenr)
\ . repeat("\<Left>", strlen(s:get_word_before(line_str,
\ strlen(line_str))))
endfunction
function! s:ic_meta_f() abort
let word_after = s:get_word_after()
if word_after =~# '\S' || mode() ==# 'c'
return repeat("\<Right>", strlen(word_after))
endif
" No word after cursor and is in insert mode
let current_linenr = line('.')
let target_linenr = nextnonblank(current_linenr + 1)
let target_linenr = target_linenr ? target_linenr : line('$')
let line_str = getline(target_linenr)
return (current_linenr == target_linenr ? '' : "\<Home>")
\ . repeat("\<Down>", target_linenr - current_linenr)
\ . repeat("\<Right>", strlen(s:get_word_after(line_str, 1)))
endfunction
" Callback function for small delete, e.g. `<C-w>`, `<M-BS>`, `<M-d>`, `<C-k>`,
" `<C-u>`, etc keymaps; sets the small delete register '-' properly, should be
" used " with `{ expr = true }`
" param: text_deleted string
" param: forward 0/1
" return: string
function! s:ic_small_del(text_deleted, forward) abort
" Lock to prevent next deletion before current deletion action completes.
" If we don't set this lock we might get and save wrong (old) cursor position
" in CmdlineChanged/TextChangedI callbacks, which will cause the '-' register
" to be reset undesirably.
if get(g:, '_rl_del_lock') || a:text_deleted == ''
return ''
endif
let g:_rl_del_lock = 1
let in_cmdline = mode() == 'c'