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