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