-
Notifications
You must be signed in to change notification settings - Fork 158
/
.vimrc
executable file
·2390 lines (1758 loc) · 73.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
set encoding=utf-8
"=====[ Enable italics in MacOS Terminal ]=======================
let &t_ZH="\e[3m"
let &t_ZR="\e[23m"
"=====[ Avoid modeline vulnerability ]===========================
set nomodeline
"=====[ Not a fan of mapleader mappings ]===========================
let mapleader = '_'
"=====[ Reduce HETC requests ]===========================
set shm=at
"=====[ Convert to Unicode defaults ]===============================
setglobal termencoding=utf-8 fileencodings=
scriptencoding utf-8
set encoding=utf-8
autocmd BufNewFile,BufRead * try
autocmd BufNewFile,BufRead * set encoding=utf-8
autocmd BufNewFile,BufRead * endtry
"====[ Ensure autodoc'd plugins are supported ]===========
runtime plugin/_autodoc.vim
"====[ Work out what kind of file this is ]========
filetype plugin indent on
augroup FiletypeInference
autocmd!
autocmd BufNewFile,BufRead *.t setfiletype perl
autocmd BufNewFile,BufRead *.pod setfiletype pod
autocmd BufNewFile,BufRead *.itn setfiletype itn
autocmd BufNewFile,BufRead * call s:infer_filetype()
augroup END
function! s:infer_filetype ()
for line in getline(1,20)
if line =~ '^\s*use\s*v\?5\.\S\+\s*;\s*$'
setfiletype perl
return
elseif line =~ '^\s*use\s*v\?6\s*;\s*$'
setfiletype raku
return
elseif line =~ '^\s*use\s*v\?\%([7-9]|\d\{2,}\)\s*;\s*$'
setfiletype perl
call Stop_ALE()
return
endif
endfor
endfunction
"=====[ Comments are important ]==================
highlight Comment term=bold cterm=italic ctermfg=white gui=italic guifg=white
"Star-space or dash-space is a bullet
set comments=fb:*,fb:-
"=====[ Enable Nmap command for documented mappings ]================
runtime plugin/documap.vim
"====[ Edit and auto-update this config file and plugins ]==========
augroup VimReload
autocmd!
autocmd BufWritePost $MYVIMRC nested source $MYVIMRC
augroup END
Nmap <silent> ;v [Edit .vimrc] :next $MYVIMRC<CR>
Nmap ;vv [Edit .vim/plugin/...] :next ~/.vim/plugin/
"====[ Edit my temporary working files ]====================
"Nmap tt [Edit temporary files] :next ~/tmp/temporary_file
"=====[ Edit files in local bin directory ]========
Nmap ;b [Edit ~/bin/...] :next ~/bin/
"=====[ Some of Vim's defaults are just annoying ]============
" :read and :write shouldn't set #
set cpo-=aA
" Make /g the default on :s/.../../ commands (use /gg to disable)
"set gdefault
" Join lines with a single space only (even after sentence terminators)
set nojoinspaces
"=====[ Make diffs better ]=====================
" Prefer vertical orientation when using :diffsplit
set diffopt+=vertical
" No | in the vertical separator
set fillchars=vert:\ ,fold:-
" Use a smarter diff, if available...
if has('nvim-0.3.2') || has("patch-8.1.0360")
set diffopt=vertical,filler,internal,algorithm:histogram,indent-heuristic
endif
"====[ Go back to alternate file (but retain other g<whatever> mappings)]====
nmap g :w<CR>:e #<CR><CR>
function! s:conditional_nnoremap ( name )
if maparg(a:name, 'n') == ""
execute 'nnoremap <unique> ' . a:name . ' ' . a:name
endif
endfunction
call s:conditional_nnoremap( 'g,' )
call s:conditional_nnoremap( 'g;' )
call s:conditional_nnoremap( 'g~' )
call s:conditional_nnoremap( 'g~~' )
call s:conditional_nnoremap( 'g~g~' )
call s:conditional_nnoremap( 'g#' )
call s:conditional_nnoremap( 'g$' )
call s:conditional_nnoremap( 'g&' )
call s:conditional_nnoremap( "g'" )
call s:conditional_nnoremap( 'g*' )
call s:conditional_nnoremap( 'g0' )
call s:conditional_nnoremap( 'g8' )
call s:conditional_nnoremap( 'g<' )
call s:conditional_nnoremap( 'g<C-G>' )
call s:conditional_nnoremap( 'g<C-H>' )
call s:conditional_nnoremap( 'g<C-]>' )
call s:conditional_nnoremap( 'g<Down>' )
call s:conditional_nnoremap( 'g<End>' )
call s:conditional_nnoremap( 'g<Home>' )
call s:conditional_nnoremap( 'g<LeftMouse>' )
call s:conditional_nnoremap( 'g<MiddleMouse>' )
call s:conditional_nnoremap( 'g<RightMouse>' )
call s:conditional_nnoremap( 'g<Up>' )
call s:conditional_nnoremap( 'g?' )
call s:conditional_nnoremap( 'g??' )
call s:conditional_nnoremap( 'g?g?' )
call s:conditional_nnoremap( 'g@' )
call s:conditional_nnoremap( 'gD' )
call s:conditional_nnoremap( 'gE' )
call s:conditional_nnoremap( 'gF' )
call s:conditional_nnoremap( 'gH' )
call s:conditional_nnoremap( 'gI' )
call s:conditional_nnoremap( 'gJ' )
call s:conditional_nnoremap( 'gP' )
call s:conditional_nnoremap( 'gR' )
call s:conditional_nnoremap( 'gU' )
call s:conditional_nnoremap( 'gUU' )
call s:conditional_nnoremap( 'gUgU' )
call s:conditional_nnoremap( 'gV' )
call s:conditional_nnoremap( 'g]' )
call s:conditional_nnoremap( 'g^' )
call s:conditional_nnoremap( 'g`' )
call s:conditional_nnoremap( 'ga' )
call s:conditional_nnoremap( 'gd' )
call s:conditional_nnoremap( 'ge' )
call s:conditional_nnoremap( 'gf' )
call s:conditional_nnoremap( 'gg' )
call s:conditional_nnoremap( 'gh' )
call s:conditional_nnoremap( 'gi' )
call s:conditional_nnoremap( 'gj' )
call s:conditional_nnoremap( 'gk' )
call s:conditional_nnoremap( 'gm' )
call s:conditional_nnoremap( 'go' )
call s:conditional_nnoremap( 'gp' )
call s:conditional_nnoremap( 'gq' )
call s:conditional_nnoremap( 'gr' )
call s:conditional_nnoremap( 'gs' )
call s:conditional_nnoremap( 'gu' )
call s:conditional_nnoremap( 'gugu' )
call s:conditional_nnoremap( 'guu' )
call s:conditional_nnoremap( 'gv' )
call s:conditional_nnoremap( 'gw' )
"call s:conditional_nnoremap( 'gx' )
" Make gn jump into visual block mode, instead if plain visual mode
nnoremap gn gn<C-V>
"====[ Use persistent undo ]=================
if has('persistent_undo')
" Save all undo files in a single location (less messy, more risky)...
set undodir=$HOME/.VIM_UNDO_FILES
" Save a lot of back-history...
set undolevels=5000
" Actually switch on persistent undo
set undofile
endif
"====[ Goto last location in non-empty files ]=======
autocmd BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$")
\| exe "normal! g`\""
\| endif
"====[ Toggle visibility of naughty characters ]============
" Make naughty characters visible...
set lcs=tab:══»,trail:␣,nbsp:˷
" Tabs shown thusly and so
" Trailing whitespace
" Non-breaking space
highlight InvisibleSpaces ctermfg=Black ctermbg=Black
call matchadd('InvisibleSpaces', '\S\@<=\s\+\%#\ze\s*$')
augroup VisibleNaughtiness
autocmd!
autocmd BufEnter * set list
autocmd BufEnter * set list
autocmd BufEnter *.txt set nolist
autocmd BufEnter *.vp* set nolist
autocmd BufEnter * if !&modifiable
autocmd BufEnter * set nolist
autocmd BufEnter * endif
augroup END
"====[ Set up smarter search behaviour ]=======================
set incsearch "Lookahead as search pattern is specified
set ignorecase "Ignore case in all searches...
set smartcase "...unless uppercase letters used
set hlsearch "Highlight all matches
highlight clear Search
highlight Search ctermfg=White ctermbg=Black cterm=bold
highlight IncSearch ctermfg=White ctermbg=Red cterm=bold
" Absolute direction for n and N...
nnoremap <silent><expr> n 'Nn'[v:searchforward] . ":call HLNext()\<CR>"
nnoremap <silent><expr> N 'nN'[v:searchforward] . ":call HLNext()\<CR>"
"Delete in normal mode to switch off highlighting till next search and clear messages...
Nmap <silent> <BS> [Cancel highlighting] :call HLNextOff() <BAR> :nohlsearch <BAR> :call VG_Show_CursorColumn('off')<CR>
"Double-delete to remove trailing whitespace...
Nmap <silent> <BS><BS> [Remove trailing whitespace] mz:call TrimTrailingWS()<CR>`z
function! TrimTrailingWS ()
if search('\s\+$', 'cnw')
:%s/\s\+$//g
endif
endfunction
"====[ Set background hint (if possible) ]=============
"if $VIMBACKGROUND != ""
" exec 'set background=' . $VIMBACKGROUND
"else
" set background=dark
"endif
set background=dark
"=====[ Enable smartwrapping ]==================================
" No smartwrapping in any of these files...
"let g:SW_IGNORE_FILES = '.vimrc,*.vim,*.pl,*.pm,**/bin/**'
set wrapmargin=2 "Wrap 2 characters from the edge of the window
"set cinwords = "" "But not for C-like keywords
set cinoptions+=#1
set cinkeys-=0#
"=======[ Select formatting options explicitly ]=========================
set formatoptions=tnbl1jcro
" t : Auto-wrap text using textwidth.
" n : When formatting text, recognize numbered lists.
" b : Only auto-wrap if you enter a blank at or before the wrap margin.
" l : Already long lines are not broken in insert mode.
" 1 : Don't break a line after a one-letter word.
" j : Remove a comment leader when joining lines.
" c : Auto-wrap comments using textwidth, inserting the current comment leader automatically.
" r : Automatically insert the current comment leader after hitting <Enter> in Insert mode.
" o : Automatically insert the current comment leader after hitting 'o' or 'O' in Normal mode.
function! BufSetFOA ()
" if empty(&filetype) || &filetype == 'text'
" set formatoptions+=a
" set textwidth=79
" endif
endfunction
" Turn on autoreformating of paragraphs in text files...
augroup Autoreindent
autocmd!
autocmd BufReadPost * call BufSetFOA()
augroup END
"=======[ Indentation ]============
set autoindent "Retain indentation on next line
filetype plugin indent on
"====[ I hate modelines ]===================
set modelines=0
"=====[ Quicker access to Ex commands ]==================
nmap ; :
xmap ; :
"=====[ Make Visual modes work better ]==================
" Visual Block mode is far more useful that Visual mode (so swap the commands)...
nnoremap v <C-V>
nnoremap <C-V> v
xnoremap v <C-V>
xnoremap <C-V> v
"Square up visual selections...
set virtualedit=block
" Make BS/DEL work as expected in visual modes (i.e. delete the selected text)...
xmap <BS> x
" Make vaa select the entire file...
xmap aa VGo1G
" Make q extend to the surrounding string...
xmap q "_y:call ExtendVisualString()<CR>
let s:closematch = [ '', '', '}', ']', ')', '>', '/', "'", '"', '`' ]
let s:ldelim = '\< \%(q [qwrx]\= \| [smy] \| tr \) \s*
\ \%(
\ \({\) \| \(\[\) \| \((\) \| \(<\) \| \(/\)
\ \)
\ \|
\ \(''\) \| \("\) \| \(`\)
\'
let s:ldelim = substitute(s:ldelim, '\s\+', '', 'g')
function! ExtendVisualString ()
let [lline, lcol, lmatch] = searchpos(s:ldelim, 'bWp')
if lline == 0
return
endif
let rdelim = s:closematch[lmatch]
normal `>
let rmatch = searchpos(rdelim, 'W')
normal! v
call cursor(lline, lcol)
endfunction
"=====[ Make arrow keys move visual blocks around ]======================
xmap <silent> <UP> <Plug>SchleppUp
xmap <silent> <DOWN> <Plug>SchleppDown
xmap <silent> <S-UP> <Plug>SchleppIndentUp
xmap <silent> <S-DOWN> <Plug>SchleppIndentDown
xmap <silent> <LEFT> <Plug>SchleppLeft
xmap <silent> <RIGHT> <Plug>SchleppRight
xmap <silent> D <Plug>SchleppDupLeft
xmap <silent> <C-D> <Plug>SchleppDupLeft
"=====[ Demo vim commands ]==============================
highlight WHITE_ON_BLACK ctermfg=white
Nmap <silent> ;; [Demonstrate Vimscript block] :call DemoCommand()<CR>
xnoremap <silent> ;; :<C-U>call DemoCommand(1)<CR>
function! DemoCommand (...)
" Remember how everything was before we did this...
let orig_buffer = getline('w0','w$')
let orig_match = matcharg(1)
" Select either the visual region, or the current paragraph...
if a:0
let @@ = join(getline("'<","'>"), "\n")
else
silent normal vipy
endif
" Highlight the selection in red to give feedback...
let matchid = matchadd('WHITE_ON_RED','\%V')
redraw
sleep 500m
" Remove continuations and convert shell commands, then execute...
let command = @@
let command = substitute(command, '^\s*".\{-}\n', '', 'g')
let command = substitute(command, '\n\s*\\', ' ', 'g')
let command = substitute(command, '^\s*>\s', ':! ', '' )
execute command
" If the buffer changed, hold the highlighting an extra second...
if getline('w0','w$') != orig_buffer
redraw
sleep 1000m
endif
" Remove the highlighting...
call matchdelete(matchid)
endfunction
"=====[ Configure % key (via matchit plugin) ]==============================
" Match angle brackets...
set matchpairs+=<:>,«:»,「:」
"=====[ Miscellaneous features (mainly options) ]=====================
set title "Show filename in titlebar of window
set titleold=
"set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:~:.:h\")})%)%(\ %a%)
set title titlestring=
set nomore "Don't page long listings
set cpoptions-=a "Don't set # after a :read
set autowrite "Save buffer automatically when changing files
set autoread "Always reload buffer when external changes detected
" +--Disable hlsearch while loading viminfo
" | +--Remember marks for last 500 files
" | | +--Remember up to 10000 lines in each register
" | | | +--Remember up to 1MB in each register
" | | | | +--Remember last 1000 search patterns
" | | | | | +---Remember last 1000 commands
" | | | | | |
" v v v v v v
set viminfo=h,'500,<10000,s1000,/1000,:1000
set backspace=indent,eol,start "BS past autoindents, line boundaries,
" and even the start of insertion
set fileformats=unix,mac,dos "Handle Mac and DOS line-endings
"but prefer Unix endings
set wildignorecase "Case-insensitive completions
set wildmode=list:longest,full "Show list of completions
" and complete as much as possible,
" then iterate full completions
set complete-=t " I don't use tags, so no need to search for them
set infercase "Adjust completions to match case
set noshowmode "Suppress mode change messages
set updatecount=10 "Save buffer every 10 chars typed
" Keycodes and maps timeout in 3/10 sec...
set timeout timeoutlen=300 ttimeoutlen=300
" "idleness" is 0.5 sec
set updatetime=500
set thesaurus+=~/Documents/thesaurus "Add thesaurus file for ^X^T
set dictionary+=~/Documents/dictionary "Add dictionary file for ^X^K
set scrolloff=2 "Scroll when 3 lines from top/bottom
"====[ Simplify textfile backups ]============================================
" Back up the current file
Nmap BB [Back up current file] :!bak -q %<CR><CR>:echomsg "Backed up" expand('%')<CR>
"=====[ Remap various keys to something more useful ]========================
" Use space to jump down a page (like browsers do)...
nnoremap <Space> <PageDown>
xnoremap <Space> <PageDown>
" Install current file and swap to alternate file...
Nmap IP [Install current file and swap to alternate] :!install -f %<CR>
" Add *** as **/* on command-line...
cmap *** **/*
" Shift-Tab in visual mode to number lines...
xnoremap <S-TAB> :s/\%V/0<C-V><TAB>/<CR>gvg<C-A>gv:retab<ESC>gvI<C-G>u<ESC>gv/ <CR>:s/\%V /./<CR>
" Take off and nuke the entire buffer contents from space
" (It's the only way to be sure)...
nnoremap <expr> XX ClearBuffer()
function! ClearBuffer ()
if &filetype =~ 'perl\|raku'
return "1Gj}dGA\<CR>\<CR>\<ESC>"
else
return '1GdG'
endif
endfunction
" Replace the current buffer with a copy of the most recent file...
nmap RR 1GdG:0r#<CR><C-G>
" Insert cut marks...
nmap -- A<CR><CR><CR><ESC>k6i-----cut-----<ESC><CR>
" Indent/outdent current block...
nmap %% $>i}``
nmap $$ $<i}``
" =====[ Perl programming support ]===========================
augroup PerlIndentedSchlepp
autocmd!
autocmd Filetype perl let b:Schlepp_reindent = 1
augroup END
augroup PerlKeywordChars
autocmd!
autocmd Filetype perl setlocal iskeyword=@,48-57,_,192-255,$,%,@-@,:,#
autocmd Filetype raku setlocal iskeyword=@,48-57,_,192-255,$,%,@-@,:,-
augroup END
augroup PerlSignColumn
autocmd!
autocmd Filetype * setlocal signcolumn=no
autocmd Filetype perl setlocal signcolumn=yes
augroup END
" Execute Perl file...
nmap <silent> W :!clear;echo;echo;(script -q ~/tmp/script_$$ motleyperl %; if (-s ~/tmp/script_$$) then; alert; echo; echo; echo; getraw; endif; rm -f ~/tmp/script_$$ )<CR><CR>
" Execute Perl file (output to pager)...
nmap E :!motleyperl -m %<CR>
augroup PerlTestFile
autocmd!
autocmd BufEnter *.t nmap <silent><buffer> W :!clear;echo;echo;(script -q ~/tmp/script_$$ polyperl %; if (-s ~/tmp/script_$$) then; alert; echo; echo; echo; getraw; endif; rm -f ~/tmp/script_$$ )<CR><CR>
autocmd BufEnter *.t nmap <silent><buffer> E :!polyperl -m %<CR>
augroup END
" Execute Perl file (in debugger)...
nmap Q :!polyperl -d %<CR>
" Execute Perl file (in regex debugger)...
nmap ;r :!rxrx %<CR>
" Format file with perltidy...
Nmap ;p [Perltidy the current buffer] 1G!Gperltidy<CR>
" Show what changes perltidy would make...
Nmap ;pp [Perltidy to the current buffer (as a diff)] :call Perltidy_diff()<CR>
function! Perltidy_diff ()
" Work out what the tidied file will be called...
let perl_file = expand( '%' )
let tidy_file = perl_file . '.tdy'
call system( 'perltidy -nst ' . perl_file . ' -o ' . tidy_file )
" Add the diff to the right of the current window...
set splitright
exe ":vertical diffsplit " . tidy_file
" Clean up the tidied version...
call delete(tidy_file)
endfunction
" Run perldoc with smarter completion...
Nmap <expr> ?? [Go to documentation] CallPerldoc()
set keywordprg=pd
function! CallPerldoc ()
" When editing Vim files, revert to :help...
if &filetype == 'vim' || &buftype == 'help'
return ":help "
" Otherwise use Perldoc...
else
let target = matchstr(expand('<cfile>'), '\w\+\(::\w\+\)*')
set wildmode=list:full
return ":Perldoc "
endif
endfunction
"Complete perldoc requests with names of installed Perl modules
command! -nargs=? -complete=customlist,CompletePerlModuleNames Perldoc call Perldoc_impl(<q-args>)
"Undo the special wildmoding and then execute the requested perdoc lookup...
function! Perldoc_impl (args)
set wildmode=list:longest,full
if empty(a:args)
exec '!pd %'
else
exec '!pd ' . a:args
endif
endfunction
" Compile the list of installed Perl modules (and include the name under the cursor)...
let s:module_files = readfile($HOME.'/.vim/perlmodules')
function! CompletePerlModuleNames(prefix, cmdline, curpos)
let cfile = expand('<cfile>')
let prefix = a:prefix
if prefix == cfile
let prefix = ""
endif
if empty(prefix) && cfile =~ '^\w\+\(::\w\+\)*$'
return [cfile] + filter(copy(s:module_files), 'v:val =~ ''\c\_^' . prefix. "'")
else
return filter(copy(s:module_files), 'v:val =~ ''\c\_^' . prefix. "'")
endif
endfunction
" Handle Perl include files better...
"set include=^\\s*use\\s\\+\\zs\\k\\+\\ze
"set includeexpr=substitute(v:fname,'::','/','g')
"set suffixesadd=.pm
"execute 'set path+=' . substitute($PERL5LIB, ':', ',', 'g')
" Insert common Perl code structures...
iab udx use Data::Dx; Dx
nmap dx A<CR>use Data::Dx; Dx;<LEFT>
iab udd use Data::Dump 'ddx'; ddx
iab uds use Data::Show; show
iab urd use Regexp::Debugger;
iab udv use Dumpvalue;<CR>Dumpvalue->new->dumpValues();<ESC>hi
iab uds use Data::Show;<CR>show
iab ubm use Benchmark qw( cmpthese );<CR><CR>cmpthese -10, {<CR>};<ESC>O
iab usc use Smart::Comments;<CR>###
iab uts use Test::Simple 'no_plan';
iab utm use Test::More 'no_plan';
iab dbs { no warnings 'once'; $DB::single = 1; }<ESC>
"=====[ Emphasize typical mistakes in Vim and Perl files ]=========
" Add a new high-visibility highlight combination...
highlight WHITE_ON_RED ctermfg=White ctermbg=Red cterm=bold
" Emphasize typical mistakes a Perl hacker makes in .vim files...
let g:VimMistakes
\ = '\_^\s*\zs\%(my\s\+\)\?\%(\k:\)\?\k\+\%(\[.\{-}\]\)\?\s*[+-.]\?=[=>~]\@!'
\ . '\|'
\ . '\_^\s*\zselsif'
\ . '\|'
\ . ';\s*\_$'
\ . '\|'
\ . '\_^\s*\zs#.*'
\ . '\|'
\ . '\_^\s*\zs\k\+('
let g:Mistakes = {
\ 'vim' : g:VimMistakes,
\}
let g:MistakesID = 668
augroup Mistakes
autocmd!
autocmd BufEnter *.vim,*.vimrc call s:Mistakes_AddMatch()
autocmd BufLeave *.vim,*.vimrc call s:Mistakes_ClearMatch()
augroup END
function! s:Mistakes_AddMatch () abort
call s:Mistakes_ClearMatch()
try | call matchadd('WHITE_ON_RED',g:Mistakes[&filetype],10,g:MistakesID) | catch | endtry
endfunction
function! s:Mistakes_ClearMatch () abort
for next_match in getmatches()
if next_match['id'] == g:MistakesID
try | silent call matchdelete(g:MistakesID) | catch | redraw | endtry
break
endif
endfor
endfunction
"=====[ Call :make and then perltests from within a Perl buffer ]========
let &errorformat .= ",%f:%l %tarning:%m,%f:%l:%m"
set makeprg=polyperl\ -vc\ %\ $*
function! RunPerlTests ()
if !empty(filter(getqflist(),{idx, val -> get(val,'type',"") == ''}))
echohl WarningMsg
echo "Errors detected, so won't run tests."
echohl NONE
silent cc 1
return
endif
" Start in the current directory...
let dir = expand('%:h')
" Walk up through parent directories, looking for a test directory...
for n in range(g:PerlTests_search_height)
" When found...
if isdirectory(dir . g:PerlTests_test_dir)
" Go there...
silent exec 'cd ' . dir
" Run the tests...
exec ':!' . g:PerlTests_program
" Return to the previous directory...
silent cd -
return
endif
" Otherwise, keep looking up the directory tree...
let dir = dir . '/..'
endfor
" If not found, report the failure...
echohl WarningMsg
echomsg "Couldn't find a suitable" g:PerlTests_test_dir '(tried' g:PerlTests_search_height 'levels up)'
echohl None
endfunction
"autocmd BufEnter *.p[lm],*.t call SetupPerlTesting()
"function! SetupPerlTesting ()
"endfunction
autocmd BufEnter *.p[lm],*.t let g:PerlTests_program = 'perltests'
autocmd BufEnter *.pm6,*.p6,*.raku* let g:PerlTests_program = 'prove6'
let g:PerlTests_search_height = 5 " ...How far up the file hierarchy to search
let g:PerlTests_test_dir = '/t' " ...Where to look for tests
augroup PerlMake
autocmd!
autocmd BufReadPost quickfix setlocal number
\ | setlocal nowrap
\ | setlocal modifiable
\ | silent! %s/^[^|]*\//.../
\ | setlocal nomodifiable
augroup END
Nmap <silent> ;t [Test this code] :call RunPerlTests()<CR>
"=====[ Placeholder data for templates (for the file_templates.vim plugin) ]=====
let g:FileTemplatesInfo = {
\ 'AUTH' : 'cpan:DCONWAY',
\ 'AUTHOR' : 'Damian Conway',
\ 'EMAIL' : 'DCONWAY@cpan.org',
\}
"=====[ Proper syntax highlighting for Rakudo files ]===========
autocmd BufNewFile,BufRead * :call CheckForRaku()
function! CheckForRaku ()
if getline(1) =~ 'rakudo'
setfiletype raku
endif
if expand('<afile>:e') =~ 'rakudoc\|rakutest'
setfiletype rakutest
endif
endfunction
" =====[ Smart completion via <TAB> and <S-TAB> ]=============
runtime plugin/smartcom.vim
" Add extra completions (mainly for Perl programming)...
let ANYTHING = ""
let NOTHING = ""
let EOL = '\s*$'
" Left Right Insert Reset cursor
" ===== ===== =============================== ============
call SmartcomAdd( '<<', ANYTHING, "\<BS>\<BS>«" )
call SmartcomAdd( '>>', ANYTHING, "\<BS>\<BS>»" )
call SmartcomAdd( '?', ANYTHING, '?', {'restore':1} )
call SmartcomAdd( '?', '?', "\<CR>\<ESC>O\<TAB>" )
call SmartcomAdd( '{{', ANYTHING, '}}', {'restore':1} )
call SmartcomAdd( '{{', '}}', NOTHING, )
call SmartcomAdd( 'qr{', ANYTHING, '}xms', {'restore':1} )
call SmartcomAdd( 'qr{', '}xms', "\<CR>\<C-D>\<ESC>O\<C-D>\<TAB>" )
call SmartcomAdd( 'm{', ANYTHING, '}xms', {'restore':1} )
call SmartcomAdd( 'm{', '}xms', "\<CR>\<C-D>\<ESC>O\<C-D>\<TAB>", )
call SmartcomAdd( 's{', ANYTHING, '}{}xms', {'restore':1} )
call SmartcomAdd( 's{', '}{}xms', "\<CR>\<C-D>\<ESC>O\<C-D>\<TAB>", )
call SmartcomAdd( '\*\*', ANYTHING, '**', {'restore':1} )
call SmartcomAdd( '\*\*', '\*\*', NOTHING, )
" Handle single : correctly...
call SmartcomAdd( '^:\|[^:]:', EOL, "\<TAB>" )
" In the middle of a keyword: delete the rest of the keyword before completing...
" Left Right Insert
" ===== ===== =======================
"call SmartcomAdd( '\k', '\k\+\%(\k\|\n\)\@!', "\<C-O>cw\<C-X>\<C-N>", )
"call SmartcomAdd( '\k', '\k\+\_$', "\<C-O>cw\<C-X>\<C-N>", )
"After an alignable, align...
function! AlignOnPat (pat)
return "\<ESC>:call EQAS_Align('nmap',{'pattern':'" . a:pat . "'})\<CR>A"
endfunction
" Left Right Insert
" ========== ===== =============================
call SmartcomAdd( '=', ANYTHING, "\<ESC>:call EQAS_Align('nmap')\<CR>A")
call SmartcomAdd( '=>', ANYTHING, AlignOnPat('=>') )
call SmartcomAdd( '\s#', ANYTHING, AlignOnPat('\%(\S\s*\)\@<= #') )
call SmartcomAdd( '[''"]\s*:', ANYTHING, AlignOnPat(':'), {'filetype':'vim'} )
call SmartcomAdd( ':', ANYTHING, "\<TAB>", {'filetype':'vim'} )
" Left Right Insert Where
" ========== ===== ============================= ===================
" Vim keywords...
call SmartcomAdd( '^\s*func\%[tion]',
\ EOL, "\<C-W>function!\<CR>endfunction\<UP> ", {'filetype':'vim'} )
call SmartcomAdd( '^\s*for', EOL, " … in …\n…\n\<C-D>endfor\n…", {'filetype':'vim'} )
call SmartcomAdd( '^\s*if', EOL, " … \n…\n\<C-D>endif\n…", {'filetype':'vim'} )
call SmartcomAdd( '^\s*while', EOL, " … \n…\n\<C-D>endwhile\n…", {'filetype':'vim'} )
call SmartcomAdd( '^\s*try', EOL, "\n\t…\n\<C-D>catch\n\t…\n\<C-D>endtry\n…", {'filetype':'vim'} )
" Left Right Insert Where
" ========== ===== ============================= ===================
" Perl keywords...
call SmartcomAdd( '^\s*for', EOL, " my $… (…) {\n…\n}\n…", {' filetype':'perl'} )
call SmartcomAdd( '^\s*if', EOL, " (…) {\n…\n}\n…", {' filetype':'perl'} )
call SmartcomAdd( '^\s*while', EOL, " (…) {\n…\n}\n…", {' filetype':'perl'} )
call SmartcomAdd( '^\s*given', EOL, " (…) {\n…\n}\n…", {' filetype':'perl'} )
call SmartcomAdd( '^\s*when', EOL, " (…) {\n…\n}\n…", {' filetype':'perl'} )
call SmartcomAdd( '^\s*sub', EOL, " … (…) {\n…\n}\n…", {' filetype':'perl'} )
" Complete Perl module loads with the names of Perl modules...
call SmartcomAddAction( '^\s*use\s\+\k\+', "",
\ 'set complete=k~/.vim/perlmodules|setlocal iskeyword+=:'
\)
" .itn itinerary files...
let s:flight_template = "\t…\nOn: \t…\nFrom:\t…\nTo: \t…\nDepart:\t…\nDTerm:\t…\nArrive:\t…\nATerm:\t…\nLength:\t…\nClass:\t…\nSeat:\t…\nBRef:\t…\nTrans:\t…\n"
let s:hotel_template = "\t…\nAddr:\t…\nPhone:\t…\nZone:\t…\nRate:\t…\nConfNo:\t…\n\nName:\t…\nEmail:\t…\nPhone:\t…\n"
let s:event_template = "\t…\nTime:\t…\nVenue:\t…\n"
" Left Right Insert Where
" ========== ===== ===================== ===================
call SmartcomAdd( '^\s*Date:', EOL, "\t…\nSumm:\t…\n", {'filetype':'itn'} )
call SmartcomAdd( '^\s*Flight:', EOL, s:flight_template, {'filetype':'itn'} )
call SmartcomAdd( '^\s*Bus:', EOL, s:flight_template, {'filetype':'itn'} )
call SmartcomAdd( '^\s*Train:', EOL, s:flight_template, {'filetype':'itn'} )
call SmartcomAdd( '^\s*Hotel:', EOL, s:hotel_template, {'filetype':'itn'} )
call SmartcomAdd( '^\s*Event:', EOL , s:event_template, {'filetype':'itn'} )
call SmartcomAdd( '^\s*Keynote:', EOL , s:event_template, {'filetype':'itn'} )
call SmartcomAdd( '^\s*Talk:', EOL , s:event_template, {'filetype':'itn'} )
call SmartcomAdd( '^\s*Course:', EOL , s:event_template, {'filetype':'itn'} )
"=====[ Itinerary generation ]===========
autocmd BufNewFile,BufRead *.itn nnoremap zd !!gen_itinerary_dates<CR>
"=====[ Miscellaneous completions ]============
call SmartcomAdd( 'Frederic', ANYTHING, "\<ESC>c?F\<CR>Frédéri\<RIGHT>", {} )
"=====[ General programming support ]===================================
" Insert various shebang lines...
iab hbc #! /bin/csh
iab hbs #! /bin/sh
iab hbp #! /usr/bin/env polyperl<CR>use 5.020;<CR>use warnings;<CR>use experimentals;<CR>
iab hbr #! /usr/bin/env raku<CR>use v6;
" Execute current file polymorphically...
Nmap ,, [Execute current file] :w<CR>:!clear;echo;echo;run %<CR>
Nmap ,,, [Debug current file] :w<CR>:!clear;echo;echo;run -d %<CR>
"=====[ Show help files in a new tab, plus add a shortcut for helpg ]==============
let g:help_in_tabs = 1
"nmap <silent> H :let g:help_in_tabs = !g:help_in_tabs<CR>
"Only apply to .txt files...
augroup HelpInTabs
autocmd!
autocmd BufEnter *.txt call HelpInNewTab()
augroup END
"Only apply to help files...
function! HelpInNewTab ()
if &buftype == 'help' && g:help_in_tabs
"Convert the help window to a tab...
execute "normal \<C-W>T"
endif
endfunction
"Simulate a regular cmap, but only if the expansion starts at column 1...
function! CommandExpandAtCol1 (from, to)
if strlen(getcmdline()) || getcmdtype() != ':'
return a:from
else
return a:to
endif
endfunction
"Expand hh -> helpg...
cmap <expr> hh CommandExpandAtCol1('hh','helpg ')
"=====[ Cut and paste from the system clipboard ]====================
" When in Normal mode, paste over the current line...
nmap <C-P> 0d$"+p
" When in Visual mode, paste over the selected region...
xmap <C-P> "+pgv
" In Normal mode, yank the entire buffer...
nmap <C-C> 1G"+yG``:call YankedToClipboard()<CR>
" In Visual mode, yank the selection...
xmap <C-C> "+y:call YankedToClipboard()<CR>
xmap <C-Y> "+y:call YankedToClipboard()<CR>
function! YankedToClipboard ()
let block_of = (visualmode() == "\<C-V>" ? 'block of ' : '')
let N = strlen(substitute(@*, '[^\n]\|\n$', '', 'g')) + 1
let lines = (N == 1 ? 'line' : 'lines')
redraw
echo block_of . N lines 'yanked to clipboard'
endfunction
"=====[ Convert file to different tabspacings ]=====================
function! InferTabspacing ()
return min(filter(map(getline(1,'$'),'strlen(matchstr(v:val, ''^\s\+''))'),'v:val != 0'))
endfunction