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