1 " User configuration file for Vi IMproved.
3 " vim 6.0+ required, 7.0+ recommended.
7 " Remove ALL autocommands in case the file is sourced for the second time
10 language messages C " Print messages in English
12 if exists("b:wrap") " Only do this on the second and subsequent :source's
13 let fenc = &fileencoding
16 set all& " Reset all options, except terminal options, to their default value.
17 execute 'set fileencoding=' . fenc
18 execute 'set filetype=' . ftype
27 " No, it is not VI, it is VIM! It is important to set this first, because this
28 " command resets many other options.
31 " Set behavior to xterm, not mswin
34 " 2 moving around, searching and patterns
36 set ignorecase " Ignore case in search patterns
37 set smartcase " Match 'word' case-insensitive and 'Word' case-sensitive
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
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
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
54 set sidescroll=1 " The minimal number of columns to scroll horizontally
58 set nohlsearch " Stop the search highlighting
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
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
70 set ttyfast " terminal connection is fast
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
77 set mouse=ar " Use mouse in all modes, plus hit-return
79 " 12 messages and info
81 set ruler " Show cursor position below each window
82 set showcmd " Show (partial) command keys in the status line
84 " Short message for [Modified];
85 " overwrite message for writing a file with subsequent message;
86 " truncate long file messages
91 set backspace=indent,eol,start
92 set complete+=k " Scan spell dictionaries for completion in addition to standard places
93 set infercase " adjust case of a keyword completion match
94 set nojoinspaces " Do not insert two spaces after a '.', '?' and '!' with a join command
95 set nrformats=hex " I seldom edit octal numbers, but very often dates like 2001-02-01
97 " Default value 'croql' is a compromise for both natural and programming
98 " languages, but as any compromise it works good for neither natural nor
99 " programming languages. This value is good for natural texts,
100 " let ftplugins to set values suitable for programming languages.
101 set formatoptions=2t " list of flags that tell how automatic formatting works
103 " 15 tabs and indenting
105 set expandtab " expand <Tab> to spaces in Insert mode
106 set shiftwidth=3 " number of spaces used for each step of (auto)indent
107 set smarttab " a <Tab> in an indent inserts 'shiftwidth' spaces
108 set softtabstop=3 " number of spaces to insert for a <Tab>
110 set noautoindent " Do not automatically set the indent of a new line
114 set timeout timeoutlen=3000 " allow timing out up to 3 seconds halfway into a mapping
116 " 21 command line editing
118 set history=1000 " how many command lines are remembered
119 set suffixes+=.pyc,.pyo " list of file name extensions that have a lower priority
120 set wildignore+=*.py[co] " Ignore these patterns when completing file names
121 set wildmenu " command-line completion shows a list of matches
122 set wildmode=longest,list:longest,full " Bash-vim completion behavior
124 " 22 executing external commands
127 set noshelltemp " Use pipes on Unix
130 " 25 multi-byte characters
132 " Automatically detected character encodings
133 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
137 " ! - when included, save and restore global variables that start
138 " with an uppercase letter, and don't contain a lowercase letter;
139 " h - disable the effect of 'hlsearch';
140 " ' - number of files for which the marks are remembered;
141 " " and < - maximum number of lines saved for a register;
142 " s - maximum size of an item in Kbytes.
144 set viminfo=!,h,'50,\"1000
146 set viminfo=!,h,'50,<1000,s10
149 " c - convert viminfo to the current encoding;
154 " Removable media paths
161 if has("gui_running")
165 "set guifont=Courier_New:h18:cRUSSIAN
166 set guifont=Lucida_Console:h18:cRUSSIAN
168 set guifont=Monospace\ 16
169 set toolbar=icons,text " how to show the toolbar
172 " set guicursor+=a:blinkon0 " Stop cursor blinking
174 " Make shift-insert work like in Xterm
175 " map <S-Insert> <MiddleMouse>
176 " map! <S-Insert> <MiddleMouse>
180 " Background for normal text is light grey
182 " Text below the last line is darker grey
183 " Status line is bright white on blue
184 highlight Normal guibg=grey90
185 highlight Cursor guibg=green guifg=NONE
186 highlight NonText guibg=grey80
187 highlight Constant guibg=grey90
188 highlight Special gui=NONE guibg=grey90
189 highlight StatusLine gui=bold guifg=white guibg=blue
192 " From http://slobin.pp.ru/vim/_vimrc.html
194 " Arrows should go into wrapped lines, but not while popup menu is visible
195 imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
196 imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
198 " The <CR> key should select from completion menu without adding a newline
199 imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
203 if (&term =~ "linux") || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
205 " Background of the terminal is black or dark grey
207 highlight MoreMsg ctermfg=white
208 highlight ModeMsg ctermfg=white
209 highlight Question ctermfg=white
212 highlight MoreMsg cterm=bold ctermfg=NONE
213 highlight Question cterm=bold ctermfg=NONE
216 if (&term =~ "linux")
217 execute 'set t_kb=' . nr2char(127)
220 if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
221 execute 'set t_kb=' . nr2char(127)
223 " 'autoselect' to always put selected text on the clipboard;
224 " 'unnamed' to use the * register like unnamed register '*'
225 " for all yank, delete and put operations;
226 " This allows to use mouse for copy/paste in local xterm,
227 " but prevents to save the unnamed register between sessions.
228 " set clipboard=autoselect,unnamed,exclude:cons\|linux
240 if (&term =~ "screen")
241 set ttymouse=xterm " Enable mouse codes under GNU screen
243 " Enable window title under screen/tmux
250 highlight SpellBad term=underline cterm=NONE ctermfg=white ctermbg=red guifg=white guibg=red " gui=undercurl guisp=red
251 highlight StatusLine cterm=bold ctermfg=white ctermbg=blue gui=NONE guifg=white guibg=blue
252 highlight Visual cterm=NONE ctermfg=white ctermbg=blue gui=NONE guifg=white guibg=blue " Selection highlighting
254 " Multiline comments often confuse vim syntax highlighting - these maps
255 " allow to resynchronize; the first is faster, the second is more thorough
256 nmap \sc :syntax sync clear<Enter>
257 nmap \ss :syntax sync fromstart<Enter>
262 " Enable filetype detection
263 filetype plugin indent on
265 " Reread me after editing
266 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
269 " Save all files before running any quickfix command (grep, makeprg, etc.)
270 autocmd QuickFixCmdPre * wall
273 " Syntax highlighting
274 autocmd BufReadPost * syntax on
277 " Restore last known cursor position
278 function! RestorePosition()
279 if exists('b:position_restored')
284 call cursor(line("'\""), col("'\""))
286 let b:position_restored = 1
289 " When editing a file, always jump to the last cursor position (if saved)
290 autocmd BufReadPost * call RestorePosition()
293 function! SetupEncoding(encoding)
294 if !has("iconv") || exists('b:encoding_set') || strlen(a:encoding) == 0
298 call RestorePosition()
299 let b:encoding_set = 1
300 execute "edit ++enc=" . a:encoding
304 " http://lwn.net/Articles/226514/
307 " Remove ALL autocommands for the current group.
309 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
310 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
311 autocmd BufReadPost *.gpg :%!gpg -q -d
312 autocmd BufReadPost *.gpg | redraw
313 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
314 autocmd BufWritePost *.gpg u
315 autocmd VimLeave *.gpg :!clear
317 " BufReadPost: use "openssl bf -d -a"
318 " BufWritePre: use "openssl bf -salt -a"
331 function! SetNoWrap()
338 command! SetWrap call SetWrap()
339 command! SetNoWrap call SetNoWrap()
341 " b:wrap can be set by an ftplugin
342 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
347 " Do not unindent #-comment
352 " map <C-Z> :shell<CR>
358 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"
360 function! ExtractURL()
361 let line = getline('.')
362 let parts = split(line, s:URL_re . '\zs')
365 throw 'ExtractURLCannotFindURL' " No URL found
369 let column = col('.')
372 let save_length = length
379 let pos = match(p, s:URL_re)
381 throw 'ExtractURLCannotFindURL' " No URL found
384 if save_length + pos >= column " cursor left of the URL
385 throw 'ExtractURLCannotFindURL'
388 return strpart(p, pos)
391 function! EscapeURL(url)
392 let url = substitute(a:url, ' ', '%20', 'g')
393 return escape(url, '!#$%')
396 function! OpenURL(url, newwin)
397 execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
400 function! ExtractOpenURL(newwin)
402 let url = ExtractURL()
403 catch /^ExtractURLCannotFindURL$/
404 echoerr 'No URL found under cursor'
408 call OpenURL(url, a:newwin)
411 function! EncodeOpenURL(url, newwin)
412 execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
416 " Send current link to a browser
417 nmap \b :call ExtractOpenURL('')<CR>
418 nmap \w :call ExtractOpenURL('-n')<CR>
419 nmap \t :call ExtractOpenURL('-t')<CR>
420 " Send visual block to a browser
421 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
422 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
423 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
424 " Encode and send visual block to a browser
425 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
426 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
427 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
428 " Send current file's name to a browser
429 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
430 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
431 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
433 endif " version >= 700
438 if has("spell") " Works in 7.0+
439 " Use builtin spellchecker
440 nmap \sv :syntax off <BAR> setlocal spell<CR>
442 nmap \sn :syntax on <BAR> setlocal nospell<CR>
446 " Russian letters mapped in normal mode
448 " set keymap=russian-jcuken
453 " langmap in utf-8 mode requires at least Vim 7.2.109
455 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
456 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
457 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
459 elseif &encoding != 'utf-8'
460 scriptencoding koi8-r
461 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
462 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
463 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
466 scriptencoding us-ascii
472 " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
473 let encodings = ['us-ascii']
474 if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
475 let encodings += ['utf-8']
476 elseif $LC_CTYPE == 'ru_RU.KOI8-R'
477 let encodings += ['koi8-r', 'utf-8']
478 elseif v:lc_time == 'Russian_Russia.1251'
479 let encodings += ['cp1251', 'utf-8']
484 execute 'set fileencoding=' . e
487 catch /E513: write error, conversion failed/
493 throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
508 set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
514 set wildmode=list:longest
515 set viminfo=!,h,'10,<100,s5
517 highlight NonText cterm=NONE ctermfg=NONE
520 if exists("$SLOWTERM")
526 " From http://slobin.pp.ru/vim/_vimrc.html
528 " These options will be kept between editing sessions
531 " Called automagically after .viminfo and plugins are loaded, sets
532 " miscellaneous options from persistent global variables
533 " function! VimEnter()
534 " for optname in g:options
535 " let varname = "g:OPT_" . toupper(optname)
537 " execute "let &" . optname . " = " . varname
541 " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
542 " execute "winpos" g:WINPOSX g:WINPOSY
546 " Called automagically before .viminfo is saved, saves miscellaneous
547 " options into persistent global variables
548 " function! VimLeavePre()
549 " call filter(g:, 'v:key !~# "^OPT_"')
550 " for optname in g:options
551 " let varname = "g:OPT_" . toupper(optname)
552 " execute "let " . varname . " = &g:" . optname
555 " if has("gui_running")
556 " let g:WINPOSX = getwinposx()
557 " let g:WINPOSY = getwinposy()
561 " autocmd VimEnter * call VimEnter()
562 " autocmd VimLeavePre * call VimLeavePre()
565 " Called automagically after every buffer read, enables fileencoding
566 " setting from modeline (see Tip #911: http://vim.wikia.com/wiki/VimTip911)
567 function! AutoEncoding()
568 if &modified && &fileencoding != ""
569 call SetupEncoding(&fileencoding)
573 autocmd! auto-encoding
574 augroup! auto-encoding
577 augroup auto-encoding
579 autocmd BufWinEnter * call AutoEncoding()
585 " Value of a character under cursor; better than standard '0x%02B (%b)'
587 let char = matchstr(getline("."), ".", col(".") - 1)
589 let char = iconv(char, &encoding, &fileencoding)
590 let format = "0x%02X <%d>"
592 let format = "0x%02X (%d)"
594 let char = char2nr(char)
595 return printf(format, char, char)
600 " Helper function for :DecodeQP and :DecodeURL commands
601 function! DecodeHex(arg)
602 return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
605 " Custom completion for encoding names
606 function! EncList(ArgLead, CmdLine, CursorPos)
607 return filter(split(&fileencodings, ','),
608 \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
612 " Command for decoding qp-encoded text
613 command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
614 \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
616 " Command for decoding url-encoded text
617 command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
618 \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
624 function! SetupSpell()
625 if &fileencoding =~ 'ascii'
626 setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
627 elseif &fileencoding == 'koi8-r'
628 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
629 elseif &fileencoding == 'utf-8'
630 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
632 setlocal spelllang= spellfile=
635 autocmd BufReadPost * call SetupSpell()
639 function! SyntaxName()
640 echomsg synIDattr(synID(line("."), col("."), 1), "name")
646 python << END_OF_PYTHON
648 import sys, rlcompleter, unicodedata, vim
649 from itertools import *
650 vim_complete = rlcompleter.Completer().complete
653 """Implementation of CompList() function"""
654 arglead = vim.eval("a:ArgLead")
655 fence = int(vim.eval("match(a:ArgLead, '\(\w\|\.\)*$')"))
656 left, right = arglead[:fence], arglead[fence:]
658 completions = (vim_complete(right, i) for i in count())
659 candidates = list(takewhile(bool, completions))
662 suggestions = [left + x for x in candidates]
663 vim.command("return " + repr(suggestions))
665 def vim_calc(command):
666 """Implementation of :Calc command"""
669 result = eval(command)
671 exec command in globals()
676 xx = ''.join('\\x%02x' % ord(x) for x in str(_))
677 vim.command('let @" = "%s"' % xx)
679 def vim_pydo(command):
680 """Implementation of :Pydo command"""
681 codeobj = compile(command, "command", "eval")
682 line1 = vim.current.range.start
683 line2 = vim.current.range.end
685 for numz in range(line1, line2+1):
686 line = vim.current.buffer[numz-delta]
687 uline = unicode(line, vim.eval('&fileencoding'))
690 result = eval(codeobj, globals(), locals())
691 if result is None or result is False:
692 del vim.current.buffer[numz-delta]
695 if isinstance(result, list) or isinstance(result, tuple):
696 result = " ".join(map(str, result))
699 vim.current.buffer[numz-delta] = result
701 def vim_unicode_name():
703 char = vim.eval("matchstr(getline('.'), '.', col('.') - 1)")
704 print map(unicodedata.name, char.decode(vim.eval("&encoding")))
705 except (AttributeError, ValueError), target:
706 print "%s: %s" % (target.__class__.__name__, target.message)
710 " Custom completion for python expressions
711 function! CompList(ArgLead, CmdLine, CursorPos)
712 python vim_comp_list()
715 " Python command line calculator
716 command! -nargs=+ -range -complete=customlist,CompList Calc
717 \ <line1>,<line2> python vim_calc(<q-args>)
719 " Python text range filter
720 command! -nargs=+ -range -complete=customlist,CompList Pydo
721 \ <line1>,<line2> python vim_pydo(<q-args>)
723 " Display unicode name for the character under cursor
724 command! Uname python vim_unicode_name()
725 command! UName call Uname()
730 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
731 set secure " safer working with script files in the current directory