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