-
Notifications
You must be signed in to change notification settings - Fork 0
/
vimrc
2515 lines (2254 loc) · 92.5 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
" VIM FULL CONFIGURATION {{{1
" vim: foldmethod=marker:foldlevel=0:nofoldenable:
" Author: [Sri Kadimisetty](https://github.com/kadimisetty)
"PLUGINS {{{1
"Initialize vim-plug {{{2
call plug#begin('~/.vim/plugged')
"Active Plugins {{{2
" NOTE: Keep this list sorted
Plug 'LnL7/vim-nix'
Plug 'Zaptic/elm-vim'
Plug 'airblade/vim-gitgutter'
Plug 'axelf4/vim-strip-trailing-whitespace'
Plug 'bps/vim-textobj-python'
Plug 'c-brenn/phoenix.vim'
Plug 'cespare/vim-toml'
Plug 'chrisbra/NrrwRgn'
Plug 'christoomey/vim-sort-motion'
Plug 'christoomey/vim-titlecase'
Plug 'dag/vim-fish'
Plug 'dense-analysis/ale'
Plug 'elixir-editors/vim-elixir'
Plug 'fatih/vim-go'
Plug 'fladson/vim-kitty'
Plug 'gcmt/taboo.vim'
Plug 'gruvbox-community/gruvbox'
Plug 'hspec/hspec.vim'
Plug 'janko/vim-test'
Plug 'jiangmiao/auto-pairs'
Plug 'joukevandermaas/vim-ember-hbs'
Plug 'junegunn/goyo.vim'
Plug 'junegunn/gv.vim'
Plug 'junegunn/rainbow_parentheses.vim'
Plug 'junegunn/vim-easy-align'
Plug 'junegunn/vim-peekaboo'
Plug 'kadimisetty/dash.vim', {'branch': 'fix-open-flicker'}
Plug 'kana/vim-textobj-entire'
Plug 'kana/vim-textobj-indent'
Plug 'kana/vim-textobj-user'
Plug 'kevinoid/vim-jsonc'
Plug 'lifepillar/pgsql.vim'
Plug 'ludovicchabant/vim-gutentags'
Plug 'machakann/vim-highlightedyank'
Plug 'majutsushi/tagbar'
Plug 'mattn/emmet-vim'
Plug 'mhinz/vim-mix-format'
Plug 'mhinz/vim-startify'
Plug 'mmorearty/elixir-ctags'
Plug 'mxw/vim-jsx'
Plug 'nathanaelkane/vim-indent-guides'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'neomake/neomake'
Plug 'neovimhaskell/haskell-vim'
Plug 'pangloss/vim-javascript'
Plug 'pbrisbin/vim-syntax-shakespeare'
Plug 'pest-parser/pest.vim'
Plug 'purescript-contrib/purescript-vim'
Plug 'idris-hackers/idris-vim'
Plug 'psf/black', { 'branch': 'stable' }
Plug 'raimon49/requirements.txt.vim', {'for': 'requirements'}
Plug 'rob-b/gutenhasktags'
Plug 'romainl/vim-cool'
Plug 'rust-lang/rust.vim'
Plug 'sdiehl/vim-ormolu'
Plug 'sgur/vim-textobj-parameter'
Plug 'simnalamburt/vim-mundo'
Plug 'styled-components/vim-styled-components', { 'branch': 'main' }
Plug 'tmux-plugins/vim-tmux'
Plug 'tomtom/tcomment_vim' "Does embedded filetypes unlike tpope/vim-commentary
Plug 'tpope/tpope-vim-abolish'
Plug 'tpope/vim-endwise'
Plug 'tpope/vim-eunuch'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-liquid'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-rsi'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-unimpaired'
Plug 'tpope/vim-vinegar'
Plug 'tweekmonster/django-plus.vim'
Plug 'vale1410/vim-minizinc'
Plug 'vim-airline/vim-airline'
Plug 'vmchale/dhall-vim'
Plug 'wfxr/minimap.vim' "Requires `code-minimap` available via cargo, nix etc.
Plug 'wsdjeg/vim-fetch'
"NERDTree. Save order.
Plug 'scrooloose/nerdtree'
Plug 'Xuyuanp/nerdtree-git-plugin'
"vim-prettier installs it's own prettier with npm.
"Also enable for listed formats
Plug 'prettier/vim-prettier', { 'do': 'npm install' }
"fzf binary is updated upon fzf plugin upgrade. Save order.
" fzf is basic integration and fzf.vim is vim plugin
Plug 'junegunn/fzf'
Plug 'junegunn/fzf.vim'
"Projections. Save order.
Plug 'tpope/vim-projectionist'
Plug 'c-brenn/fuzzy-projectionist.vim'
"Tabular and Markdown. Save order.
"(godlygeek/tabular is a dependency for plasticboy/vim-markdown)
Plug 'godlygeek/tabular'
Plug 'plasticboy/vim-markdown'
"Vim-Devicons. Load as last plugin
Plug 'ryanoasis/vim-devicons' "Requires encoding utf-8. Set as such elsewhere.
"Finish vim-plug
call plug#end()
"SEARCH {{{1
set infercase "Infer case matching while doing keyword completions
set ignorecase "Case insensitive Search
set hlsearch "For non-case sensitive search
set smartcase "Perform case-detection slightly more sensibly
set wrapscan "Wrap search scan around the file
set incsearch "Match search incrementally
"MISC PREFERENCES {{{1
"Leaders {{{2
let mapleader = '\'
let maplocalleader = '\\'
"Wildignore {{{2
"Ignore these file patterns while completing file/dir names
"(Also used by plugins like CtrlP, NERDTree etc.)
"Ignoring: Usual culprits
set wildignore+=*.o,*.obj,*.exe,*.so,*.dll,*.pyc,*.lock
"Ignoring: Source Control
set wildignore+=.svn,.hg,.bzr,.git,.git/*
"Ignoring: CSS Preprocessors
set wildignore+=.sass-cache,*.class,*.scssc,*.cssc,
"Ignoring: JS & Node
set wildignore+=.sass-cache,*.class,*.scssc,*.cssc,
"Ignoring: Elixir Mix & Phoenix etc.
set wildignore+=*/_build/*,*/cover/*,*/deps/*,*/.fetch/*,erl_crash.dump,mix.lock
set wildignore+=*.ez,*.beam,*/config/*.secret.exs,.elixir_ls/*
"Ignoring: Python Projects
set wildignore+=.ropeproject,__pycache__,*.egg-info,.DS_Store
"Ignoring: Haskell Projects
set wildignore+=.stack-work,.stackwork/*
"Encodings {{{2
set encoding=utf-8 "Set default file encoding to UTF-8
"Set character encoding in the script.
"NOTE: Place after setting encoding, see `:help scriptencoding`
scriptencoding utf-8
set title "Enable setting title
"Completions & Ignores {{{2
set wildmenu "Perform things like menu completion with wildchar(often tab) etc.
set iskeyword+=_,$,@,%,#,- "Treat as keywords
set printoptions=header:0,duplex:long,paper:A4
"Diffs {{{2
"open diffs in vertical split
set diffopt+=vertical
" Session options {{{2
" DEFAULT: `blank,buffers,curdir,folds,help,options,tabpages,winsize,terminal`
" DESIRED: `blank,buffers,curdir,folds,help,tabpages,winsize,globals`
set sessionoptions+=tabpages
set sessionoptions+=globals
set sessionoptions-=terminal
" `options`: all options and mappings (also global values for local options)
" TODO:
" Figure out why I removed `options` and kept `globals`.
" (INDECIPHERABLE PREVIOUS NOTES ON REASON: Do not save some options into
" the sessions file, so they dont override any vimrc changes made when the
" session is revoked later.). Is it related to this link?
" [stack overflow answer](https://stackoverflow.com/a/1651061/225903)
set sessionoptions-=options
"Misc {{{2
syntax on "Turn on syntax highlighting
set hidden "Unsaved bufers are allowed to move to the background
set noshowmode "Don't print mode changes upon entering a new mode e.g. --INSERT--
set autoread "Sync loaded file to changes on disk
set laststatus=2 "Always display a status line, even with only 1 window
set mousehide "Hide mouse pointer while typing
set mouse=a "Automatically detect mouse usage
set history=500 "Remember 500 items in history
set showcmd "Show partial command in the last line at the bottom
"Use external program [`par`](http://www.nicemice.net/par/) to format paragraphs
"gwip will still use vim's own formatprg
set formatprg=par\ -w50
"Expect vim modelines in the first 3 lines (3 to allow for encoding, title)
set modeline
set modelines=3
set completeopt=menu,menuone,noinsert,preview
"Close quickfix window if it's the last one left
"SEE: https://vim.fandom.com/wiki/Automatically_quit_Vim_if_quickfix_window_is_the_last
augroup quickfix_to_be_closed
autocmd!
autocmd BufEnter * call CloseQuickfixIfItIsLastOpenWinLeftInTab()
augroup end
" close if quickfix is the last window left in this tab
function! CloseQuickfixIfItIsLastOpenWinLeftInTab()
if (&buftype=="quickfix" && winnr('$') < 2)
quit
endif
endfunction
"FILETYPE PREFERENCES {{{1
" FILETYPE SETTINGS {{{2
filetype on "Detect filetypes
filetype plugin on "Activate builtin set of filetypes plugins
filetype indent on "Activate builtin and computed indentations
augroup filetype_rss
autocmd!
" Treat .rss files as XML. Place before encoding.
autocmd BufNewFile,BufRead *.rss setfiletype xml
augroup end
augroup filetype_md
autocmd!
"Use md for markdown instead of the default module2
autocmd BufNewFile,BufRead *.md setfiletype markdown
augroup end
augroup filetype_help
autocmd!
autocmd FileType help setlocal textwidth=78
autocmd BufWinEnter *.txt call MoveHelpToNewTab()
augroup end
function! MoveHelpToNewTab ()
if &buftype ==# 'help' | wincmd T | endif
endfunction
" MISC FILETYPE HELPERS {{{2
augroup filetype_haskell
autocmd!
" Chosing formatprg as hindent to keep a secondary formatprg at hand
" NOTE: Requires `hindent` in `$PATH`
" TODO: Call via `stack` (like `ALE` does for `hlint`)
autocmd FileType haskell setlocal formatprg=hindent
" Append current word with a trailing `'`
" TODO: Use a function to allow adding and removing trailing `'`
autocmd FileType haskell nnoremap <silent> <localleader>' ea'<Esc>
" Insert module line on new buffers
" i.e. for a new buffer named `Foo.hs` add the module line `module Foo where`
autocmd BufNewFile *.hs :execute
\ "normal! Imodule " . expand("%:t:r") . " where\<cr>\<cr>\<esc>"
augroup end
augroup haskell_stack_helper
autocmd!
" PROJECT WIDE COMMANDS (using <leader>)
" i.e. Run `stack` on entire project
autocmd FileType haskell nnoremap <silent> <leader>sr :call term_start(
\ "stack run",
\ { "term_name":"stack run"
\ })<CR>
autocmd FileType haskell nnoremap <silent> <leader>st :call term_start(
\ "stack test",
\ { "term_name":"stack test"
\ })<CR>
autocmd FileType haskell nnoremap <silent> <leader>sg :call term_start(
\ "stack ghci",
\ { "term_name":"stack ghci"
\ , "term_finish": "close"
\ })<CR>
autocmd FileType haskell nnoremap <silent> <leader>sb :call term_start(
\ "stack build",
\ { "term_name":"stack build"
\ })<CR>
autocmd FileType haskell nnoremap <silent> <leader>sbf :call term_start(
\ "stack build --fast",
\ { "term_name":"stack build fast"
\ })<CR>
autocmd FileType haskell nnoremap <silent> <leader>sbw :call term_start(
\ "stack build --fast --file-watch",
\ { "term_name":"stack build watch"
\ , "term_rows":3
\ })<CR>
" FILE SPECIFIC COMMANDS (using <localleader>)
" i.e. Run `stack` on file in current buffer
autocmd FileType haskell nnoremap <silent> <localleader>sr :call term_start(
\ "stack runhaskell " . expand('%:~'),
\ { "term_name": "stack run " . expand('%:p:t')
\ })<CR>
autocmd FileType haskell nnoremap <silent> <localleader>sg :call term_start(
\ "stack ghci " . expand('%:p:t'),
\ { "term_name":"stack ghci " . expand('%:p:t')
\ , "term_finish": "close"
\ })<CR>
" Makes easier to type the last part of `stack new FOO kadimisetty/basic`
" by providing an imap for appending "kadimisetty/basic" to the end of line.
" This is for when opening zsh shell currently being written in $EDITOR
" with the shortcut commanbd <C-x><C-e>. See help section
" `edit-and-execute-command` in `man bash`. Bash has sligtlty different
" behavior from zh. Prefer the zsh behavior.
" Why `kb`? For `kadimisetty basic`.
" Does: Inserts the text, switches to normal mode and exits to shell.
autocmd FileType zsh inoremap <silent> <leader>kb kadimisetty/basic<esc>ZZ
autocmd FileType zsh nnoremap <silent> <leader>kb A kadimisetty/basic<esc>ZZ
" Add an `undefined` implementation for function whose type signature is on current line
autocmd FileType haskell nnoremap <silent> <localleader>u :<c-u>call HaskellAddUndefinedImplForFuntionTypeSignOnCurrentLine()<CR>
augroup END
function HaskellAddUndefinedImplForFuntionTypeSignOnCurrentLine()
" TODO:
" 1. Match indentation.
" 2. Do not use up registers being used here to record position and function name.
execute "normal! mn^yiwo\<esc>pA = undefined\<esc>`n"
endfunction
augroup haskell_stack_helper_package_yaml
autocmd!
" For package.yaml, only allow:
" `stack build`
" `stack build --fast`
" PROJECT WIDE COMMANDS (using <leader>)
" i.e. Run `stack` on entire project
autocmd BufEnter package.yaml nnoremap <silent> <leader>sb :call term_start(
\ "stack build",
\ { "term_name":"stack build"
\ })<CR>
autocmd BufEnter package.yaml nnoremap <silent> <leader>sbf :call term_start(
\ "stack build --fast",
\ { "term_name":"stack build fast"
\ })<CR>
augroup END
augroup filetype_elm
" Insert module line on new buffers i.e. for a new buffer named `Foo.elm`
" add the module line at the top:
" `module Foo exposing (..)`
autocmd BufNewFile *.elm :execute
\ "normal! Imodule " . expand("%:t:r") . " exposing (..)\<cr>\<cr>\<esc>"
augroup end
" FILETYPE-SPECIFIC TOGGLES {{{2
" Toggle filetype specific elements, usually on current line.
" e.g.: `<local-leader>,` toggles a trailing comma on current line.
"
" NOTES:
" 1. Using `<localleader>` as prefix for the toggle keys.
" 2. Keep the toggles small, preferably to acted on elements on current
" line or word under cursor.
" 3. WARNING: A toggle that makes sense in one filetype might not be able to
" use the same login in anither filetype, so keep that in mind.
" TODO:
" 1. Group together commonly applicable toggles, .e.g. trailing comma toggle.
" 2. Get common toggles for common programming languages.
" 3. Consider an alternate prefix(other than `<localleader>`).
" 4. Refine the helper functions.
" TOGGLE MAPPINGS: {{{3
augroup toggles_elixir
autocmd!
" Toggle trailing comma on current line
autocmd FileType elixir nnoremap <silent> <localleader>, :call ToggleTrailingStringOnLine(",", line("."))<CR>
" Toggle leading `_` on current word
autocmd FileType elixir nnoremap <silent> <localleader>_ :call ToggleLeadingUnderscoreOnWordUnderCursor()<CR>
augroup end
augroup toggles_python
autocmd!
" Toggle trailing colon on current line
autocmd FileType python nnoremap <silent> <localleader>: :call ToggleTrailingStringOnLine(":", line("."))<CR>
" Toggle trailing comma on current line
autocmd FileType python nnoremap <silent> <localleader>, :call ToggleTrailingStringOnLine(",", line("."))<CR>
" Toggle leading `async`/`await` keywords on current line
autocmd FileType python nnoremap <silent> <localleader>a :call ToggleAsyncOrAwaitKeywordPython(".")<CR>
" Toggle `pass` keywork on current line
autocmd FileType python nnoremap <silent> <localleader>p :call TogglePassKeywordPython(".")<CR>
" Toggle `pass` keywork on current line, replacing any existing content
autocmd FileType python nnoremap <silent> <localleader>P :call TogglePassKeywordReplacingContentPython(".")<CR>
" Toggle trailing pyright ignore label ` # type: ignore` on current line
autocmd FileType python nnoremap <silent> <localleader>i :call ToggleTrailingStringOnLine(" # type: ignore", line("."))<CR>
augroup end
augroup toggles_rust
autocmd!
autocmd FileType rust setlocal formatprg=rustfmt
" Toggle trailing semicolon on current line
autocmd FileType rust nnoremap <silent> <localleader>; :call ToggleTrailingStringOnLine(";", line("."))<CR>
" Toggle trailing comma on current line
autocmd FileType rust nnoremap <silent> <localleader>, :call ToggleTrailingStringOnLine(",", line("."))<CR>
" Toggle leading `let/let mut` keywords on current line
autocmd FileType rust nnoremap <silent> <localleader>l :call ToggleLetKeyword(".", 0, 1)<CR>
autocmd FileType rust nnoremap <silent> <localleader>lm :call ToggleLetKeyword(".", 1, 0)<CR>
" Toggle leading `pub` keyword on current line
autocmd FileType rust nnoremap <silent> <localleader>p :call TogglePubKeyword(".")<CR>
" Toggle trailing `into()` on content of current line
autocmd FileType rust nnoremap <silent> <localleader>i :call ToggleTrailingInto(".")<CR>
" Toggle leading `async` keyword on current line
autocmd FileType rust nnoremap <silent> <localleader>a :call ToggleAsyncKeywordRust(".")<CR>
" Toggle trailing `await` on content of current line
autocmd FileType rust nnoremap <silent> <localleader>A :call ToggleTrailingAwaitKeyword(".")<CR>
" Toggle trailing question mark on current line
autocmd Filetype rust nnoremap <silent> <localleader>? :call ToggleTrailingQuestionMark(".")<CR>
" Toggle wrapping `Ok()` and `Err()` on current line
autocmd FileType rust nnoremap <silent> <localleader>o :call ToggleWrappingTagOnCurrentLine("Ok")<CR>
autocmd FileType rust nnoremap <silent> <localleader>e :call ToggleWrappingTagOnCurrentLine("Err")<CR>
" Toggle leading `_` on current word
autocmd FileType rust nnoremap <silent> <localleader>_ :call ToggleLeadingUnderscoreOnWordUnderCursor()<CR>
" TODO: Toggle attribute `[allow(dead_code)]` on current line
" autocmd FileType rust nnoremap <silent> <localleader>d :call ToggleAttributeOnLine("[allow(dead_code)]" , ".")<CR>
augroup end
" TOGGLE HELPERS: {{{3
function! TogglePassKeywordReplacingContentPython(line_number)
" Toggles leading keywords `pass`
let line_content = getline(a:line_number)
let trimmed_line_content = trim(line_content)
if (trimmed_line_content =~# "^pass")
execute 'normal ^d4l'
else
execute 'normal Spass'
endif
endfunction
function! TogglePassKeywordPython(line_number)
" Toggles leading keywords `pass`
let line_content = getline(a:line_number)
let trimmed_line_content = trim(line_content)
if (trimmed_line_content =~# "^pass")
execute 'normal ^d4l'
else
execute 'normal Ipass'
endif
endfunction
function! ToggleAsyncOrAwaitKeywordPython(line_number)
" Toggles leading keywords `async` or `await` on given line.
" NOTE: This is bound to python's async grammar i.e. if line
" begins with `def`(function) then `async` is toggled, else `await` (not
" function) is toggled.
let line_content = getline(a:line_number)
let trimmed_line_content = trim(line_content)
if ((trimmed_line_content =~# "^async ") || (trimmed_line_content =~# "^await "))
execute 'normal ^d6l'
else
if (trimmed_line_content =~# "^def ")
execute 'normal Iasync '
else
execute 'normal Iawait '
endif
endif
endfunction
function! ToggleAttributeOnLine(string, line_number)
" TODO:
" - Multiple attributes?
" - Preserve indentation
" - Attributes acting on a statement can be stacked on multiple lines,
" so check for that.
" - Sometimes one of the stacked attributes can span multiple lines with
" a comma in between and so the check for multiple attributes would have
" to take that into account.
"
" GIVEN ATTRIBUTE ON ABOVE LINE? YES
" REMOVE GIVEN ATTRIBUTE LINE ABOVE CURRENT LINE
" GIVEN ATTRIBUTE ON ABOVE LINE? NO
" DIFFERENT ATTRIBUTE ON ABOVE LINE? YES
" GIVEN ATTRIBUTE ON ANY STACKED ATTRIBUTES ABOVE LINE? YES
" REMOVE THE GIVEN ATTRIBUTE LINE
" GIVEN ATTRIBUTE ON ANY STACKED ATTRIBUTES ABOVE LINE? NO
" ADD GIVEN ATTRIBUTE IN LINE ABOVE CURRENT LINE
" DIFFERENT ATTRIBUTE ON ABOVE LINE? NO
" ADD GIVEN ATTRIBUTE IN LINE ABOVE CURRENT LINE
endfunction
function! ToggleTrailingAwaitKeyword(line_number)
" Toggles trailing `await` keyword on line of provided line number
"
let trimmed_line_content = getline(a:line_number)->trim()
"
" Ensure trimmed line is not empty
if strchars(trimmed_line_content) > 0
" TRAILING `?;`
if trimmed_line_content =~# '?;$'
" TRAILING `.await` BEHIND `?;`?
if trimmed_line_content =~# '.await?;$'
" YES: Remove trailing `.await`
execute "normal mm$hd6h`m"
else
" NO: Insert `.await` behind trailing `?;`
execute "normal mm$hi.await\e`m"
endif
" TRAILING `;`
elseif trimmed_line_content =~# ';$'
" TRAILING `.await` BEHIND `;`?
if trimmed_line_content =~# '.await;$'
" YES: Remove trailing `.await`
execute "normal mm$d6h`m"
else
" NO: Insert `.await` behind trailing `;`
execute "normal mm$i.await\e`m"
endif
" NO TRAILING `?;` OR `;`
else
" TRAILING `.await`?
if trimmed_line_content =~# '.await$'
" YES: Remove trailing `.await`
execute "normal mm$d5hx`m"
else
" NO: Insert trailing `.await`
execute "normal mmA.await\e`m"
endif
endif
endif
endfunction
function! ToggleLeadingUnderscoreOnWordUnderCursor()
" Toggles `_` on word under cursor
"
" NOTE: Uses `wb` to jump to first letter of word.
" TODO:
" Fix bug where while `wb` always lands cursor at beginning of word,
" it has a catch where it can't work if cursor is on last letter of last
" word in file (and thereby also single letter words at end of file).
"
" Get current word
let word_under_cursor = expand("<cword>")
"
" Act only if cursor is on top of a word that is at least 1 letter long
if len(word_under_cursor) > 0
if word_under_cursor =~# "^_"
" Remove leading underscore on word under cursor
execute 'normal mmwb"_x`mh'
else
" Insert leading underscore on word under cursor
execute "normal mmwbi_\e`ml"
endif
endif
endfunction
function! ToggleWrappingTagOnCurrentLine(tag)
" Toggles wrapping line content with supplied tag e.g. `Ok()` or `Err()`
"
let trimmed_line_content = trim(getline("."))
if len(trimmed_line_content) == 0
" Empty line: Produce empty tag e.g. Ok(())
execute 'normal I' . a:tag . '()'
else
" Non-empty line: Toggle tag around current line content. e.g. `Ok("x") and `"x"`
" Check if line begins with tag name e.g. `Ok` or `Err`
if trimmed_line_content =~# '^' . a:tag
" Remove leading tag and `(`
execute 'normal ^d' . (len(a:tag)+1) . 'l'
" Check if trailing semicolon
if trimmed_line_content =~ ';$'
" Remove `)` before trailing semicolon
execute 'normal $h"_x'
else
" Remove trailing semicolon
execute 'normal $"_x'
endif
else
" Add leading tag and `(`
execute 'normal I' . a:tag . '('
" Check if trailing semicolon
if trimmed_line_content =~ ';$'
" Add `)` before trailing semicolon
execute 'normal $i)'
else
" Add trailing `)`
execute 'normal A)'
endif
endif
endif
endfunction
function ToggleTrailingQuestionMark(line_number)
" Toggles trailing `?` character in both `?` and `?;` forms
" TODO: Adapt to use `ToggleTrailingStringOnLine`
" LOGIC:
" 1. Ensure non-empty trimmed line
" 2. Check if there is a trailing `?`
" YES: Remove trailing `?`
" NO: Check if there is a trailing `;`
" NO: Add trailing `?`
" YES: Check if there is `?` behind trailing `;`
" YES: Remove that `?` before trailing `;`
" NO: Add `?` before trailing `;`
"
let line_content = getline(a:line_number)
let trimmed_line_content = trim(line_content)
"
" Ensure trimmed line is not empty
if strwidth(trimmed_line_content) > 0
" Check if there is a trailing `?`
if (line_content[-1:] == '?' )
" Remove trailing `?`
call setline(a:line_number, line_content[:-2])
else
" Check if there is a trailing `;`
if (line_content[-1:] == ';' )
" Check if there is `?` behind trailing `;`
if (line_content[-2:-1] == '?;' )
" Remove that `?` before trailing `;`
call setline(a:line_number, line_content[:-3] . ';')
else
" Add `?` before trailing `;`
call setline(a:line_number, line_content[:-2] . '?;')
endif
else
" Add trailing `?`
call setline(a:line_number, line_content . '?')
endif
endif
endif
endfunction
function! ToggleTrailingInto(line_number)
" Toggles the into keyword on last word of a non-empty line.
" TODO: Make more flexible i.e. remove hardocded positions.
" LOGIC:
" line has trailing `;`?
" YES: line has `.into()` before trailing `;`?
" YES: remove `.into()` before trailing `;`
" NO: insert `.into()` before trailing `;`
" NO: line ends with `.into()`
" YES: remove .into()
" NO: append `.into()`
"
let line_content = getline(a:line_number)
let trimmed_line_content = trim(line_content)
if len(trimmed_line_content) == 0
" Ensure non-empty line
return
else
if trimmed_line_content =~# ';$'
if trimmed_line_content =~# 'into();$'
execute 'normal $d7h'
else
execute 'normal $i.into()'
endif
else
if trimmed_line_content =~# 'into()$'
execute 'normal $d6hx'
else
echomsg "into()$"
execute 'normal A.into()'
endif
endif
endif
endfunction
function! ToggleAsyncKeywordRust(line_number)
let line_content = getline(a:line_number)
let trimmed_line_content = trim(line_content)
if (trimmed_line_content =~# "^async ")
execute 'normal ^d6l'
else
execute 'normal Iasync '
endif
endfunction
function! TogglePubKeyword(line_number)
let line_content = getline(a:line_number)
let trimmed_line_content = trim(line_content)
if (trimmed_line_content =~# "^pub ")
execute 'normal ^d4l'
else
execute 'normal Ipub '
endif
endfunction
function! ToggleTrailingStringOnLine(string, line_number)
" Toggles trailing given string on line at given line number
"
" TODO: Check which builtin string length function to use from:
" len/strlen/strdisplaywidth/strwidth erc.
"
let line_content = getline(a:line_number)
let string_length= strwidth(a:string)
"
" TODO: Also check if line length is > than given string_length?
" Ensure line is not empty
if strwidth(line_content) > 0
if (line_content[-(string_length):] == a:string)
" Append given string if not present at end of line
call setline(a:line_number, line_content[:-(string_length+1)])
else
" Remove trailing given string if present at end of line
call setline(a:line_number, line_content . a:string)
endif
endif
endfunction
function! ToggleLetKeyword (line_number, toggle_let_mut, toggle_let)
"TODO: While this function accepts a line_number, the helpe fucntions within
" only act upon the current line to accomodate the current way of restoring
" the cursor position. Rewrite them to accept an arbitrary line number.
"
" Assert provided toggle_* arguments are mutually exclusive booleans
if (a:toggle_let_mut == a:toggle_let)
echoerr "Provided arguments make it imposible to decide between exclusive keywords - `let` and `let mut`"
else
let line_content = getline(a:line_number)
let trimmed_line_content = trim(line_content)
" Note whether line begins with `let mut` or `let`
" 1. First check for leading `let mut`
if (trimmed_line_content =~# "^let mut ")
let has_let_mut = 1
else
let has_let_mut = 0
" 2. Next check for leading `let`
" (Nesting to avoid `let mut` matcfhes)
if (trimmed_line_content =~# "^let ")
let has_let = 1
else
let has_let = 0
endif
endif
"
" TOGGLING LOGIC:
" +--------------+------------------+----------------+
" | | a:toggle_let_mut | a:toggle_let |
" +==============+==================+================+
" | has_let_mut | RemoveLetMut() | RemoveLetMut() |
" | | | PrependLet() |
" +--------------+------------------+----------------+
" | has_let | RemoveLetMut() | RemoveLet() |
" | | PrependLet() | |
" +--------------+------------------+----------------+
" | !has_let_mut | PrependLetMut() | PrependLet() |
" | !has_let | | |
" +--------------+------------------+----------------+
"
" Helper functions that modify current line:
" TODO:
" - Cover edge cases while restoring the cursor
" - Accept arbitrary line number instead of acting on current line
" - Remove the use of normal
function! PrependLetMut()
let save_pos = getpos(".")
execute 'normal Ilet mut '
call setpos('.', save_pos)
execute 'normal 8l'
endfunction
function! RemoveLetMut()
let save_pos = getpos(".")
execute 'normal ^2dw'
call setpos('.', save_pos)
execute 'normal 8h'
endfunction
function! PrependLet()
echo "PrependLet"
let save_pos = getpos(".")
execute 'normal Ilet '
call setpos('.', save_pos)
execute 'normal 4l'
endfunction
function! RemoveLet()
let save_pos = getpos(".")
execute 'normal ^dw'
call setpos('.', save_pos)
execute 'normal 4h'
endfunction
"
" Run logic
if a:toggle_let_mut && has_let_mut
call RemoveLetMut()
elseif a:toggle_let_mut && has_let
call RemoveLet()
call PrependLetMut()
elseif a:toggle_let_mut && (!has_let_mut && !has_let)
call PrependLetMut()
"
elseif a:toggle_let && has_let_mut
call RemoveLetMut()
call PrependLet()
elseif a:toggle_let && has_let
call RemoveLet()
elseif a:toggle_let && (!has_let_mut && !has_let)
call PrependLet()
else
" NoOp
endif
endif
endfunction
"INDENTS & FOLDS {{{1
"Vi Folding Specifics {{{2
augroup foldmethod_vim
autocmd!
autocmd FileType vim setlocal foldmethod=marker
augroup end
set nofoldenable "Disable Folds by deafult
set foldopen=block,insert,jump,mark,percent,quickfix,search,tag,undo
set foldmethod=syntax
set foldlevelstart=1
let javaScript_fold=1 "JavaScript
let perl_fold=1 "Perl
let php_folding=1 "PHP
let r_syntax_folding=1 "R
let ruby_fold=1 "Ruby
let sh_fold_enabled=1 "sh
let vimsyn_folding='af' "Vim script
let xml_syntax_folding=1 "XML
"Custom Fold Title {{{2
function! NeatFoldText()
let line = ' ' . substitute(getline(v:foldstart), '^\s*"\?\s*\|\s*"\?\s*{{' . '{\d*\s*', '', 'g') . ' '
let lines_count = v:foldend - v:foldstart + 1
let lines_count_text = '| ' . printf("%10s", lines_count . ' lines') . ' '
let foldchar = matchstr(&fillchars, 'fold:\zs.')
let foldtextstart = strpart('' . line, 0, (winwidth(0)*2)/3)
let foldtextend = lines_count_text . repeat(' ', 8)
let foldtextlength = strlen(substitute(foldtextstart . foldtextend, '.', 'x', 'g')) + &foldcolumn
return foldtextstart . repeat(foldchar, winwidth(0)-foldtextlength) . foldtextend
endfunction
set foldtext=NeatFoldText()
"Wraps & Indents {{{2
"Enables :Wrap to set settings required for soft wrap
command! -nargs=* Wrap set wrap linebreak nolist
set cindent "Use C's indenting rules
set smarttab "Insert bkanks according to listed shiftwidth/tabstop/softtabstop
set expandtab "Use appropriate number of spaces to insert a tab when autodindent is on
set pastetoggle=<F12> "Same indentation on pastes
set cf "Allow error files and error jumping
set timeoutlen=350 "Wait for this long anticipating for a command
"Backup Preferences {{{2
set backup "Make a backup before writing the file
set backupdir=~/.vim/backup "Use this directory to store backups
set directory=/tmp/ "List of directory names to create the swp files in
set backupcopy=yes "Make a backup and then overwrite orginal file
set backupskip=/tmp/*,$TMPDIR/*,$TMP/*,$TEMP/*
"UI CHANGES {{{1
"Misc {{{2
set number "Display line numbers
set ruler "Display line number and cursor position
set nostartofline "Do not shift cursor back to line beginning while scrolling
set report=0 "Threshold for number of lines changed
set ch=2 "Command line height(1 is default)
set nolazyredraw "Redraw screen while executing macros, registers, untyped commands etc.
set showmatch "When cursor is on bracket, briefly jump to coupled bracket
set mat=5 "Spend this much time switching the cursor to the coupled bracket
set novisualbell "Don't show visual bell (enabled when audio bell is turned off)
set belloff=all "Stop all error bellsof
set formatoptions+=n "Support lists (numbered, bulleted)
set virtualedit=block "Allow cursor to go to invalid places only in visually selected blocks
set wildmode=full "Tab-Completion ala zsh
set background=dark
" Set vertical window sepertor to pipelike symbol │ with no vertical spaces
set fillchars+=vert:│
"Title {{{2
set title
set titleold="Terminal"
if has('statusline')
"Clear title string
set titlestring=
"Show + if file has been modified
set titlestring+=%M
"Show base filename
set titlestring+=%f
"Show [help] if help window
set titlestring+=%h
"Show [RO] if read-only
set titlestring+=%r
"Show [Preview] if preview window
set titlestring+=%w
endif
" Change cursor shapes for different modes {{{2
"
" Reference for Terminal Escape Sequence Numbers for Cursor Shapes:
" +------------+-----------------------+
" | 0, 1, none | Blink Block (Default) |
" | 2 | Steady Block |
" | 3 | Blink Underline |
" | 4 | Steady Underline |
" | 6 | Steady Vertical Bar |
" +------------+-----------------------+
if $TERM =~ "xterm-kitty"
let &t_SI="\033[6 q"
let &t_SR="\033[4 q"
let &t_EI="\033[2 q"
elseif $TERM_PROGRAM =~ "Apple_Terminal"
let &t_SI="\033[6 q" "Vertical bar in Insert mode
let &t_SR="\033[4 q" "Underline in Replace mode
let &t_EI="\033[2 q" "Steady Block in Normal mode
elseif $TERM_PROGRAM =~ "iTerm"
"iTerm cursors look much better, especially contrast on hover.
"https://hamberg.no/erlend/posts/2014-03-09-change-vim-cursor-in-iterm.html
let &t_SI = "\<Esc>]50;CursorShape=1\x7" "Vertical bar in Insert mode
let &t_EI = "\<Esc>]50;CursorShape=0\x7" "Steady Block in Normal mode
let &t_SR = "\<esc>]50;CursorShape=2\x7" "Underline in Replace mode
elseif $TERM_PROGRAM =~ "tmux"
" NOTE: When `$TERM_PROGRAM` shows `tmux` it isn't possible to
" say whether we are in `terminal.app` or `iTerm.app`, so using the
" same settings for `terminal.app` since they work for both `terminal.app`
" and `iTerm`, unlike `iTerm's`.
let &t_SI="\033[6 q"
let &t_SR="\033[4 q"
let &t_EI="\033[2 q"
endif
"Show error messages and throw exceptions
" set debug=msg,throw
"Show ellipsis on a soft break
" NOTE:
" 1. This previous used to be `…` but in 9.x version,
" so using `> ` in the meantime.
" 2. The trailing space required a backslash.
set showbreak=>\
set synmaxcol=2048 "For performance, only do syntax highlight upto these columns
set nocursorline "Highlight the screen line of cursor
set nocursorcolumn "Highlight the screen column of cursor
set splitbelow "Position newly split windows to thebelow
set splitright "Position newly split windows to the right
syntax enable "Enable Syntax highlighting
"Whitespace & Other Special Characters {{{2
set scrolloff=1 "Keep cursor these many lines above bottom of screen
set nowrap "Wrap Long lines
set autoindent "Indent as previous line
set softtabstop=4
set shiftwidth=4 "Use indents as length of 4 spaces
set shiftround "Round indent to multiple of 'shiftwidth'
set tabstop=4 "A tab counts for these many spaces
set backspace=2 "Make backspace behave more like the popular usage
"Whitespace {{{3
"TODO - More filetypes
"TODO - Move into a plugin to support prefs eg. `confirmations` or `conditions`
augroup whitespace_preferences
autocmd!
filetype on
" NOTE:
" `softtabstop` set to 0 disables it.
" `shiftwidth` set to 0 makes it use `tabstop` value.
autocmd FileType make setlocal tabstop=4 softtabstop=0 shiftwidth=0 noexpandtab
autocmd FileType yaml setlocal tabstop=2 softtabstop=2 shiftwidth=0 expandtab
autocmd FileType html,css,javascript,haskell
\ setlocal
\ tabstop=2
\ softtabstop=2
\ shiftwidth=2
\ expandtab
augroup end
" Disable my whitespace_trailing map/func (removes in entire buffer on save) in favor of
" the plugin 'axelf4/vim-strip-trailing-whitespace' that only removes
" white space on changed lines in buffer. To remove trailing whitespace in
" entire file use it's provided command :StripTrailingWhitespace instead.
" augroup whitespace_trailing
" autocmd!
" autocmd FileType c,cpp,java,php,js,twig,xml,yml,elm autocmd BufWritePre <buffer> call RemoveTrailingWhitespace()
" augroup end
" function! RemoveTrailingWhitespace ()
" call setline(1,map(getline(1,"$"),'substitute(v:val,"\\s\\+$","","")'))
" endfunction
"ABBREVIATIONS, TYPOS, ALIASES & CONCEALS {{{1
"Abbreviations & Typos
" Common `iabbrev`s like `iabbrev improt import` etc. moved to file recommended
" by `Abolish.vim`: `~/.vim/after/plugin/abolish.vim`
augroup elm_abbreviations
autocmd!
autocmd FileType elm abbreviate <buffer> :: :
augroup END