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