-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.vimrc
executable file
·1999 lines (1819 loc) · 68.3 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
" Strip trailing whitespace on save:
augroup striptrailing
autocmd!
autocmd BufWritePre * :exec (&syntax!="snippets" && ShouldStripTrailing()==1)? '%s/\s\+$//e' : ""
augroup END
augroup reloadReadOnly
autocmd!
" This will automatically reload any buffers for which `autoread` has
" been :set :
autocmd CursorHold * checktime
augroup END
" Compatibility settings 1{{{
:set nocompatible
" **NOTE**: It's important to set `term` first because setting it can (at
" least on certain systems) undo custom keycode definitions (the ones like
" `set <C-Left> = b`)
let term=$TERM
if term == 'screen' || term == "screen-256color" || term == "xterm-256color"
" if running from `screen`, assume xterm-signals:
:set term=xterm
endif
:set <A-a>=a
:set <A-b>=b
:set <A-c>=c
:set <A-d>=d
:set <A-e>=e
:set <A-g>=g
:set <A-o>=o
:set <A-p>=p
:set <A-r>=r
:set <A-s>=s
:set <A-=>==
:set <A-w>=w
:set <A-x>=x
:set <A-z>=z
:set <A-(>=9
:set <A-)>=0
:set <A-1>=1
:set <A-i>=i
:set <C-S-g>=
:set <C-J>=
:set ttimeout
:set ttimeoutlen=100
" ^ 2: This prevents the above key-codes from being easily confused by Esc
" being pressed followed promptly (but not instantaneously) by another
" key; without this setting leaving insert mode by pressing Esc followed
" promptly (though perhaps not instantaneously) by a keystroke meant to be
" received by normal mode can cause strange characters or other weird
" nonsense to be processed
if match(system("uname -a"),"Darwin")==0
" iTerm2 settings (comment) 2{{{
" Profiles -> Keys -> General:
" Allow application keypad mode
" xterm control sequence can enable modifyOtherKeys mode
" Left Option key = Esc+
" Profiles -> Keys -> Key Mappings
" optionLeft = Send Escape Sequence Esc+b
" optionRight= Send Escape Sequence Esc+f
" Profiles -> Text -> Font
" Menlo regular 18
" General -> Selection
" Copy to pasteboard on selection
" Applications in terminal may access clipboard
" Other stuff (to allow ctrlUp and ctrlDown to work):
" Desktop and Dock -> Shortcuts ("Keyboard and Mouse Shortcuts" via
" search)
" Mission Control = (Hotkey disabled)
" Application windows = (Hotkey disabled)
" }}}
set <A-d>=á
set <A-f>=æ
set <A-q>=ñ
" 2: ctrlLeft and ctrlRight seem to get trapped completely (nothing
" gets sent) so we just assign optionLeft and optionRight:
set <C-Left>=â
set <C-Right>=f
else
:set <A-f>=f
:set <A-q>=q
:set <S-Left>=[D
:set <S-Right>=[C
:set <C-Left>=OD
:set <C-Right>=OC
:set <C-A-p>=
:set <C-A-q>=
:set <C-A-t>=
:set <C-A-x>=
endif
" }}}
" Custom handling by filetype 1{{{
"
augroup oddboyz
autocmd!
autocmd BufNewFile,BufRead, pom.xml,web.xml,*.yaml,*.ansible* setlocal tabstop=2 expandtab shiftwidth=2
augroup END
augroup ansible
autocmd BufNewFile,BufRead, *.ansible* setf yaml.ansible
augroup END
augroup gitconfigs
autocmd!
autocmd BufNewFile,BufRead, .gitconfig* setf gitconfig
augroup END
augroup screenstuff
autocmd!
autocmd BufNewFile,BufRead, *.screen,.screenrc* setf screen
augroup END
" allow various comments to rewrap correctly:
augroup vimstuff
autocmd!
autocmd BufNewFile,BufRead, *.vim,.vimrc setlocal foldmethod=marker modeline
" If vim is in its very own tab, with no other panes in that tab, open the FoldDigest pane at a
" reasonable size
autocmd BufWinEnter .vimrc if tabpagewinnr(tabpagenr(),'$') == 1 && winnr('$') == 1 | call FoldDigest() | silent Resize -h 45 endif
autocmd BufNewFile,BufRead, *.vim,.vimrc setlocal comments+=:\\\\|
augroup END
augroup pgstuff
autocmd!
autocmd BufNewFile,BufRead, *.postgre.sql,scp://*.postgre.sql setf pgsql
\| setlocal comments=:--
augroup END
augroup ultistuff
autocmd!
autocmd BufNewFile,BufRead, *.snippets setlocal comments=:#
augroup END
" }}}
" Conventions 1{{{
" Conventions: marks and registers
"
" Sophisticated macros may naturally require storage of clipboard or
" cursor-location info, but perfect data-hiding is impractical, as it would
" require making a function-call in every macro. So instead, I'll lay out some
" conventions for how to store data:
"
" register 's': used to temporarily hold the contents of the default register '"'
" in some cases this is unavoidable because of `diw` and similar
"
" Otherwise, register 'p' is used instead of the default register to avoid
" overwriting it in the first place. This should theoretically be used more
" often than register 's'.
"
" mark '`' is used to temporarily store the last cursor position in macros
" mark 'w' is an alternate for the same purpose
" mark 'u' is a secondary alternate for the same purpose
" Conventions: character-representations
"
" I won't explain the full spec here but here are some expamples of how
" plain-english macro explanations should look (the ones chosen are nonsense so
" they don't turn up when I'm searching for my real boys):
"
" " one-key deletes everything in the buffer:
" nnoremap 1 GVggx
"
" " F1-key starts help-search:
" nnoremap <F1> :h
" imap <F1> <C-o><F1>
"
" " one-then-two deletes everything in the buffer, saves, and quits:
" nnoremap 21 GVggx:wq<Return>
"
" " ctrlW-then-shiftW is the same as undo:
" nnoremap <C-w>W u
"
" The following characters might have ambiguous names so here's what I'll use
" when describing macros:
"
" { openbrace
" } closebrace
" ( openparen
" ) closeparen
" " quote
" ' apostrophe
" < lessThan
" > greaterThan
" 1 one
" 2 two
" 3 three
" 4 four
" 5 five
" 6 six
" 7 seven
" 8 eight
" 9 nine
" 0 zero
"
" Conventions: function-names
" I use the convention "before" in function names to connote one CHARACTER before
" In turn "after" means the opposite.
" To connote the LINE before the cursor's current position, I use "above".
" In turn "below" means the opposite.
" }}}
" Plugin Settings and Imports 1{{{
filetype plugin on
source ~/.vim/plugin/cmdalias.vim
if !empty(glob("~/.vimrc2"))
source ~/.vimrc2
endif
" Cutlass overrides/settings 2{{{
" We have to apply this mapping before pathogen loads cutlass:
vnoremap d ""d
" }}}2
let g:pathogen_blacklist = []
if has('signs') != 1
call add(g:pathogen_blacklist, 'vim-bookmarks')
echom "vim-bookmarks is not supported on this system"
else
let g:bookmark_sign = '🔖'
endif
let s:copilot = 0
" If nodejs is not available, or it's an older version of vim, don't
" try to load Copilot.
silent let njs = system("nodejs --version")
if v:shell_error || v:version < 900
" ^ Note: `has('patch-9.0-0185')` should work according to
" vi.stackexchange.com/questions/2466 but it doesn't seem to, so the
" above is slightly imprecise; a few versions of vim 9.0 won't work,
" which will have to be caught by the extension itself
call add(g:pathogen_blacklist, 'copilot.vim')
echom "copilot requires vim >=9.0.0185 and access to nodejs " .. v:shell_error .. njs
" nodejs will typically break under WSL 1 so it's necessary to
" upgrade to 2. Sufficiently-modern versions of vim begin to
" appear under WSL Ubuntu 24.04.1 LTS and up.
else
let s:copilot = 1
endif
" grab everything from ~/.vim/bundle:
execute pathogen#infect()
runtime macros/matchit.vim " allow jumping to matching XML tags using '%'
" Copilot settings 2{{{
" Info about the free tier of Copilot:
" * 2,000 code suggestions per month
" * 50 Copilot chat messages per month
" * Choice of Claude 3.5 Sonnet and GPT 4o
" * Copilot extensions like Perplexity web-search
" * 'Copilot Edits' for edits across multiple files
" altLeft while in insert mode to scrub forward along suggestion
" (built-in)
if s:copilot == 1
" altA accepts whole Copilot suggestion:
imap <silent><script><expr> <A-a> copilot#Accept("\<CR>")
let g:copilot_no_tab_map = v:true
" if ! exists('g:copilot_workspace_folders')
" let g:copilot_workspace_folders = ['~/.copilot_context']
" endif
" ^ At least for SQL files, doing this did not appear to have any
" effect. Perhaps in the future, this will be resolved, but for
" the moment, copilot.vim requires hacks.
augroup copilot
autocmd!
" Start vim with Copilot disabled:
autocmd VimEnter * :Copilot disable
" When a new buffer is opened or we leave insert mode, disable
" Copilot:
autocmd BufNew,BufRead * :let b:copilot_enabled = v:false
" Since both temporarily pausing insert mode (ctrlO) to perform
" other actions and leaving insert mode wholesale both trigger
" InsertLeave, we check which one has just occurred before we
" switch Copilot off:
autocmd InsertLeave * if match(mode('full'),'^ni')==-1 | let b:copilot_enabled = v:false | endif
autocmd InsertEnter * let g:normal_mode_time=0
augroup end
" c-key enters insert-mode with Copilot turned on:
nnoremap ci :Copilot enable<Return>:let b:copilot_enabled=v:true<Return>i
" c-then-k enters insert-mode with Copilot turned on using the k-key
" mapping:
nmap ck :Copilot enable<Return>:let b:copilot_enabled=v:true<Return>k
" c-then-a enters insert-mode with Copilot turned on by using the
" a-key mapping:
nmap ca :Copilot enable<Return>:let b:copilot_enabled=v:true<Return>a
" c-then-shiftA enters insert-mode with Copilot turned on by using
" the shiftA mapping:
nmap cA :Copilot enable<Return>:let b:copilot_enabled=v:true<Return>A
endif
" }}}2
" Ultisnips config: 2{{{
" altQ expands snippet:
let g:UltiSnipsExpandTrigger="<A-q>"
" tab-key moves to next tabstop while snippets are active:
let g:UltiSnipsJumpForwardTrigger="<tab>"
" shiftTab moves to previous tabstop while snippets are active:
let g:UltiSnipsJumpBackwardTrigger="[Z"
let g:UltiSnipsEditSplit="vertical"
" }}}2
" Netrw config: 2{{{
let g:netrw_banner=0
" make netrw splits happen to the right (doesn't work with preview-splits,
" even if they're set vertical :C):
" let g:netrw_altv=1
" }}}2
" Taboo config: 2{{{
" This isn't technically a Taboo setting, but doing this per the repo's
" README allows tab names to be retained when using `:mksession`
set sessionoptions+=tabpages,globals
" }}}2
" EightHeader config 2{{{
" This makes fold-headers look a bit nicer, by using '.' as a
" fill-character, indenting according to the fold-level, and also
" indicating the indent-level with a leading number. e.g.:
" 2 EightHeader config ................................10 lines
let &foldtext = "EightHeaderFolds( '\\=s:fullwidth-2', 'left', [ repeat(' ', v:foldlevel - 1), '.', '' ], '\\= s:foldlines . \" lines\"', '\\=substitute(s:str,\"^\\\\(.*\\\\)\\\\([0-9]\\\\)$\",\"\\\\2 \\\\1\",\"\")' )"
" NOTE: If this addon ever breaks, a custom function can just be
" provided to the `foldtext` setting to override the default value
" which causes the built-in `foldtext()` to be invoked. It'll take a
" little bit of extra work, since EightHeader takes care of some
" basics for us, but it shouldn't be too bad. Maybe I could even try
" to expose the innards of a given header by making it multi-line.
" }}}2
" Folddigest config 2{{{
let folddigest_options="vertical,nofoldclose,flexnumwidth"
" }}}2
" }}}1
" User settings 1{{{
" Display 2{{{
colorscheme koyae
" 4: Only turn on syntax highlighting once; this avoids turning
" highlighting off when viewing/editing an unrecognized filetype for which
" the user has already manually performed `set syntax=<syntax>` or `set
" filetype=<filetype>`:
if !exists('g:koyaeSyntaxEnabled')
syntax enable
let g:koyaeSyntaxEnabled = 1
endif " :4
let g:is_posix=1 " this will be right on 99% of systems
if exists('+breakindent')
:set breakindent
" ^ paragraphs moved all the way over if there's an indent in front
" (long line soft wrap)
endif
:set linebreak " whole-word wrapping instead of mid-word
:set foldmethod=marker
" }}}2
" I/O 2{{{
:set bs=2
:set mouse=n
:set scrolloff=0
:set noincsearch " no incremental search; makes me think i hit enter already
:set ttymouse=sgr
:set gdefault " find-and-replace defaults to global rather than just current line
:set autoindent " keep the current indentation on new <CR>. Negate with :setlocal noautoindent
:set splitright " make :vs open on right instead of bumping current pane over
:set splitbelow " make :split open files on the bottom instead of bumping current pane down
:set tabstop=4 " make tab-characters display as 4 spaces instead of default 8
:set shiftwidth=0 " make '>' (angle bracket) always just match `tabstop`
:set ignorecase smartcase "searching is non-case-sensitive unless there's a cap
:set shellcmdflag=-c
" }}}
" Formatting behavior 2 {{{
:set formatoptions+=j " allow vim's re-wrapping functionality to join as well as split
" 3: wrap python-style arg-docs
:set formatoptions+=n
:set formatoptions-=2 " having the 2 flag set prevents n from working
:set formatlistpat=^\\s\*[a-z-][a-z_0-9-]\\+[^-]\*\ \ --\ \ " :3 *
" ^ * the end-of-line comment here is functional since it prevents the
" trailing whitespace from being stripped
" Disable highlighting of non-capitalized words that follow periods; IMO
" this is so noisy that it hurts more than it helps:
:hi SpellCap none
" }}}2
" cmdalias.vim aliases (vanilla): 2{{{
:Alias Wq wq
:Alias WQ wq
:Alias qw wq
:Alias Q q
:Alias w W
" }}}2
" Custom commands 2{{{
:command! ArgTranspose call TransposeArgs()
:command! -nargs=? W call RobustSave(<f-args>)
:command! Reup source ~/.vimrc
:Alias reup Reup
" Create a new tab with the desired help-page inside of it:
:command! -nargs=1 Tabh tab h <args>
:Alias tabh Tabh
:command! -nargs=+ Resize call Resize(<f-args>) " TODO: handle percents. https://www.reddit.com/r/vim/comments/3m85zo/resizing_splits_as_a_percentage_in_macvim/
:command! Hoh set hlsearch
:Alias hoh Hoh
" Count the number of commas on the current line:
:command! Comman keeppattern s/,//n
" Run vim's grep in a new tab if necessary:
:command! -nargs=+ Grep execute (&modified)? "tabe" : "" | grep <args>
Alias grep Grep
:command! Grepr Grep -r <args> .
Alias grepr Grepr
:command! -nargs=+ Greprt tabe | grep -r <args> .
Alias greprt Greprt
:command! -range=% Imply <line1>,<line2>s/^./>\0/ | noh
" Soft-yank a line (or line-range) and then immediately paste it at the
" cursor's current position:
:command! -range Yp <line1>,<line2>y p | normal! "pP
Alias yp Yp
" ^ This won't correct to 'Yp' on <Return> or <Space> but it will correct on
" <Tab> so to yank-then-paste the line above it would be :-1yp<Tab>
" Turn tabs into spaces for either the current line, or the lines indicated
" using the preceding range-syntax:
:command! -range Poof setlocal expandtab | <line1>,<line2>retab! | setlocal noexpandtab
" This command prefixes/prepends the given text to the beginning of the
" selected lines, or all lines, if it's invoked with no selection:
:command! -range=% -nargs=+ Beg silent <line1>,<line2>call InsertAtBeginning(<f-args>)
Alias beg Beg
" Copy path to current file into default register #current path
:command! Cpath let @"=escape(expand('%:p'),' \')
Alias cpath Cpath
" Change the current working directory to that of the current file:
command! Nowat lcd %:p:h
Alias nowat Nowat
Alias ulti UltiSnipsEdit
command! Comred hi Comment ctermfg=Red
" Grab either the lefthand side or righthand side of a nearby line and paste
" it to the current line:
:command! -range Lhs :normal! mw<line1>gg^"pyf=`w"pp<Return>
Alias lhs Lhs
:command! -range Rhs :normal! mw<line1>gg^f=l"py$`w"pp<Return>
Alias rhs Rhs
:command! -range Dp <line1>m .
:Alias dp Dp
" }}}2
" }}} 1
" Functions 1{{{
" Note `function!` forces overwrite if necessary on creation of a funciton
if ! exists('*ShouldStripTrailing')
" On certain systems, this may be defined in .vimrc2 already
function ShouldStripTrailing()
return 1
endfunction
endif
" SuSave([path [,escape]])
"
" path -- the path to which the current buffer should be saved. If
" omitted, this defaults to whatever the current save-path
" already is.
" escape -- 1 or 0 indicating whether the path should be escaped for use
" on the shell or not. If omitted, it's assumed this is not
" needed and has already been done.
function! SuSave(...)
" Code adapted from vim.fandom.com/wiki/Su-write
let path=expand("%:p")
let escapePath=0
if a:0 > 0
let path=a:1
if a:0 > 1
let escapePath=a:2
endif
else
let escapePath=1
endif
if escapePath==1
let path=shellescape(path)
endif
let fname=tempname()
exec 'w ' . fnameescape(fname)
let owners=GetOwners(path)
let modes=GetPermissions(path)
silent exec '!sudo cp' shellescape(fname) path
call SetAccess(path, modes, owners)
endfunction
" GetOwners(filePath)
" It's assumed filePath is already shellescape()'d
function! GetOwners(filePath)
return shellescape(system('stat --printf=%U:%G ' . a:filePath))
endfunction
" GetPermissions(filePath)
" It's assumed filePath is already shellescape()'d
function! GetPermissions(filePath)
return system('stat -c%a ' . a:filePath . ' | tr -d "\n"')
endfunction
" Adjust the ownership and permissions-bits of a given file.
"
" target -- path to the file to work on. This should already be
" shellescaped()'d
" modes -- chmod mode-bits to set e.g. 600 or 0600. Pass an empty
" string if you don't care about mode
" owners -- first argument to chown. This can be either the name of a
" single user or <userName>:<groupName> if you wish to set
" both. Pass an empty string if you don't care about ownership
function! SetAccess(targetFile, modes, owners)
if a:modes
silent exec '!sudo' "chmod" a:modes a:targetFile
endif
if a:owners
silent exec '!sudo' "chown" a:owners a:targetFile
endif
endfunction
" Prepare a given vim-style SCP-path for use with real SCP. Cygwin doesn't
" seem to need this but Ubuntu does.
function! SCPify(targetPath)
let rval = a:targetPath
if match(rval,'^scp://[a-z_0-9]\+//.*')!=-1
let rval = substitute(rval,'^scp://','','')
let rval = substitute(rval,'//',':/','')
endif
return rval
endfunction
" RobustSave([targetPath])
" A (somewhat) robust wrapper for :W and :sav that avoids
" https://github.com/vim/vim/issues/1268 if SCP-paths contain spaces, which
" also uses AsyncRun to perform network writes, preventing Vim from
" temporarily hanging/freezing while waiting on IO on slow connections.
"
" targetPath -- the path to which the buffer-contents should be written
"
" If you wish to save both a local file and a remote file every time this
" function is called, you can set the value of b:robustsave_alt_path. For example:
" let b:robustsave_alt_path = getcwd() .. '/' .. substitute(expand('%:t'),'\\ ',' ','')
" Assuming the current buffer is pointed at a remote SCP address with a
" space in the path, this will take that basename, unescape the spaces
function! RobustSave(...)
let naturalpath = expand('%:p')
let path = naturalpath
if a:0 == 1
let path = expand(a:1)
endif
if ( match(path, "scp://") == 0 )
" ^ if the remote filename might cause problems with how netrw tries to
" invoke scp, correct before saving:
let tmpfile = exists('b:robustsave_alt_path') ?
\ b:robustsave_alt_path
\ : exists('b:netrw_tmpfile') ?
\ b:netrw_tmpfile
\ : escape(tempname(),' ')
execute "write! " . tmpfile
" Replace any space that is not proceded by a backslash with the
" literal: '\ ':
let path = shellescape(substitute(SCPify(path), '\(\\\)\@<! ', '\\ ', 'g'))
let l:doMe='AsyncRun'
\ . ' -post=echo\ "delayed\ write"\ g:asyncrun_status\ strftime(''\%X'')'
\ . '\ |\ if\ g:asyncrun_status=="success"'
\ . '\ |\ set\ nomod'
\ . '\ |\ :endif '
\ . "scp " . shellescape(tmpfile)
\ . " " . path
" ^ inspired by:
" github.com/skywind3000/asyncrun.vim/wiki/Get-netrw-using-asyncrun-to-save-remote-files
"echom l:doMe
execute doMe
return
endif
if naturalpath != path && match(naturalpath,'^scp://') == 0
let path = substitute(path, '\\ ', '\ ', '')
endif
" Check file is writeable to current user
let writetest = "test -w " . shellescape(path)
\ . " || touch " . shellescape(path)
call system(writetest)
let couldNotWrite=v:shell_error
if couldNotWrite
echo "Did not have permissions to write file. Try to su? "
let response=nr2char(getchar())
if response=="y" || response=="Y"
call SuSave()
else
redraw
echo "Write-op cancelled."
endif
else
" otherwise, just write (pretty much) as normal:
let sePath=shellescape(path)
let perms=GetPermissions(sePath)
let owners=GetOwners(sePath)
" if the original path of the current buffer is different from the
" file we're being told to save (write) and is an SCP address,
" reduce the backslashes so we don't write files with backslashes
" locally:
let doMe="write " . fnameescape(path)
try
execute doMe
catch /^Vim\%((\a\+)\)\=:E13:/
echo "File " . path . " exists. Overwrite? "
let response=nr2char(getchar())
if response=="y" || response=="Y"
execute substitute(doMe,'^write','write!','')
else
echo "File-write aborted."
return
endif
endtry
let newPerms=GetPermissions(sePath)
let newOwners=GetOwners(sePath)
if perms!=newPerms || owners!=newOwners
echo "Permissions changed on write. Use su to adjust? "
let response=nr2char(getchar())
if response=="y" || response=="Y"
call SetAccess(sePath, perms, owners)
endif
endif
endif
endfunction
" InsertAtBeginning(['-q'|'-Q',] whatToInsert)
function! InsertAtBeginning(first,...) range
let doQuotes = 0
let args = a:000
if a:first == '-q'
let doQuotes = 1
let args += ['"']
else
let args = [a:first]
let args += a:000
endif
let whatToInsert = join(args,' ')
execute a:firstline . ',' . a:lastline . 's/^/' . whatToInsert
if doQuotes
execute a:firstline . ',' . a:lastline . 's/$/"'
endif
endfunction
function! Resize(first,...)
" echom type(a:first)
if a:0 == 0
" if no extra arguments given:
echom "resize " . a:first
resize a:first
elseif a:first == "-v"
" if direction (vertical) was given first:
echom "resize " . a:1
execute "resize " . a:1
elseif a:1 == "-v"
" if direction (vertical) was given second:
echom "resize " . a:first
execute "resize " . a:first
elseif a:first == "-h"
" if direciton (horizontal) was given first:
echom 'vertical resize ' . a:1
execute "vertical resize " . a:1
elseif a:1 == "-h"
" if direction (horizontal) was given second:
echom "vertical resize " . a:first
execute "vertical resize " . a:first
else
echom "Resize(): Huh?"
endif
endfunction
function! PaneToTab()
let buffer_number = bufnr('%')
close
tabedit
execute "buffer " . buffer_number
endfunction
" Get the ID of the current screen session (assuming we're inside one
" presently) e.g. '4105.T'
function! GetScreenSession()
let results = system('screen -wipe | grep "Attached" | cut -f 2')
return substitute(results, "\n", '', '')
endfunction
" ScreenDo(minusXArgs[,redraw[,windowId[,sessionId]]])
"
" Pass a command to GNU Screen to have it executed
"
" minusXargs -- the arguments to give to Screen's `-X` flag
"
" redraw -- integer representing whether to redraw vim's UI, since
" screen can mess it up in console.
" Defaults to: 1 (true/on)
"
" windowID -- the task (window) which the screen-command should affect
" Defaults to: window 0 (if omitted or empty string given)
"
" sessionID -- the screen session-identifier. Defaults to: current
" session (if omitted or empty string given)
"
function! ScreenDo(minusXArgs,...)
let redraw = 1
let sessionId = GetScreenSession()
let windowId = '0'
if a:0 > 1
let redraw = a:1
endif
if a:0 > 2
let windowId = a:2
endif
if a:0 > 3 && string(a:3)!=''
let sessionId = a:3
endif
silent exec '!screen -dr ' . sessionId . ' -p ' . windowId . ' -X ' . a:minusXArgs
redraw!
endfunction
" ToJumpToIdent([backwards[,indentToMatch[,ignoreWhite]]])
" move the cursor from the current line to either the end of the current
" block (by indentation) or the next line that has the same indent-level but
" is not part of the block
function! ToJumpToIndent(...)
let backwards = 0
if a:0 > 0
let backwards = a:1
endif
let indentToMatch = matchstr(getline('.'),'^\s*')
if a:0 > 1
let indentToMatch = a:2
endif
let ignoreWhite = 1
if a:0 > 2
let ignoreWhite = a:3
endif
let startnr = line('.')
let increment = (backwards)? -1 : 1
let linenr = startnr " current line-number as candidate to jump to
let lastMatchNr = startnr " where the last match we found was
let run = 1
"^ tracks whether we've had continuous matches between the start and the
" iteration previous to the current one
while (backwards)? linenr>=line('^') : linenr<=line('$')
let linenr += increment " move to next line
let line = getline(linenr)
let isWhite = (match(line,'\S')==-1)
let matched = 1 " whether we had a match this time
let leadingWhitespace = matchstr(getline(linenr),'^\s*\([^ \t]\)\@=')
if leadingWhitespace!=indentToMatch
if !ignoreWhite || (ignoreWhite && !isWhite)
let matched = 0
endif
if !isWhite && strlen(leadingWhitespace) < indentToMatch
" Generally, we won't want to jump to a matching indent-level if
" there's an intervening indent that's LESS than what we started
" with, so if we encounter that, we jump out if there's already
" a jump-target:
if lastMatchNr != startnr
return lastMatchNr . 'gg'
else
return ""
endif
endif
else
" if we matched, record the last line on which that occurred:
let lastMatchNr = linenr
endif
if lastMatchNr!=startnr && ((!run && matched) || (run && !matched))
" if we've identified a jump-point other than the start-line, AND:
" A) we've just hit the end of the current block (`run && !matched`)
" or
" B) we've found the next block of the same indent size after
" crossing a patch of differently-indented code (`!run && matched`)
break
endif
if !matched
let run = 0
endif
endwhile
if startnr == lastMatchNr
" if the while-loop failed to find any matches:
return ""
else
return lastMatchNr . "gg"
endif
endfunction
" Call this function if the argument-list to a function has grown too long,
" for one line, even if you go down a line to provide arguments only before
" closing out the call. This provides a way to sanely wrap each argument,
" even if there are strings containing commas or things that would screw up
" something simpler like a basic macro:
function! TransposeArgs()
" Note: we're currently making the assumption the args have already been
" put on their own line, so jump to the first right away:
normal ^
let startpos = getcurpos()
let repcount = 0
while startpos[1] == line('.')
" So long as we're still on the same line, keep repeating the motion to
" visit the next argument, keeping track of how many times we've
" done it:
normal 1],
let repcount += 1
endwhile
" Reset the cursor position and use the number of repeats we determined
" to jump to the dividing comma between each argument, move right one
" character, then insert a new line after the comma, which will match
" indent (or not) on the next line according to vim's `formatoptions`
call setpos('.',startpos) " reset cursor position
let doThis = repeat("1],\<Right>\<Return>", repcount-1)
execute 'normal ' .. doThis
endfunction
function! EatNextWord()
normal! m'v
call search('\s*[_a-zA-Z]\+\s*', 'ce', getline('.'))
normal! "_x
normal! `'
endfunction
" Selects entire document then performs series of keystrokes in normal mode
function! SelectAllThenDo(commandString)
normal ggVG
exec a:commandString
endfunction
function! InsertCharAfterCurrentChar(char)
silent! exec "normal a" . a:char
endfunction
function! ToInsertBeforeCurrentChar(char)
silent! exec "normal a" . "\<Left>". a:char
return "i" . a:char . "\<Esc>"
endfunction
function! InsertAtEOL(str,cleanEnd)
if a:cleanEnd
execute "normal! :s/\\s\\+$//e\<Return>"
endif
execute "normal! i\<End>" . a:str . "\<Esc>"
endfunction
" Returns a string to insert a new line relative to the current line
"
" preCr -- a key or combination of keys in the form of a string
" to press before <CR> is input, after determining the current line's indent level
" postCr -- a key or combination of key in the form of a string
" to press after <CR> is input to reorient the cursor appropriately
" for example, ('\<End>\<End>','') would result in the <CR> being placed after whatever's on the current line, while
" ('\<Home>','\<Up>') would insert a line before header charcaters in current line, and then move up
function! InsertLineSomewhere(preCr,postCr)
" BOOKMARK
let indentlevel = matchstr(getline('.'), '\_^\s\+')
" If Home sent cursor to a \s character then use that character plus everything behind it
" If Home sent the cursor to an alpha character then use whatever's to the left of that
" <End>a<CR> and then paste the whitespace characters we had from the beginning of the line. See what happens after that. If the cursor moves to somewhere inappropriate when we leave insert-mode, we can move functionality to "StartInsertingAbove()" and "StartInsertingBelow" and just have O and o insert lame old newlines like they always have (but in our case without entering into insert-mode.
" Another alternative is to alter the behavior of 'i' so that it checks the above and/or below lines to figure out what to do. It would spam some whitespaces in and then leave you in insert mode as per usual.
return "i" . a:preCr . "\<CR>" . indentlevel . a:postCr
endfunction
" currently unused
"function! GetCurrentIndentLevel()
"return matchstr(getline('.'),'\_$\s\+')
"endfunction
" GetCharFromCursor([offset])
function! GetCharFromCursor(...)
let offset = a:0 >= 1 ? a:1 : 0
return matchstr(getline('.'),'\%' . (col('.') + offset) . 'c.')
endfunction
function! InsertLineBelow()
return "m`i\<C-o>$\<CR>"
endfunction
function! InsertLineAbove()
" if matchstr(getline('.'),'\(\_^\s\+\)\@<=\S')
" let indentAmount = GetCurrentIndentLevel()
let colpos=virtcol('.')
return "i\<End>\<Home>\<CR>\<C-o>" . (l:colpos + 1) . '|'
endfunction
" SetEncloseWithFunctionCallFunctionName([returnThis])
" Set the name of a function so that other macros/functions can access it
" and know what function to wrap things with when instructed.
"
" Using the optional argument for this function allows a string of the
" caller's choice to be returned which can be useful in <expr> bindings,
" such that actions are executed only after the user has responded to the
" input-prompt.
"
function! SetEncloseWithFunctionCallFunctionName(...)
let returnThis = a:0 >= 1 ? a:1 : ''
let g:EncloseWithFunctionCallFunctionName = input("Function name? ")
return returnThis
endfunction
" Function adapted from http://vim.wikia.com/wiki/Smart_home#More_features
function! SmartHome(mode)
" if the cursor is not at the virtual home, hard home, or soft home,
" send it to the virtual home
"
" if the cursor is at the virutal home but is not at the line's soft
" home, send it there.
"
" if the cursor is at the line's hard home, send it to the line's soft
" home.
"
" Virtual home: the leftmost location of the screen accessible by the
" cursor without it changing lines visually. This is only different
" from the 'hard' home if the line is long enough that vim wraps it
" and will always match the hard home if 'nowrap' is set.
"
" Soft home: the leftmost absolute column (not visual) the cursor can
" visit on the current nonvisual line before reaching a whitespace.
"
" Hard home: the leftmost absolute column on the current nonvisual
" line.
let orig_pos = col('.')
let vorig_pos = virtcol('.')
let virtual_home = 1 + vorig_pos - vorig_pos%winwidth('%') + &tabstop*len(matchstr(getline('.'),'^\t*'))
let soft_home = match(getline('.'), '\S') + 1
let hard_home = 1
" echom "orig: " . orig_pos . " vorig: " . vorig_pos . " virth: " . virtual_home . " softh: " . soft_home
if vorig_pos != virtual_home && orig_pos != hard_home && orig_pos != soft_home
return 'g^'
elseif vorig_pos == virtual_home && orig_pos != soft_home
return '^'
elseif orig_pos == soft_home
return '0'
elseif orig_pos == hard_home
return '^'
endif
endfunction
" :[<startline>,<stopline>]call PgCap()
" capitalize all Postgres keywords on the given lines or -- if range is
" omitted -- on the current line
"
" PgCap(lineNumber, columnNumber)
" capitalize the character at the designated location if it is
" a Postgres keyword.
"
function! PgCap(...) range
let capThese = ['pgsqlKeyword','pgsqlOperator','pgsqlType','pgsqlVariable']
if a:0==2
let kwType = synIDattr( synID( a:1, a:2, 1 ), "name" )
if index(capThese,l:kwType) >= 0
normal! vgU
endif
else
set syntax=pgsql
let curLine = a:firstline
while curLine<=a:lastline
let curPos=1
while curPos<=len(getline(curLine))
let kwType = synIDattr( synID( curLine, curPos, 1 ), "name" )
if index(capThese,l:kwType) >= 0
let doString = curLine . ',' . curLine . 's/\(\%' . curPos . 'c.\)/\U\1'
execute doString
endif
let curPos += 1
endwhile
let curLine += 1
endwhile
endif
endfunction
" To(toLine,toColumn[,fromLine='.'[,luddite=false,lineInject='',colInject='']])
" Return the keystrokes for moving the cursor to the specified line+column
"
" toLine -- specific line-number or symbol like '$'