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