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