-
Notifications
You must be signed in to change notification settings - Fork 4
/
.vimrc
1733 lines (1434 loc) · 54.4 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
" Search this file for "important" for the most important lines
" =============================================================================
" ====
" =====
" ======
" Setup And Styles And Colors:
" ======
" =====
" ====
" ===
" =============================================================================
colorscheme vividchalk
set nocompatible
" Pathogen loading
filetype off
call pathogen#infect()
Helptags " Added to avoid having to manually install docs for plugins
filetype plugin indent on
" The "right" way to set color. Use `enable` because `on` will overwrite all
" other colors. Guard because no reason to call it more than once
if !exists("g:syntax_on")
syntax enable
endif
" Highlight column 80 and don't make it default bright red (needs to be done
" after syntax set)
highlight ColorColumn guibg=#331111
set colorcolumn=80
set cursorline
set novisualbell
" Make the cursor a thin line (not a block) and color it differently in insert
" and normal mode. Makes it WAY easier to see where the cursor is. This is the
" most important thing in this file
highlight Cursor guibg=#FF92BB guifg=#ffffff
highlight iCursor guibg=red
set guicursor=n-c:ver30-Cursor/lCursor,ve:ver35-Cursor,o:hor50-Cursor,i-ci:ver25-iCursor/lCursor,r-cr:hor20-Cursor/lCursor,v-sm:block-Cursor
" Highlight trailing whitespace in vim on non empty lines, but not while
" typing in insert mode. Super useful!
highlight ExtraWhitespace ctermbg=red guibg=Brown
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\S\zs\s\+$/
au InsertEnter * match ExtraWhitespace /\S\zs\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\S\zs\s\+$/
" Always show vim's tab bar
set showtabline=2
" =============================================================================
" ====
" =====
" ======
" Vanilla Vim Settings:
" ======
" =====
" ====
" ===
" =============================================================================
" Make all searches very magic. This is the most important thing in this file.
" Also mark the position before you start searching to copy text back to
nnoremap / ms/\v
nnoremap ? ms?\v
" Don't put two spaces after a period when joining lines with gq or J or
" whatever
set nojoinspaces
" Don't try to highlight lines longer than 800 characters.
set synmaxcol=800
" Always splits to the right and below, since Bram doesn't read left to right
set splitright
" This makes :help open at the bottom, which I don't like, so removing for now
"set splitbelow
" Custom file type syntax highlighting
au BufRead,BufNewFile .aprc set ft=ruby syntax=ruby
au BufRead,BufNewFile .pryrc set ft=ruby syntax=ruby
au BufRead,BufNewFile onboarding-tech-notes set ft=markdown syntax=markdown
au BufRead,BufNewFile .bash_config set ft=sh syntax=sh
au BufRead,BufNewFile .jshintrc set ft=javascript
au BufRead,BufNewFile .eslintrc set ft=javascript
au BufRead,BufNewFile *.json set ft=javascript
au BufRead,BufNewFile *.pryrc set ft=ruby
" Make all line substituions global (same as pattern/g) by default
set gdefault
" Store the GUI window position when making a vim session. I totally forgot
" Vim has a concept of "sessions" beacuse it's poorly designed and
" inconvenient to work with, so I never use this.
set sessionoptions+=winpos
" Don't want no lousy .swp files in my directoriez
set backupdir=/tmp
set directory=/tmp
" Hide buffers instead of closing, can do :e on an unsaved buffer
set hidden
" Add the "A" flag to shortmess, which means that when given an existing swap
" buffer warning, it won't demand that you press enter when the message is
" more than one line long.
set shortmess=filnxtToOA
" Wildignore all of these when autocompleting
set wig=*.swp,*.bak,*.pyc,*.class,node_modules*,*.ipr,*.iws,built,locallib
" Always snap to multiples of shiftwidth when using > and <
set shiftround
" You always, always want relativenumber on. This is most important thing in
" this file
setglobal relativenumber
" Use non-windows linebreaks. This command errors in modifiable off files, so
" suppress errors with silent :(
silent! set ff=unix
" Ignore caase in search, unless you type any capital letters, then it
" automatically switches to case sensitive search
set ignorecase
set smartcase
" Highlight search results
set hlsearch
" Live search while typing, shows matches before hitting enter
set incsearch
" GUI Vim (MacVim) configuraiton
" m = Always show menu bar(?)
" e = Always show nice GUI looking tabs, don't attempt to badly draw with
" vim's default tab setting
" r = Always show scrollbar
set guioptions=mer
" Use spaces always
set expandtab
" Copy indent from current line when starting a new line
set autoindent
" Break at specific characters when wrapping long lines (:set breakat?)
set lbr
" Give one virtual space at end of line so the cursor can go to the end of the
" line (useful)
set virtualedit=onemore
" Always have statusline so powerline shows up on non-split windows
set laststatus=2
" Include $ in varibale names, so viw works with jQuery variables
set iskeyword=@,48-57,_,192-255,#,$
" Backspace in normal mode: Act like normal backspace and go into insert mode
nnoremap <bs> i<bs>
" More commands in q: q/ etc (default is 50)
set history=200
" VIM LITERALLY CAN'T INDENT HTML AND THERE'S NO HELP FOR THIS VARIABLE NAME
" BUT LOOK AT :h html-indent **OBVIOUSLY**
let g:html_indent_inctags = "body,head,tbody,p"
" This does not work, obviously, it should make anything inside html tags not
" indented. myabe a plugin conflict?
let g:html_indent_autotags = "html"
" If you set the above variables, you have to call the below function IN THE
" HTML BUFFER after setting the global variables to get proper HTML
" indenting... come on Vim
" call HtmlIndent_CheckUserSettings()
" Jump to last known cursor position when opening file
" warning: This appears to break jump-to-line when opening a file with CtrlP
autocmd BufReadPost *
\ if line("'\"") > 0 && line ("'\"") <= line("$") |
\ exe "normal g'\"" |
\ endif
" In commit edit turn on spell check, make diff bigger, and switch to other
" window in insertmode
au BufNewFile,BufRead COMMIT_EDITMSG setlocal spell | DiffGitCached
" Equalize splits when the window is resized. I don't think I actually want
" this becasue it can mess up terminal vim when resizing the terminal when
" editing a git commit message, which has split of msg/code change
"au VimResized * :wincmd =
" Some experimental stuff
" Experimental to make command line completion easier?
set wildmenu
" Experimental make lines that wrap have same indenting as their parent
set breakindent
" Maybe I should remove these? Annoying when I'm in a 2 space project and have
" to manually set
set tabstop=4
set shiftwidth=4
set smarttab
" Disable C-style indenting. Experimental
set nocindent
" Set bottom indicator. Probably does nothing with vim-powerline
set ruler
set showcmd
" Why do I have this?
set path=.,/usr/include,$PWD
" =============================================================================
" ====
" =====
" ======
" Non Plugin Custom Key Mappings And Setup:
" ======
" =====
" ====
" ===
" =============================================================================
" Let mapleader be space. This is the most important line in this file
let mapleader = "\<Space>"
" In search mode, remove \v (very magic) with ctrl-v
cnoremap <C-v> <C-f>02l"zyg_:q<cr>/<c-r>za
" Title case a line or selection (doesn't work at all)
vnoremap <Leader>ti :s/\%V\<\(\w\)\(\w*\)\>/\u\1\L\2/ge<cr>
nnoremap <Leader>ti :s/.*/\L&/<bar>:s/\<./\u&/g<cr>
" Lets you do w!! to sudo write the file. I'd eventually like to fix this to
" not warn on file save that the file changed
nnoremap <Leader>ww :w !sudo tee % >/dev/null<cr>
" delete a line, but only copy a whitespace-trimmed version to " register
nnoremap <Leader>dd _yg_"_dd
nnoremap <Leader>yy _yg_
" underline a line with dashes or equals
nnoremap <Leader>r- :t.<cr>:norm 0vg_r-<cr>
nnoremap <Leader>r= :t.<cr>:norm 0vg_r=<cr>
" Clear search highlighting
nnoremap <silent> <Leader>/ :nohlsearch<CR>
" Source vim when this file is updated
nnoremap <Leader>sv :source $MYVIMRC<cr>
nnoremap <silent> <Leader>so :source %<cr>:echo "Sourced this file!"<cr>
" Quick file open shortcuts
nnoremap <Leader>b :tabe ~/.bashrc<cr>
nnoremap <Leader>v :tabe $MYVIMRC<cr>
nnoremap <Leader>ss :tabe ~/.vim/delvarworld-snippets/javascript/javascript.snippets<cr>
nnoremap <Leader>hs :tabe /etc/hosts<cr>:setlocal noreadonly<cr>:setlocal autoread<cr>
nnoremap <Leader>js :tabe ~/.jsl<cr>
" Copy current filename to system clipboard
nnoremap <Leader>yf :let @*=expand("%:t")<cr>:echo "Copied file name to clipboard"<cr>
" Copy current buffer path without filename to system clipboard
nnoremap <Leader>yd :let @*=expand("%:h")<cr>:echo "Copied file directory to clipboard"<cr>
" select last yanked / pasted text, using the [ marks (:h `[)
nnoremap <Leader>ht `[v`]
" select last paste in visual mode
nnoremap <expr> gb '`[' . strpart(getregtype(), 0, 1) . '`]'
" Change to working directory of current file and echo new location
nnoremap cd :cd %:h<cr>:pwd<cr>
" Prepare a file prefixed with the path of the current buffer
nmap <Leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
" Never, ever let vim look up the word under the cursor and ruin your life.
" Map to normal up
map K k
" Same with Q. Very bad and easy to type accidentally
nmap Q q
" Strip one layer of nesting
nnoremap <Leader>sn [{mzjV]}k<]}dd`zdd
" Alphabetize CSS rules if on mulitple lines
nnoremap <Leader>rs vi{:sort<cr>
" trim trailing whitespace
noremap <Leader>sw :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar>:nohl<CR>
" See ~/.gvimrc
" Execute VIM colon command under cursor with <⌘-e>
nnoremap <D-e> yy:<C-r>"<backspace><cr>
" Copy line to last changed postition
nnoremap <silent> <Leader>t. :t'.<cr>
vnoremap <silent> <Leader>t. :t'.<cr>
" copy last changed line here
nnoremap <silent> <Leader>t; :'.t.<cr>
vnoremap <silent> <Leader>t; :'.t.<cr>
" Make Y yank till end of line. Super useful. This is the most important thing
" in this file
nnoremap Y y$
" In command line mode use ctrl-direction to move instead of arrow keys. Super
" useful.
cnoremap <C-j> <t_kd>
cnoremap <C-k> <t_ku>
cnoremap <C-a> <Home>
cnoremap <C-e> <End>
" See also https://github.com/tpope/vim-rsi
" Ctrl-e: Go to end of line like bash and command mode
inoremap <c-e> <esc>A
" Ctrl-a: Go to start of line like bash and command mode
"inoremap <c-a> <esc>I
" Commenting this out to try using ctlr-a for inserting last inserted text
" Ctrl-h / l: Move left/right by word in command mode
cnoremap <c-h> <s-left>
cnoremap <c-l> <s-right>
" Same for insert mode, including up down
inoremap <c-h> <s-left>
inoremap <c-l> <s-right>
" Ctrl-j in insert mode: Move cursor down if autocomplete menu is closed
inoremap <expr> <c-j> pumvisible() ? "\<C-e>\<Down>" : "\<Down>"
" Ctrl-k in insert mode: Move cursor up if autocomplete menu is closed
inoremap <expr> <c-k> pumvisible() ? "\<C-e>\<Up>" : "\<Up>"
" use space to cycle between splits. I never use this garbage
"nmap <S-Space> <C-w>W
" Delete current buffer
nmap <Leader>bd :bdelete<CR>
" Map :W to :w (http://stackoverflow.com/questions/3878692/aliasing-a-command-in-vim)
cnoreabbrev <expr> W ((getcmdtype() is# ':' && getcmdline() is# 'W')?('w'):('W'))
" Map :H to :h
cnoreabbrev <expr> H ((getcmdtype() is# ':' && getcmdline() is# 'H')?('h'):('H'))
" Even with MacVim, Command-V to paste isn't repeatable. I have no idea what's
" up with that. This maps it to a normal Vim command and now I can repeat with
" . but I don't know why this fixes it
inoremenu Edit.Paste <C-r><C-p>*
" Jump backwards to previous function, assumes code is indented (useful when
" inside function)
nnoremap <Leader>ff ?^func\\|^[a-zA-Z].*func<CR>,/
" Faster tab switching. I never use these cause macvim lets me use
" command-shift-[ which is way nicer
"nnoremap <C-l> gt
"nnoremap <C-h> gT
nnoremap <C-L> <C-w>l
" Mark TODO item as complete
nnoremap <Leader>cp dd?❌\\|✅<cr>p0ls✅<esc><c-o>
nnoremap <Leader>cx dd?❌\\|✅<cr>p0ls❌<esc><c-o>
" experimental - enter to go into command mode (otherwise useless shortcut).
" See clickable_maps for preventing vim clickable from messing this up. Also
" see :h <cr> which is duplicated by BOTH ctrl-m AND + lol
" I never ended up using this
" nmap <CR> :
" Ray-Frame testing thingy
" nnoremap <Leader>x:tabe a.js
" =============================================================================
" ====
" =====
" ======
" Custom Functions And Hand Written Plugins:
" ======
" =====
" ====
" ===
" =============================================================================
"------------------------------------------------------------------------------
" CloseVimIfLastBufferIsQuickFix
" Quit vim if the only buffer open is the quickfix list. Vim is not "well
" designed" http://vim.wikia.com/wiki/Automatically_quit_Vim_if_quickfix_window_is_the_last
"------------------------------------------------------------------------------
function! CloseVimIfLastBufferIsQuickFix()
" if the window is quickfix go on
if &buftype=="quickfix"
" if this window is last on screen quit without warning
if winbufnr(2) == -1
quit!
endif
endif
endfunction
au BufEnter * call CloseVimIfLastBufferIsQuickFix()
"------------------------------------------------------------------------------
" FixVimSpellcheck
" Map z=, which normally opens a big useless list of suggested spelling
" corrections, to automatiaclly replace the word under the cursor with the
" first most likely spell suggestion, even if set spell is off
"------------------------------------------------------------------------------
function! FixVimSpellcheck()
if &spell
normal! 1z=
else
set spell
normal! 1z=
set nospell
endif
endfunction
nnoremap z= :call FixVimSpellcheck()<cr>
" While we're here, disable the zg (add to dictionary) shortcut, because it's
" awful functionality and I hit it all the time because who on earth remembers
" what zg and z= do
nnoremap zg z=
"------------------------------------------------------------------------------
" ToggleQuickFix
" There's no way to close the quickfix window without jumping to it and :q or
" whatever. That's bad. Let me close it from anywhere
"------------------------------------------------------------------------------
function! ToggleQuickFix()
if exists("g:qwindow")
cclose
execute "wincmd p"
unlet g:qwindow
else
try
copen
execute "wincmd J"
let g:qwindow = 1
catch
echo "Error!"
endtry
endif
endfunction
nnoremap <Leader>cq :call ToggleQuickFix()<CR>
"------------------------------------------------------------------------------
" TextEnableCodeSnip
" Highlight blocks of text as one syntax style with start/end markers
"------------------------------------------------------------------------------
" Garbage doesn't work yet http://vim.wikia.com/wiki/Different_syntax_highlighting_within_regions_of_a_file
function! TextEnableCodeSnip(filetype,start,end,textSnipHl) abort
let ft=toupper(a:filetype)
let group='textGroup'.ft
if exists('b:current_syntax')
let s:current_syntax=b:current_syntax
" Remove current syntax definition, as some syntax files (e.g. cpp.vim)
" do nothing if b:current_syntax is defined.
unlet b:current_syntax
endif
execute 'syntax include @'.group.' syntax/'.a:filetype.'.vim'
try
execute 'syntax include @'.group.' after/syntax/'.a:filetype.'.vim'
catch
endtry
if exists('s:current_syntax')
let b:current_syntax=s:current_syntax
else
unlet b:current_syntax
endif
execute 'syntax region textSnip'.ft.'
\ matchgroup='.a:textSnipHl.'
\ start="'.a:start.'" end="'.a:end.'"
\ contains=@'.group
endfunction
call TextEnableCodeSnip('ruby', '@begin=ruby@', '@end=ruby@', 'SpecialComment')
call TextEnableCodeSnip('glsl', '@begin=glsl@', '@end=glsl@', 'SpecialComment')
"------------------------------------------------------------------------------
" FixJumpChangeList
" I want g; (jump to older change) to only jump to the line if the change was
" far away (not on the same line)... I think. But this doesn't work.
"------------------------------------------------------------------------------
" this is a good start but not quite there yet, it goes in a loop
function! FixJumpChangeList()
redir @a
silent changes
redir end
let s:current_line = line('.')
let s:lines = reverse( split(@a, '\n') )
let s:idx = 1
let s:bail = min([ 10, len( s:lines ) ])
while s:idx < s:bail
let s:rows = split( s:lines[ s:idx ], '\s\+' )
if abs( s:rows[ 1 ] - s:current_line ) > 1
echo "Jumped to line " . s:rows[ 1 ] . " from " . s:current_line
execute "normal " . s:rows[ 1 ] . "G"
keepjumps execute "normal 0" . s:rows[ 2 ] . "l"
break
endif
let s:idx = s:idx + 1
endwhile
endfunction
nnoremap g; :call FixJumpChangeList()<cr>
"------------------------------------------------------------------------------
" Wipeout (helpful!)
" Remove non visible buffers
" From http://stackoverflow.com/questions/1534835/how-do-i-close-all-buffers-that-arent-shown-in-a-window-in-vim
"------------------------------------------------------------------------------
function! Wipeout()
"From tabpagebuflist() help, get a list of all buffers in all tabs
let tablist = []
for i in range(tabpagenr('$'))
call extend(tablist, tabpagebuflist(i + 1))
endfor
let nWipeouts = 0
for i in range(1, bufnr('$'))
if bufexists(i) && !getbufvar(i,"&mod") && index(tablist, i) == -1
"bufno exists AND isn't modified AND isn't in the list of buffers
"open in windows and tabs
silent exec 'bwipeout' i
let nWipeouts = nWipeouts + 1
endif
endfor
echomsg nWipeouts . ' buffer(s) wiped out'
endfunction
nnoremap <Leader>x :tabcl<cr>:call Wipeout()<cr>
"------------------------------------------------------------------------------
" ParagraphMove
" Fix vim's default { } motions by treating lines containing only whitespace
" as blank, so they aren't jumped to
" see http://stackoverflow.com/questions/1853025/make-and-ignore-lines-containing-only-whitespace
"------------------------------------------------------------------------------
function! ParagraphMove(delta, visual, count)
normal m'
normal |
if a:visual
normal gv
endif
if a:count == 0
let limit = 1
else
let limit = a:count
endif
let i = 0
while i < limit
if a:delta > 0
" first whitespace-only line following a non-whitespace character
let pos1 = search("\\S", "W")
let pos2 = search("^\\s*$", "W")
if pos1 == 0 || pos2 == 0
let pos = search("\\%$", "W")
endif
elseif a:delta < 0
" first whitespace-only line preceding a non-whitespace character
let pos1 = search("\\S", "bW")
let pos2 = search("^\\s*$", "bW")
if pos1 == 0 || pos2 == 0
let pos = search("\\%^", "bW")
endif
endif
let i += 1
endwhile
normal |
endfunction
nnoremap <silent> } :<C-U>call ParagraphMove( 1, 0, v:count)<CR>
nnoremap <silent> { :<C-U>call ParagraphMove(-1, 0, v:count)<CR>
"------------------------------------------------------------------------------
" EditConflictFiles
" Paired with the "vc" function in my .bashrc. This loads all files that Git
" has marked as conflicts (during merge/rebase/cherry-pick etc) into the
" arglist, and loads all conflict markers (<<<<<<<<) etc into the quickfix
" list, so you can easily jump between them
"------------------------------------------------------------------------------
function! EditConflictFiles()
let filter = system('git diff --name-only --diff-filter=U')
let conflicted = split( filter, '\n')
let massaged = []
for conflict in conflicted
let tmp = substitute(conflict, '\_s\+', '', 'g')
if len( tmp ) > 0
call add( massaged, tmp )
endif
endfor
call ProcessConflictFiles( massaged )
endfunction
function! EditConflitedArgs()
call ProcessConflictFiles( argv() )
endfunction
" Experimental function to load vim with all conflicted files
function! ProcessConflictFiles( conflictFiles )
" These will be conflict files to edit
let conflicts = []
" Read git attributes file into a string
silent! let gitignore = readfile('.gitattributes')
let ignored = []
for ig in gitignore
" Remove any extra things like -diff (this could be improved to
" actually use some syntax to know which files ot ignore, like check
" if [1] == 'diff' ?
let spl = split( ig, ' ' )
if len( spl ) > 0
call add( ignored, spl[0] )
endif
endfor
" Loop over each file in the arglist (passed in to vim from bash)
for conflict in a:conflictFiles
" If this file is not ignored in gitattributes (this could be improved)
if index( ignored, conflict ) < 0
" Grep each file for the starting error marker
let cmd = system("grep -n '<<<<<<<' ".conflict)
" Remove the first line (grep command) and split on linebreak
let markers = split( cmd, '\n' )
for marker in markers
let spl = split( marker, ':' )
" If this line had a colon in it (otherwise it's an empty line
" from command output)
if len( spl ) == 2
" Get the line number by removing the white space around
" it
let line = substitute(spl[0], '\_s\+', '', 'g')
" Add this file to the list with the data format for the quickfix
" window
call add( conflicts, {'filename': conflict, 'lnum': line, 'text': spl[1]} )
endif
endfor
endif
endfor
" Set the quickfix files and open the list
call setqflist( conflicts )
execute 'copen'
execute 'cfirst'
" Highlight diff markers and then party
highlight Conflict guifg=white guibg=red
match Conflict /^=\{7}.*\|^>\{7}.*\|^<\{7}.*/
echom "Use ]n or [n to navigate to conflict markers with vim-unimpaired"
endfunction
"------------------------------------------------------------------------------
" TabMove
" Move a tab left or right with a keystroke. Pretty strange this isn't in Vim
" by default
"------------------------------------------------------------------------------
" @param direction -1 for left, 1 for right.
function! TabMove(direction)
let s:current_tab = tabpagenr()
let s:total_tabs = tabpagenr("$")
" Wrap to end
if s:current_tab == 1 && a:direction == -1
tabmove
" Wrap to start
elseif s:current_tab == s:total_tabs && a:direction == 1
tabmove 0
" Normal move
else
execute (a:direction > 0 ? "+" : "-") . "tabmove"
endif
echo "Moved to tab " . tabpagenr() . " (previosuly " . s:current_tab . ")"
endfunction
" Move tab left or right
map <D-H> :call TabMove(-1)<CR>
map <D-L> :call TabMove(1)<CR>
"------------------------------------------------------------------------------
" FormatX
" Attempts to format and properly indent different types of files. Like if you
" have a big indented JSON string, run :call FormatJson()<cr> and this
" attempts to format it. These work pretty poorly and I should probably
" replace with a command line tool and never, ever use Vim for things like
" this
"------------------------------------------------------------------------------
function! FormatPerlObj()
silent! exec '%s/\v\S+\s*\=\>\s*[^,]*,/\0\r'
silent! exec '%s/\v\S+\s*\=\>\s*\{/\0\r'
silent! exec '%s/\v[^{]\zs\},/\r\0'
normal vie=
exec 'set ft=perl'
endfunction
function! FormatJson()
silent! exec '%s/\v\S+\s*:\s*[^,]*,/\0\r'
silent! exec '%s/\v\S+\s*:\s*\{/\0\r'
silent! exec '%s/\v[^{]\zs\},/\r\0'
normal vie=
exec 'set ft=javascript'
endfunction
function! FormatVarList()
silent! exec '%s/\v\S+\s*\=\>\s*[^,]*,/\0\r'
silent! exec '%s/\v\S+\s*\=\>\s*\{/\0\r'
silent! exec '%s/\v[^{]\zs\},/\r\0'
normal vie=
exec 'set ft=perl'
endfunction
function! FormatAdiumLogs()
silent! exec '%g/\vleft the room/d'
silent! exec '%g/\ventered the room/d'
silent! exec '%s/\v time\="[^"]+"\>\<div\>\<span style\="[^"]+"//'
normal vie=
exec 'set ft=html'
endfunction
function! FormatHtml()
silent! exec '%s/\v\>\</\>\r\<'
normal vie=
exec 'set ft=html'
endfunction
"------------------------------------------------------------------------------
" JumpToWebpackError
" Uhhh...ignore this one probably. I don't even remember writing it
"------------------------------------------------------------------------------
function! JumpToWebpackError()
let cmd = system("node ./find_webpack_error.js")
let place = split( cmd, ' ' )
exe ":tabe " . place[0]
endfunction
nnoremap <leader>fw :call JumpToWebpackError()<cr>
"------------------------------------------------------------------------------
" HandleURI
" Open a URL-looking thing with the system "open" command, which opens it in
" the default browser. Note this doesn't conflict with vim-clickable, but
" clickable gives you this by default
"------------------------------------------------------------------------------
function! HandleURI()
let s:uri = matchstr(getline("."), '[a-z]*:\/\/[^ >,;:]*')
echo s:uri
if s:uri != ""
exec "!open \"" . s:uri . "\""
else
echo "No URI found in line."
endif
endfunction
nnoremap <Leader>op :call HandleURI()<CR>
"------------------------------------------------------------------------------
" ToggleRelativeAbsoluteNumber
" Toggle relative / line number. I never use this garbage
"------------------------------------------------------------------------------
function! ToggleRelativeAbsoluteNumber()
if &number
set relativenumber
else
set number
endif
endfunction
nnoremap <leader>rl :call ToggleRelativeAbsoluteNumber()<CR>
"------------------------------------------------------------------------------
" Refactor
" Locally (local to block) rename a variable. Every day I want Vim to be an
" IDE, but it will always be a text editor
"------------------------------------------------------------------------------
function! Refactor()
call inputsave()
let @z=input("What do you want to rename '" . @z . "' to? ")
call inputrestore()
endfunction
nnoremap <Leader>rf "zyiw:call Refactor()<cr>mx:silent! norm gd<cr>:silent! norm [{<cr>$V%:s/<C-R>//<c-r>z/g<cr>`x
"------------------------------------------------------------------------------
" VSetSearch
" Let * and # search for next/previous of selected text when you have text
" selected in visual mode (you want this)
"------------------------------------------------------------------------------
function! s:VSetSearch()
let old = @"
norm! gvy
let @/ = '\V' . substitute(escape(@", '\'), '\n', '\\n', 'g')
let @" = old
endfunction
vnoremap * :<C-u>call <SID>VSetSearch()<CR>/<CR>
vnoremap # :<C-u>call <SID>VSetSearch()<CR>?<CR>
"------------------------------------------------------------------------------
" Highlight Word
" This mini-plugin provides a few mappings for highlighting words temporarily.
" Sometimes you're looking at a hairy piece of code and would like a certain
" word or two to stand out temporarily. You can search for it, but that only
" gives you one color of highlighting. Now you can use <leader>N where N is
" a number from 1-6 to highlight the current word in a specific color.
"------------------------------------------------------------------------------
function! HiInterestingWord(n)
" Save our location.
normal! mz
" Yank the current word into the z register.
normal! "zyiw
" Calculate an arbitrary match ID. Hopefully nothing else is using it.
let mid = 86750 + a:n
" Clear existing matches, but don't worry if they don't exist.
silent! call matchdelete(mid)
" Construct a literal pattern that has to match at boundaries.
let pat = '\V\<' . escape(@z, '\') . '\>'
" Actually match the words.
call matchadd("InterestingWord" . a:n, pat, 1, mid)
" Move back to our original location.
normal! `z
endfunction
" Clear all matches
function! TurnOffInterestingHighlight()
let mid = 86750
silent! call matchdelete(mid + 1)
silent! call matchdelete(mid + 2)
silent! call matchdelete(mid + 3)
silent! call matchdelete(mid + 4)
silent! call matchdelete(mid + 5)
silent! call matchdelete(mid + 6)
endfunction
hi def InterestingWord1 guifg=#000000 ctermfg=16 guibg=#ffa724 ctermbg=214
hi def InterestingWord2 guifg=#000000 ctermfg=16 guibg=#aeee00 ctermbg=154
hi def InterestingWord3 guifg=#000000 ctermfg=16 guibg=#8cffba ctermbg=121
hi def InterestingWord4 guifg=#000000 ctermfg=16 guibg=#b88853 ctermbg=137
hi def InterestingWord5 guifg=#000000 ctermfg=16 guibg=#ff9eb8 ctermbg=211
hi def InterestingWord6 guifg=#000000 ctermfg=16 guibg=#ff2c4b ctermbg=195
nnoremap <silent> <leader>h1 :call HiInterestingWord(1)<cr>
nnoremap <silent> <leader>h2 :call HiInterestingWord(2)<cr>
nnoremap <silent> <leader>h3 :call HiInterestingWord(3)<cr>
nnoremap <silent> <leader>h4 :call HiInterestingWord(4)<cr>
nnoremap <silent> <leader>h5 :call HiInterestingWord(5)<cr>
nnoremap <silent> <leader>h6 :call HiInterestingWord(6)<cr>
" Turn off above
nnoremap <silent> <leader>hx :call TurnOffInterestingHighlight()<cr>
nnoremap <silent> <leader>h0 :call TurnOffInterestingHighlight()<cr>
nnoremap <silent> <leader>hd :call TurnOffInterestingHighlight()<cr>
"------------------------------------------------------------------------------
" AttemptToSwapTwoThings
" Everyone wants the most efficient way to swap two pieces of text in Vim.
" This is my attempt to guess at what the user wants to swpa
"------------------------------------------------------------------------------
function! AttemptToSwapTwoThings()
let l:lastSearch = @/
" Search backwards for an opening brace, but only on current line
let l:match = search('\v[({<[]', 'b', line("."))
" If there was no match (opening brace), jump to the first non-blank char
if !l:match
normal g^
else
normal w
endif
" Go to the first thing to match and mark
execute "normal! mz"
" Set search for dividing character, or the closing brace
let @/ = '\v\s*\zs([,/)\]>}\-+:]|(\.|as|in|\|\|?|\&\&?|\?|\=)\s)|$|;'
" select and yank till that dividng character into z
execute "normal vnge\"zy"
" go past diving character to the next thing and mark y
execute "normal! nwmy"
" paste z in place of second thing. second thing now in paste register
execute "normal! vnge\"zp"
" go back to first word
execute "normal! `z"
" select first word until old match, then paste
execute "normal! vngep"
let @/ = l:lastSearch
execute "normal :nohlsearch\<cr>"
endfunction
function! AttemptToSwapThingsInVisualMode()
let l:lastSearch = @/
" Go to the first thing to match and mark
execute "normal! \<Esc>`<mz`>mx`z"
" Set search for dividing character, or the closing brace
let @/ = '\v\s*\zs([,/)\]>}\-+:]|(\.|as|in|\|\|?|\&\&?|\?|\=)\s)|$|;'
" select and yank till that dividng character into z
execute "normal vnge\"zy"
" go past diving character to the next thing and mark y
execute "normal! nwmy"
" paste z in place of second thing. second thing now in paste register
execute "normal! vnge\"zp"
" go back to first word
execute "normal! `z"
" select first word until old match, then paste
execute "normal! vngep"
let @/ = l:lastSearch
execute "normal :nohlsearch\<cr>"
execute "normal `zv`x"
endfunction
" Swap two parameters in a function
nnoremap <Leader>- :call AttemptToSwapTwoThings()<cr>
vnoremap <Leader>- :call AttemptToSwapThingsInVisualMode()<cr>
"------------------------------------------------------------------------------
" DimInactiveWindows
" Since it's usually hard to tell where the Vim cursor is when using splits,
" set the background color of splits you're not focused on to a "dimmed"
" color. Note for some reason on command line vim, the color is bright red
"------------------------------------------------------------------------------
function! s:DimInactiveWindows()
for i in range(1, tabpagewinnr(tabpagenr(), '$'))
let l:range = "80"
if i != winnr()
if &wrap
" HACK: when wrapping lines is enabled, we use the maximum number
" of columns getting highlighted. This might get calculated by
" looking for the longest visible line and using a multiple of
" winwidth().
let l:width=256 " max
else
let l:width=winwidth(i)
endif
let l:range = join(range(1, l:width), ',')
endif
call setwinvar(i, '&colorcolumn', l:range)
endfor
endfunction
augroup DimInactiveWindows
au!
au WinEnter * call s:DimInactiveWindows()
augroup END
"------------------------------------------------------------------------------
" MyTabLine
" Attempt to show what folder files are in (doesn't work)
"------------------------------------------------------------------------------
"function! MyTabLine()