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