]> 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 " Send visual block to a browser
527 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
528 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
529 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
530 " Encode and send visual block to a browser
531 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
532 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
533 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
534 " Send current file's name to a browser
535 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
536 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
537 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
538
539 endif " version >= 700
540
541
542 " SPELLING
543
544 if has("spell") " Works in 7.0+
545    " Use builtin spellchecker
546    nmap \sv :syntax off <BAR> setlocal spell<CR>
547    " Clear
548    nmap \sn :syntax on <BAR> setlocal nospell<CR>
549 endif
550
551
552 " Russian letters mapped in normal mode
553 "if has("keymap")
554 "   set keymap=russian-jcuken
555 "endif
556
557 if has("langmap")
558    if v:version >= 702
559       " langmap in utf-8 mode requires at least Vim 7.2.109
560       scriptencoding utf-8
561       set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
562                  \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
563                  \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
564
565    elseif &encoding != 'utf-8'
566       scriptencoding koi8-r
567       set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
568                  \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
569                  \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
570    endif
571
572    scriptencoding us-ascii
573 endif
574
575
576 if version >= 700
577 function! W()
578    " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
579    let encodings = ['us-ascii']
580    if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
581       let encodings += ['utf-8']
582    elseif $LC_CTYPE == 'ru_RU.KOI8-R'
583       let encodings += ['koi8-r', 'utf-8']
584    elseif v:lc_time == 'Russian_Russia.1251'
585       let encodings += ['cp1251', 'utf-8']
586    endif
587
588    for e in encodings
589       try
590          execute 'set fileencoding=' . e
591          w
592          break
593       catch /E513: write error, conversion failed/
594          continue
595       endtry
596    endfor
597
598    if &modified
599       throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
600    elseif has("spell")
601       call SetupSpell()
602    endif
603 endfunction
604
605 command! W call W()
606 endif
607
608
609 function! SlowTerm()
610    set laststatus=1
611    set noruler
612    set shortmess=aoOtT
613    set noshowcmd
614    set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
615    set sidescroll=5
616    set nottyfast
617    set notitle
618    set timeoutlen=5000
619    set nowildmenu
620    set wildmode=list:longest
621    set viminfo=!,h,'10,<100,s5
622    if has("iconv")
623       set viminfo+=c
624    endif
625    syntax off
626    highlight NonText cterm=NONE ctermfg=NONE
627 endfunction
628
629 if exists("$SLOWTERM")
630    call SlowTerm()
631 endif
632
633
634 if has("python")
635 pyfile ~/.vim/python/virtualenv.py
636 endif
637
638 if has("python3")
639 py3file ~/.vim/python/virtualenv.py
640 endif
641
642
643 " From Tip 212:
644 " http://vim.fandom.com/wiki/Setting_file_attributes_without_reloading_a_buffer
645
646 if executable('chmod')
647    function! SetExecutableBit(x)
648       checktime
649       " Avoid 'Reload Y/N?' question
650       autocmd FileChangedShell <buffer> call _BufChangedCB()
651       let fx = executable(expand("%:p"))
652       if a:x && !fx
653          silent !chmod a+x %
654       elseif !a:x && fx
655          silent !chmod a-x %
656       endif
657       if v:shell_error
658          echoerr 'Error running chmod: ' . v:shell_error
659       endif
660       checktime
661       autocmd! FileChangedShell <buffer>
662    endfunction
663    function! _BufChangedCB()
664       autocmd! FileChangedShell <buffer>
665    endfunction
666    command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
667 endif
668
669 function! Code()
670     setlocal expandtab tabstop=8 softtabstop=4 shiftwidth=4
671 endfunction
672 command! Code call Code()
673
674 function! Text()
675     setlocal expandtab tabstop=8 softtabstop=3 shiftwidth=3
676 endfunction
677 command! Text call Text()
678
679 " ----------
680 " From http://slobin.pp.ru/vim/_vimrc.html
681
682 " These options will be kept between editing sessions
683 " let options = []
684
685 " Called automagically after .viminfo and plugins are loaded, sets
686 " miscellaneous options from persistent global variables
687 " function! VimEnter()
688   " for optname in g:options
689   "   let varname = "g:OPT_" . toupper(optname)
690   "   if exists(varname)
691   "     execute "let &" . optname . " = " . varname
692   "   endif
693   " endfor
694
695   " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
696   "   execute "winpos" g:WINPOSX g:WINPOSY
697   " endif
698 " endfunction
699
700 " Called automagically before .viminfo is saved, saves miscellaneous
701 " options into persistent global variables
702 " function! VimLeavePre()
703   " call filter(g:, 'v:key !~# "^OPT_"')
704   " for optname in g:options
705   "   let varname = "g:OPT_" . toupper(optname)
706   "   execute "let " . varname . " = &g:" . optname
707   " endfor
708
709   " if has("gui_running")
710   "   let g:WINPOSX = getwinposx()
711   "   let g:WINPOSY = getwinposy()
712   " endif
713 " endfunction
714
715 " autocmd VimEnter * call VimEnter()
716 " autocmd VimLeavePre * call VimLeavePre()
717
718
719 " Called automagically after every buffer read, enables fileencoding
720 " setting from modeline (see Tip #911:
721 " http://vim.fandom.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
722 function! AutoEncoding()
723   if &modified && &fileencoding != ""
724     call SetupEncoding(&fileencoding)
725   endif
726   autocmd! auto-encoding
727   augroup! auto-encoding
728 endfunction
729
730 augroup auto-encoding
731 autocmd!
732 autocmd BufWinEnter * call AutoEncoding()
733 augroup END
734
735
736 let CONVERT=1
737
738 " Value of a character under cursor; better than standard '0x%02B (%b)'
739 function! HexDec()
740   let char = matchstr(getline("."), ".", col(".") - 1)
741   if g:CONVERT
742     let char = iconv(char, &encoding, &fileencoding)
743     let format = "0x%02X <%d>"
744   else
745     let format = "0x%02X (%d)"
746   endif
747   let char = char2nr(char)
748   return printf(format, char, char)
749 endfunction
750
751
752 if has("iconv")
753    " Helper function for :DecodeQP and :DecodeURL commands
754    function! DecodeHex(arg)
755      return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
756    endfunction
757
758    " Custom completion for encoding names
759    function! EncList(ArgLead, CmdLine, CursorPos)
760      return filter(split(&fileencodings, ','),
761                  \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
762    endfunction
763
764    if version >= 700
765    " Command for decoding qp-encoded text
766    command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
767           \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
768
769    " Command for decoding url-encoded text
770    command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
771           \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
772    endif
773 endif
774
775
776 if has("spell")
777    function! SetupSpell()
778       if &fileencoding =~ 'ascii'
779          setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
780       elseif &fileencoding == 'koi8-r'
781          setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
782       elseif &fileencoding == 'utf-8'
783          setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
784       else
785          setlocal spelllang= spellfile=
786       endif
787    endfunction
788    autocmd BufReadPost * call SetupSpell()
789
790    function! SaveSpell()
791       if expand('%:p') == expand('~/.vim/spell/en.ascii.add')
792          mkspell! -ascii %
793       else
794          mkspell! %
795       endif
796    endfunction
797    autocmd BufWritePost ~/.vim/spell/*.add call SaveSpell()
798 endif
799
800
801 function! SyntaxName()
802   echomsg synIDattr(synID(line("."), col("."), 1), "name")
803 endfunction
804
805
806 if has("python")
807 pyfile ~/.vim/python/completion.py
808
809 " Custom completion for python expressions
810 function! CompList(ArgLead, CmdLine, CursorPos)
811   python vim_comp_list()
812 endfunction
813
814 " Python command line calculator
815 command! -nargs=+ -range -complete=customlist,CompList Calc
816        \ <line1>,<line2> python vim_calc(<q-args>)
817
818 " Python text range filter
819 command! -nargs=+ -range -complete=customlist,CompList Pydo
820        \ <line1>,<line2> python vim_pydo(<q-args>)
821
822 " Display unicode name for the character under cursor
823 command! Uname python vim_unicode_name()
824 endif
825
826 if has("python3")
827 py3file ~/.vim/python/completion.py
828
829 " Custom completion for python expressions
830 function! CompList(ArgLead, CmdLine, CursorPos)
831   python3 vim_comp_list()
832 endfunction
833
834 " Python command line calculator
835 command! -nargs=+ -range -complete=customlist,CompList Calc
836        \ <line1>,<line2> python3 vim_calc(<q-args>)
837
838 " Python text range filter
839 command! -nargs=+ -range -complete=customlist,CompList Pydo
840        \ <line1>,<line2> python3 vim_pydo(<q-args>)
841
842 " Display unicode name for the character under cursor
843 command! Uname python3 vim_unicode_name()
844 endif
845
846 if has("python") || has("python3")
847 command! UName Uname
848 endif
849 " ----------
850
851 if v:version >= 800
852    function! SetLazyRedraw(timer_id)
853       call timer_stop(a:timer_id) " One-time event
854       set lazyredraw
855    endfunction
856    call timer_start(500, 'SetLazyRedraw')
857 endif
858
859 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
860 set secure        " safer working with script files in the current directory