]> git.phdru.name Git - dotfiles.git/blob - .vimrc
Feat(recode-filenames-recursive): Allow to omit parameters
[dotfiles.git] / .vimrc
1 " User configuration file for Vi IMproved.
2 "
3 " vim 6.0+ required, 7.0+ recommended.
4
5 " 1 important
6
7 " Remove ALL autocommands in case the file is sourced for the second time
8 autocmd!
9
10 language messages C " Print messages in English
11
12 if exists("b:wrap") " Only do this on the second and subsequent :source's
13    let fenc = &fileencoding
14    let ftype = &filetype
15    let mod = &modified
16    set all& " Reset all options, except terminal options, to their default value.
17    execute 'set fileencoding=' . fenc
18    execute 'set filetype=' . ftype
19    if mod
20       set modified
21    else
22       set nomodified
23    endif
24    unlet fenc ftype mod
25
26 elseif filereadable($VIMRUNTIME . "/defaults.vim")
27    unlet! skip_defaults_vim
28    source $VIMRUNTIME/defaults.vim
29 endif
30
31 " No, it is not VI, it is VIM! It is important to set this first, because this
32 " command resets many other options.
33 set nocompatible
34
35 " Set behavior to xterm, not mswin
36 behave xterm
37
38 " 2 moving around, searching and patterns
39
40 set ignorecase    " Ignore case in search patterns
41 set noincsearch   " No incremental searching
42 set smartcase     " Match 'word' case-insensitive and 'Word' case-sensitive
43
44 set nostartofline " Keep cursor's column
45 set whichwrap=b,s,h,l,<,>,[,],~ " Wrap to the previous/next line on all keys and ~ command
46
47 " 4 displaying text
48
49 set display=lastline,uhex " Show the last line instead of '@'; show non-printable chars as <hex>
50
51 " Do not set it here, it breaks initial screen drawing and cursor positioning.
52 " See SetLazyRedraw at the end of the script.
53 " set lazyredraw  " Do not update screen while executing macros
54
55 set list          " listchars only works with 'list'
56 " Show tabs, non-breaking/trailing spaces, long lines
57 set listchars=tab:>_,nbsp:_,trail:_,extends:+,precedes:+
58 " Another usefull additions: eol:$,space:_
59 set scrolloff=0 " number of screen lines to show around the cursor
60 set wrap          " Visually wrap long lines
61
62 " With 'set wrap' wrap long lines at a character in 'breakat'
63 " Please note 'nolist' is required to use 'linebreak'
64 set linebreak showbreak=+\ " A plus and a space
65
66 set sidescroll=1  " The minimal number of columns to scroll horizontally
67
68 " 5 highlighting
69
70 colorscheme phd
71 set nohlsearch    " Stop the search highlighting
72
73 " 6 multiple windows
74
75 set hidden        " Don't unload a buffer when no longer shown in a window; allow to switch between buffers/windows when the buffer is modified
76 set laststatus=2  " Always show status line
77 " set statusline=%<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P " Default statusline
78
79 set splitbelow    " A new window is put below of the current one
80 set splitright    " A new window is put right of the current one
81
82 " 8 terminal
83
84 set ttyfast       " terminal connection is fast
85
86 set title         " Set title to the value of 'titlestring' or to 'filename - VIM'
87 set titleold=     " string to restore the title to when exiting Vim
88 " String to use for the Vim window title; with statusline printf items.
89 " This is the default:
90 " display filename, modification flag, full path, and program name in uppercase.
91 " set titlestring=%t%(\ %M%)%(\ (%{substitute(expand(\"%:p:h\"),\ $HOME,\ \"~\",\ \"\")})%)%(\ %a%)\ -\ %{toupper(v:progname)}
92 " display filename, modification flag, full path, argument list status,
93 " the current user, host and program name (to distinguish vim/view/etc).
94 set titlestring=%t%(\ %M%)%(\ (%{substitute(expand(\"%:p:h\"),\ $HOME,\ \"~\",\ \"\")})%)%(\ %a%)\ -\ %{v:progname}\ [%{$USER}@%{hostname()}]
95
96 " 9 using the mouse
97
98 if has('mouse')
99    set mouse=ar      " Use mouse in all modes, plus hit-return
100 endif
101
102 " 12 messages and info
103
104 set ruler         " Show cursor position below each window
105 set showcmd       " Show (partial) command keys in the status line
106 set visualbell    " Use visual bell instead of beeping
107 if v:version >= 800
108    set belloff=error,insertmode " Do not ring the bell for these reasons
109 endif
110
111 " Short message for [Modified];
112 " overwrite message for writing a file with subsequent message;
113 " truncate long file messages
114 set shortmess=mot
115
116 " 14 editing text
117
118 set backspace=indent,eol,start
119 set complete+=k   " Scan spell dictionaries for completion in addition to standard places
120 set infercase     " adjust case of a keyword completion match
121 set nojoinspaces  " Do not insert two spaces after a '.', '?' and '!' with a join command
122 set nrformats=hex " I seldom edit octal numbers, but very often dates like 2001-02-01
123
124 " Default value 'croql' is a compromise for both natural and programming
125 " languages, but as any compromise it works good for neither natural nor
126 " programming languages. This value is good for natural texts,
127 " let ftplugins to set values suitable for programming languages.
128 set formatoptions=2t " list of flags that tell how automatic formatting works
129
130 " 15 tabs and indenting
131
132 set expandtab     " expand <Tab> to spaces in Insert mode
133 set shiftwidth=3  " number of spaces used for each step of (auto)indent
134 set smarttab      " a <Tab> in an indent inserts 'shiftwidth' spaces
135 set softtabstop=3 " number of spaces to insert for a <Tab>
136
137 set noautoindent  " Do not automatically set the indent of a new line
138
139 " 18 mapping
140
141 set timeout timeoutlen=3000 ttimeoutlen=100 " allow timing out up to 3 seconds halfway into a mapping; 100 ms to wait for a key code or mapped key sequence to complete
142
143 " 19 reading and writing files
144 if v:version >= 703
145    set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
146 endif
147
148 " 20 the swap file
149
150 let myUndoDir = expand('~/tmp/vim/undo')
151 if !isdirectory(myUndoDir)
152     " Create dirs
153     call mkdir(myUndoDir, 'p')
154 endif
155
156 " list of directories for the swap file; remove . (the current directory)
157 if has("win32")
158    set directory=~/tmp/vim//,$TEMP//,c:/tmp//,c:/temp//
159 else
160    set directory=~/tmp/vim//,~/tmp//,/var/tmp//,/tmp//
161 endif
162 " if a directory ends in two path separators "//"
163 " or "\\", the swap file name will be built from the complete path to
164 " the file with all path separators substituted to percent '%' signs.
165 " This will ensure file name uniqueness in the preserve directory.
166
167 " 21 command line editing
168
169 set history=1000  " how many command lines are remembered
170 set suffixes+=.pyc,.pyo " list of file name extensions that have a lower priority
171 set wildignore+=*.py[co] " Ignore these patterns when completing file names
172 set wildmenu      " command-line completion shows a list of matches
173 set wildmode=longest,list:longest,full " Bash-vim completion behavior
174
175 " Keep undo history across sessions by storing it in a file
176 if has('persistent_undo')
177     let &undodir = myUndoDir
178     set undofile
179 endif
180
181 " 22 executing external commands
182
183 if has("filterpipe")
184    set noshelltemp " Use pipes on Unix
185 endif
186
187 " 25 multi-byte characters
188
189 " Automatically detected character encodings
190 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
191
192 " 26 various
193
194 " ! - when included, save and restore global variables that start
195 "     with an uppercase letter, and don't contain a lowercase letter;
196 " h - disable the effect of 'hlsearch';
197 " ' - number of files for which the marks are remembered;
198 " " and < - maximum number of lines saved for a register;
199 " s - maximum size of an item in Kbytes.
200 set viminfo=!,h,'50
201 if version < 603
202    set viminfo+=\"1000
203 else
204    set viminfo+=<1000,s10
205 endif
206
207 " c - convert viminfo to the current encoding;
208 if has("iconv")
209    set viminfo+=c
210 endif
211
212 " Removable media paths
213 if has("win32")
214    set viminfo+=ra:,rb:
215 endif
216
217 " ----------
218
219 if has("gui_running")
220    set background=light
221
222    if has("win32")
223       "set guifont=Courier_New:h18:cRUSSIAN
224       set guifont=Lucida_Console:h18:cRUSSIAN
225    elseif has("x11")
226       set guifont=Monospace\ 18
227       set toolbar=icons,text " how to show the toolbar
228    endif
229
230    set guicursor+=n:block " Block cursor in normal mode
231    set guicursor+=i:ver10 " Solid vertical bar in insert mode
232    set guicursor+=a:blinkon0 " Stop cursor blinking
233
234    " Make shift-insert work like in Xterm
235    " map <S-Insert> <MiddleMouse>
236    " map! <S-Insert> <MiddleMouse>
237
238    " ----------
239    " From http://slobin.pp.ru/vim/_vimrc.html
240
241    " Arrows should go into wrapped lines, but not while popup menu is visible
242    imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
243    imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
244
245    " The <CR> key should select from completion menu without adding a newline
246    imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
247    " ----------
248
249 else
250    if (&term =~ "linux") || (&term =~ "cygwin") || (&term =~ "putty")
251          \ || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
252          \ || has("win32")
253       " Background of the terminal is black or dark grey
254       set background=dark
255    else
256       set background=light
257    endif
258
259    if (&term =~ "linux")
260       execute 'set t_kb=' . nr2char(127)
261    endif
262
263    if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
264       execute 'set t_kb=' . nr2char(127)
265
266       if has ("terminfo")
267          " set t_Co=256
268          set t_Co=16
269       else
270          set t_Co=8
271          set t_Sf="\e[3%dm"
272          set t_Sb="\e[4%dm"
273       endif
274
275       " KP_Up -> Up
276       map <Esc>Ox <Esc>OA
277       map! <Esc>Ox <Esc>OA
278       " KP_Down -> Down
279       map <Esc>Or <Esc>OB
280       map! <Esc>Or <Esc>OB
281       " KP_Right -> Right
282       map <Esc>Ov <Esc>OC
283       map! <Esc>Ov <Esc>OC
284       " KP_Left -> Left
285       map <Esc>Ot <Esc>OD
286       map! <Esc>Ot <Esc>OD
287       " KP_Home -> Home
288       map <Esc>Ow <Esc>[7~
289       map! <Esc>Ow <Esc>[7~
290       " KP_End -> End
291       map <Esc>Oq <Esc>[8~
292       map! <Esc>Oq <Esc>[8~
293       " KP_Prev (PgDn) and KP_Next (PgUp) work fine, no mapping is required
294
295       " 'autoselect' to always put selected text on the clipboard;
296       " 'unnamed' to use the * register like unnamed register '*'
297       " for all yank, delete and put operations;
298       " This allows to use mouse for copy/paste in local xterm,
299       " but prevents to save the unnamed register between sessions.
300       " set clipboard=autoselect,unnamed,exclude:cons\|linux
301
302       " Use xclip to copy/paste to/from X clipboard at remote host
303       " vmap "+y :!xclip -i -sel clip
304       " map "+p :r!xclip -o -sel clip
305       " Enable X11Forwarding and use ssh -X or even -Y
306    endif
307
308    if (&term =~ "screen")
309       set ttymouse=xterm2 " Enable mouse codes under screen/tmux
310       if empty(&t_ts)
311          " Enable window title under screen/tmux
312          let &t_ts = "\e]2;"
313          let &t_fs = "\007"
314       endif
315    endif
316
317    " https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
318    " https://ttssh2.osdn.jp/manual/en/usage/tips/vim.html
319    function! WrapForScreenTmux(s)
320       if (&term =~ "screen")
321          let scr_start = "\<Esc>P"
322          let scr_end = "\<Esc>\\"
323
324          return scr_start . a:s . scr_end
325       endif
326
327       if exists('$TMUX')
328          let tmux_start = "\<Esc>Ptmux;"
329          let tmux_end = "\<Esc>\\"
330
331          return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
332       endif
333
334       return a:s
335    endfunction
336
337    " https://vim.fandom.com/wiki/Change_cursor_shape_in_different_modes
338    let &t_EI.=WrapForScreenTmux("\e[2 q") "EI = NORMAL mode (ELSE)
339    let &t_SI.=WrapForScreenTmux("\e[6 q") "SI = INSERT mode
340    if v:version >= 800
341       let &t_SR.=WrapForScreenTmux("\e[4 q") "SR = REPLACE mode
342    endif
343
344    "Cursor settings:
345    "  1 -> blinking block
346    "  2 -> solid block 
347    "  3 -> blinking underscore
348    "  4 -> solid underscore
349    "  5 -> blinking vertical bar
350    "  6 -> solid vertical bar
351 endif
352
353 " Multiline comments often confuse vim syntax highlighting - these maps
354 " allow to resynchronize; the first is faster, the second is more thorough
355 nmap \sc :syntax sync clear<Enter>
356 nmap \ss :syntax sync fromstart<Enter>
357
358
359 " AUTOCOMMANDS
360
361 " Enable filetype detection
362 filetype plugin indent on
363
364 runtime macros/matchit.vim
365
366 " Reread me after editing
367 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
368
369 if version >= 700
370 " Save all files before running any quickfix command (grep, makeprg, etc.)
371 autocmd QuickFixCmdPre * wall
372 " automatically close quickfix if it's the only window left
373 autocmd WinEnter * if winnr('$') == 1 && 
374    \ index(["nofile", "quickfix"], &buftype) >= 0 | quit | endif
375 endif
376
377 " Syntax highlighting
378 autocmd BufReadPost * syntax on
379
380
381 " Restore last known cursor position
382 function! RestorePosition()
383    if exists('b:position_restored')
384       return
385    endif
386
387    if line("'\"") > 0
388       call cursor(line("'\""), col("'\""))
389    endif
390    let b:position_restored = 1
391 endfunction
392
393 " When editing a file, always jump to the last cursor position (if saved)
394 autocmd BufReadPost * call RestorePosition()
395
396
397 function! SetupEncoding(encoding)
398    if !has("iconv") || exists('b:encoding_set') || empty(a:encoding)
399       return
400    endif
401
402    call RestorePosition()
403    let b:encoding_set = 1
404    if !empty(expand('%'))
405       execute "edit ++enc=" . a:encoding
406    endif
407 endfunction
408
409
410 " From http://lwn.net/Articles/226514/
411
412 augroup gpg
413 " Remove ALL autocommands for the current group.
414 autocmd!
415 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
416 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
417 autocmd BufReadPost *.gpg :%!gpg -q -d
418 autocmd BufReadPost *.gpg | redraw
419 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
420 autocmd BufWritePost *.gpg u
421 autocmd VimLeave *.gpg :!clear
422 " For OpenSSL:
423 " BufReadPost: use "openssl bf -d -a"
424 " BufWritePre: use "openssl bf -salt -a"
425 augroup END
426
427
428 function! SetWrap()
429    setlocal wrap
430    map <Up> gk
431    imap <Up> <C-O>gk
432    map <Down> gj
433    imap <Down> <C-O>gj
434    let b:wrap = 1
435 endfunction
436
437 function! SetNoWrap()
438    setlocal nowrap
439    map <Up> k
440    map <Down> j
441    let b:wrap = 0
442 endfunction
443
444 command! SetWrap call SetWrap()
445 command! SetNoWrap call SetNoWrap()
446
447 " b:wrap can be set by an ftplugin
448 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
449
450
451 " MAPPINGS
452
453 " Do not unindent #-comment
454 inoremap # X<C-H>#
455
456 " map <C-A> <Home>
457 " map <C-E> <End>
458 " map <C-Z> :shell<CR>
459
460
461 if version >= 700
462 " WEB BROWSERS
463
464 let s:URL_re="\\v(((https?|ftp|gopher|telnet)://|(mailto|file|news|about|ed2k|irc|sip|magnet):)[^' \t<>\"]+|(www|web|w3)[a-z0-9_-]*\\.[a-z0-9._-]+\\.[^' \t<>\"]+)[a-z0-9/]\\c"
465
466 function! ExtractURL()
467    let line = getline('.')
468    let parts = split(line, s:URL_re . '\zs')
469
470    if empty(parts)
471       throw 'ExtractURLCannotFindURL' " No URL found
472    endif
473
474    let length = 0
475    let column = col('.')
476
477    for p in parts
478       let save_length = length
479       let length += len(p)
480       if length >= column
481          break
482       endif
483    endfor
484
485    let pos = match(p, s:URL_re)
486    if pos == -1
487       throw 'ExtractURLCannotFindURL' " No URL found
488    endif
489
490    if save_length + pos >= column " cursor left of the URL
491       throw 'ExtractURLCannotFindURL'
492    endif
493
494    return strpart(p, pos)
495 endfunction
496
497 function! EscapeURL(url)
498    let url = substitute(a:url, ' ', '%20', 'g')
499    return escape(url, '!#$%')
500 endfunction
501
502 function! OpenURL(url, newwin)
503    execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
504 endfunction
505
506 function! ExtractOpenURL(newwin)
507    try
508       let url = ExtractURL()
509    catch /^ExtractURLCannotFindURL$/
510       echoerr 'No URL found under cursor'
511       return
512    endtry
513
514    call OpenURL(url, a:newwin)
515 endfunction
516
517 function! EncodeOpenURL(url, newwin)
518    execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
519 endfunction
520
521
522 " Send current link to a browser
523 nmap \b :call ExtractOpenURL('')<CR>
524 nmap \w :call ExtractOpenURL('-n')<CR>
525 nmap \t :call ExtractOpenURL('-t')<CR>
526 nmap \p :call ExtractOpenURL('-p')<CR>
527 " Send visual block to a browser
528 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
529 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
530 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
531 vmap \p ""y:call OpenURL('<C-R>"', '-p')<CR>
532 " Encode and send visual block to a browser
533 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
534 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
535 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
536 " Send current file's name to a browser
537 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
538 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
539 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
540
541 endif " version >= 700
542
543
544 " SPELLING
545
546 if has("spell") " Works in 7.0+
547    " Use builtin spellchecker
548    nmap \sv :syntax off <BAR> setlocal spell<CR>
549    " Clear
550    nmap \sn :syntax on <BAR> setlocal nospell<CR>
551 endif
552
553
554 " Russian letters mapped in normal mode
555 "if has("keymap")
556 "   set keymap=russian-jcuken
557 "endif
558
559 if has("langmap")
560    if v:version >= 702
561       " langmap in utf-8 mode requires at least Vim 7.2.109
562       scriptencoding utf-8
563       set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
564                  \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
565                  \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
566
567    elseif &encoding != 'utf-8'
568       scriptencoding koi8-r
569       set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
570                  \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
571                  \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
572    endif
573
574    scriptencoding us-ascii
575 endif
576
577
578 if version >= 700
579 function! W()
580    " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
581    let encodings = ['us-ascii']
582    if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
583       let encodings += ['utf-8']
584    elseif $LC_CTYPE == 'ru_RU.KOI8-R'
585       let encodings += ['koi8-r', 'utf-8']
586    elseif v:lc_time == 'Russian_Russia.1251'
587       let encodings += ['cp1251', 'utf-8']
588    endif
589
590    for e in encodings
591       try
592          execute 'set fileencoding=' . e
593          w
594          break
595       catch /E513: [Ww]rite error, conversion failed/
596          continue
597       endtry
598    endfor
599
600    if &modified
601       throw '"' . expand('%') . '" E513: Write error, conversion failed; tried ' . join(encodings, ',')
602    elseif has("spell")
603       call SetupSpell()
604    endif
605 endfunction
606
607 command! W call W()
608 endif
609
610
611 function! SlowTerm()
612    set laststatus=1
613    set noruler
614    set shortmess=aoOtT
615    set noshowcmd
616    set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
617    set sidescroll=5
618    set nottyfast
619    set notitle
620    set timeoutlen=5000
621    set nowildmenu
622    set wildmode=list:longest
623    set viminfo=!,h,'10,<100,s5
624    if has("iconv")
625       set viminfo+=c
626    endif
627    syntax off
628    highlight NonText cterm=NONE ctermfg=NONE
629 endfunction
630
631 if exists("$SLOWTERM")
632    call SlowTerm()
633 endif
634
635
636 if has("python")
637 pyfile ~/.vim/python/virtualenv.py
638 endif
639
640 if has("python3")
641 py3file ~/.vim/python/virtualenv.py
642 endif
643
644
645 " From Tip 212:
646 " http://vim.fandom.com/wiki/Setting_file_attributes_without_reloading_a_buffer
647
648 if executable('chmod')
649    function! SetExecutableBit(x)
650       checktime
651       " Avoid 'Reload Y/N?' question
652       autocmd FileChangedShell <buffer> call _BufChangedCB()
653       let fx = executable(expand("%:p"))
654       if a:x && !fx
655          silent !chmod a+x %
656       elseif !a:x && fx
657          silent !chmod a-x %
658       endif
659       if v:shell_error
660          echoerr 'Error running chmod: ' . v:shell_error
661       endif
662       checktime
663       autocmd! FileChangedShell <buffer>
664    endfunction
665    function! _BufChangedCB()
666       autocmd! FileChangedShell <buffer>
667    endfunction
668    command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
669 endif
670
671 function! Code()
672     setlocal expandtab tabstop=8 softtabstop=4 shiftwidth=4
673 endfunction
674 command! Code call Code()
675
676 function! Text()
677     setlocal expandtab tabstop=8 softtabstop=3 shiftwidth=3
678 endfunction
679 command! Text call Text()
680
681 " ----------
682 " From http://slobin.pp.ru/vim/_vimrc.html
683
684 " These options will be kept between editing sessions
685 " let options = []
686
687 " Called automagically after .viminfo and plugins are loaded, sets
688 " miscellaneous options from persistent global variables
689 " function! VimEnter()
690   " for optname in g:options
691   "   let varname = "g:OPT_" . toupper(optname)
692   "   if exists(varname)
693   "     execute "let &" . optname . " = " . varname
694   "   endif
695   " endfor
696
697   " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
698   "   execute "winpos" g:WINPOSX g:WINPOSY
699   " endif
700 " endfunction
701
702 " Called automagically before .viminfo is saved, saves miscellaneous
703 " options into persistent global variables
704 " function! VimLeavePre()
705   " call filter(g:, 'v:key !~# "^OPT_"')
706   " for optname in g:options
707   "   let varname = "g:OPT_" . toupper(optname)
708   "   execute "let " . varname . " = &g:" . optname
709   " endfor
710
711   " if has("gui_running")
712   "   let g:WINPOSX = getwinposx()
713   "   let g:WINPOSY = getwinposy()
714   " endif
715 " endfunction
716
717 " autocmd VimEnter * call VimEnter()
718 " autocmd VimLeavePre * call VimLeavePre()
719
720
721 " Called automagically after every buffer read, enables fileencoding
722 " setting from modeline (see Tip #911:
723 " http://vim.fandom.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
724 function! AutoEncoding()
725   if &modified && &fileencoding != ""
726     call SetupEncoding(&fileencoding)
727   endif
728   autocmd! auto-encoding
729   augroup! auto-encoding
730 endfunction
731
732 augroup auto-encoding
733 autocmd!
734 autocmd BufWinEnter * call AutoEncoding()
735 augroup END
736
737
738 let CONVERT=1
739
740 " Value of a character under cursor; better than standard '0x%02B (%b)'
741 function! HexDec()
742   let char = matchstr(getline("."), ".", col(".") - 1)
743   if g:CONVERT
744     let char = iconv(char, &encoding, &fileencoding)
745     let format = "0x%02X <%d>"
746   else
747     let format = "0x%02X (%d)"
748   endif
749   let char = char2nr(char)
750   return printf(format, char, char)
751 endfunction
752
753
754 if has("iconv")
755    " Helper function for :DecodeQP and :DecodeURL commands
756    function! DecodeHex(arg)
757      return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
758    endfunction
759
760    " Custom completion for encoding names
761    function! EncList(ArgLead, CmdLine, CursorPos)
762      return filter(split(&fileencodings, ','),
763                  \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
764    endfunction
765
766    if version >= 700
767    " Command for decoding qp-encoded text
768    command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
769           \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
770
771    " Command for decoding url-encoded text
772    command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
773           \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
774    endif
775 endif
776
777
778 if has("spell")
779    function! SetupSpell()
780       if &fileencoding =~ 'ascii'
781          setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
782       elseif &fileencoding == 'koi8-r'
783          setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
784       elseif &fileencoding == 'utf-8'
785          setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
786       else
787          setlocal spelllang= spellfile=
788       endif
789    endfunction
790    autocmd BufReadPost * call SetupSpell()
791
792    function! SaveSpell()
793       if expand('%:p') == expand('~/.vim/spell/en.ascii.add')
794          mkspell! -ascii %
795       else
796          mkspell! %
797       endif
798    endfunction
799    autocmd BufWritePost ~/.vim/spell/*.add call SaveSpell()
800 endif
801
802
803 function! SyntaxName()
804   echomsg synIDattr(synID(line("."), col("."), 1), "name")
805 endfunction
806
807
808 if has("python")
809 pyfile ~/.vim/python/completion.py
810
811 " Custom completion for python expressions
812 function! CompList(ArgLead, CmdLine, CursorPos)
813   python vim_comp_list()
814 endfunction
815
816 " Python command line calculator
817 command! -nargs=+ -range -complete=customlist,CompList Calc
818        \ <line1>,<line2> python vim_calc(<q-args>)
819
820 " Python text range filter
821 command! -nargs=+ -range -complete=customlist,CompList Pydo
822        \ <line1>,<line2> python vim_pydo(<q-args>)
823
824 " Display unicode name for the character under cursor
825 command! Uname python vim_unicode_name()
826 endif
827
828 if has("python3")
829 py3file ~/.vim/python/completion.py
830
831 " Custom completion for python expressions
832 function! CompList(ArgLead, CmdLine, CursorPos)
833   python3 vim_comp_list()
834 endfunction
835
836 " Python command line calculator
837 command! -nargs=+ -range -complete=customlist,CompList Calc
838        \ <line1>,<line2> python3 vim_calc(<q-args>)
839
840 " Python text range filter
841 command! -nargs=+ -range -complete=customlist,CompList Pydo
842        \ <line1>,<line2> python3 vim_pydo(<q-args>)
843
844 " Display unicode name for the character under cursor
845 command! Uname python3 vim_unicode_name()
846 endif
847
848 if has("python") || has("python3")
849 command! UName Uname
850 endif
851 " ----------
852
853 if v:version >= 800
854    function! SetLazyRedraw(timer_id)
855       call timer_stop(a:timer_id) " One-time event
856       set lazyredraw
857    endfunction
858    call timer_start(500, 'SetLazyRedraw')
859 endif
860
861 autocmd VimLeave * call writefile([getcwd()], expand('~/tmp/vim/cwd'))
862
863 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
864 set secure        " safer working with script files in the current directory