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
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}
81 set mouse=ar " Use mouse in all modes, plus hit-return
83 " 12 messages and info
85 set ruler " Show cursor position below each window
86 set showcmd " Show (partial) command keys in the status line
88 " Short message for [Modified];
89 " overwrite message for writing a file with subsequent message;
90 " truncate long file messages
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
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
107 " 15 tabs and indenting
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>
114 set noautoindent " Do not automatically set the indent of a new line
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
120 " 19 reading and writing files
122 set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
127 " list of directories for the swap file; remove . (the current directory)
129 set directory=$TEMP//,c:/tmp//,c:/temp//
131 set directory=~/tmp//,/var/tmp//,/tmp//
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.
138 " 21 command line editing
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
146 " 22 executing external commands
149 set noshelltemp " Use pipes on Unix
152 " 25 multi-byte characters
154 " Automatically detected character encodings
155 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
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.
166 set viminfo=!,h,'50,\"1000
168 set viminfo=!,h,'50,<1000,s10
171 " c - convert viminfo to the current encoding;
176 " Removable media paths
183 if has("gui_running")
187 "set guifont=Courier_New:h18:cRUSSIAN
188 set guifont=Lucida_Console:h18:cRUSSIAN
190 set guifont=Monospace\ 16
191 set toolbar=icons,text " how to show the toolbar
194 set guicursor+=a:blinkon0 " Stop cursor blinking
196 " Make shift-insert work like in Xterm
197 " map <S-Insert> <MiddleMouse>
198 " map! <S-Insert> <MiddleMouse>
201 " From http://slobin.pp.ru/vim/_vimrc.html
203 " Arrows should go into wrapped lines, but not while popup menu is visible
204 imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
205 imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
207 " The <CR> key should select from completion menu without adding a newline
208 imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
212 if (&term =~ "linux") || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
214 " Background of the terminal is black or dark grey
220 if (&term =~ "linux")
221 execute 'set t_kb=' . nr2char(127)
224 if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
225 execute 'set t_kb=' . nr2char(127)
227 " 'autoselect' to always put selected text on the clipboard;
228 " 'unnamed' to use the * register like unnamed register '*'
229 " for all yank, delete and put operations;
230 " This allows to use mouse for copy/paste in local xterm,
231 " but prevents to save the unnamed register between sessions.
232 " set clipboard=autoselect,unnamed,exclude:cons\|linux
244 if (&term =~ "screen")
245 set ttymouse=xterm2 " Enable mouse codes under screen/tmux
247 " Enable window title under screen/tmux
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 runtime macros/matchit.vim
267 " Reread me after editing
268 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
271 " Save all files before running any quickfix command (grep, makeprg, etc.)
272 autocmd QuickFixCmdPre * wall
275 " Syntax highlighting
276 autocmd BufReadPost * syntax on
279 " Restore last known cursor position
280 function! RestorePosition()
281 if exists('b:position_restored')
286 call cursor(line("'\""), col("'\""))
288 let b:position_restored = 1
291 " When editing a file, always jump to the last cursor position (if saved)
292 autocmd BufReadPost * call RestorePosition()
295 function! SetupEncoding(encoding)
296 if !has("iconv") || exists('b:encoding_set') || strlen(a:encoding) == 0
300 call RestorePosition()
301 let b:encoding_set = 1
302 execute "edit ++enc=" . a:encoding
306 " http://lwn.net/Articles/226514/
309 " Remove ALL autocommands for the current group.
311 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
312 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
313 autocmd BufReadPost *.gpg :%!gpg -q -d
314 autocmd BufReadPost *.gpg | redraw
315 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
316 autocmd BufWritePost *.gpg u
317 autocmd VimLeave *.gpg :!clear
319 " BufReadPost: use "openssl bf -d -a"
320 " BufWritePre: use "openssl bf -salt -a"
333 function! SetNoWrap()
340 command! SetWrap call SetWrap()
341 command! SetNoWrap call SetNoWrap()
343 " b:wrap can be set by an ftplugin
344 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
349 " Do not unindent #-comment
354 " map <C-Z> :shell<CR>
360 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"
362 function! ExtractURL()
363 let line = getline('.')
364 let parts = split(line, s:URL_re . '\zs')
367 throw 'ExtractURLCannotFindURL' " No URL found
371 let column = col('.')
374 let save_length = length
381 let pos = match(p, s:URL_re)
383 throw 'ExtractURLCannotFindURL' " No URL found
386 if save_length + pos >= column " cursor left of the URL
387 throw 'ExtractURLCannotFindURL'
390 return strpart(p, pos)
393 function! EscapeURL(url)
394 let url = substitute(a:url, ' ', '%20', 'g')
395 return escape(url, '!#$%')
398 function! OpenURL(url, newwin)
399 execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
402 function! ExtractOpenURL(newwin)
404 let url = ExtractURL()
405 catch /^ExtractURLCannotFindURL$/
406 echoerr 'No URL found under cursor'
410 call OpenURL(url, a:newwin)
413 function! EncodeOpenURL(url, newwin)
414 execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
418 " Send current link to a browser
419 nmap \b :call ExtractOpenURL('')<CR>
420 nmap \w :call ExtractOpenURL('-n')<CR>
421 nmap \t :call ExtractOpenURL('-t')<CR>
422 " Send visual block to a browser
423 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
424 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
425 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
426 " Encode and send visual block to a browser
427 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
428 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
429 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
430 " Send current file's name to a browser
431 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
432 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
433 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
435 endif " version >= 700
440 if has("spell") " Works in 7.0+
441 " Use builtin spellchecker
442 nmap \sv :syntax off <BAR> setlocal spell<CR>
444 nmap \sn :syntax on <BAR> setlocal nospell<CR>
448 " Russian letters mapped in normal mode
450 " set keymap=russian-jcuken
455 " langmap in utf-8 mode requires at least Vim 7.2.109
457 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
458 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
459 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
461 elseif &encoding != 'utf-8'
462 scriptencoding koi8-r
463 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
464 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
465 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
468 scriptencoding us-ascii
474 " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
475 let encodings = ['us-ascii']
476 if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
477 let encodings += ['utf-8']
478 elseif $LC_CTYPE == 'ru_RU.KOI8-R'
479 let encodings += ['koi8-r', 'utf-8']
480 elseif v:lc_time == 'Russian_Russia.1251'
481 let encodings += ['cp1251', 'utf-8']
486 execute 'set fileencoding=' . e
489 catch /E513: write error, conversion failed/
495 throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
510 set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
516 set wildmode=list:longest
517 set viminfo=!,h,'10,<100,s5
519 highlight NonText cterm=NONE ctermfg=NONE
522 if exists("$SLOWTERM")
528 " From http://slobin.pp.ru/vim/_vimrc.html
530 " These options will be kept between editing sessions
533 " Called automagically after .viminfo and plugins are loaded, sets
534 " miscellaneous options from persistent global variables
535 " function! VimEnter()
536 " for optname in g:options
537 " let varname = "g:OPT_" . toupper(optname)
539 " execute "let &" . optname . " = " . varname
543 " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
544 " execute "winpos" g:WINPOSX g:WINPOSY
548 " Called automagically before .viminfo is saved, saves miscellaneous
549 " options into persistent global variables
550 " function! VimLeavePre()
551 " call filter(g:, 'v:key !~# "^OPT_"')
552 " for optname in g:options
553 " let varname = "g:OPT_" . toupper(optname)
554 " execute "let " . varname . " = &g:" . optname
557 " if has("gui_running")
558 " let g:WINPOSX = getwinposx()
559 " let g:WINPOSY = getwinposy()
563 " autocmd VimEnter * call VimEnter()
564 " autocmd VimLeavePre * call VimLeavePre()
567 " Called automagically after every buffer read, enables fileencoding
568 " setting from modeline (see Tip #911: http://vim.wikia.com/wiki/VimTip911)
569 function! AutoEncoding()
570 if &modified && &fileencoding != ""
571 call SetupEncoding(&fileencoding)
575 autocmd! auto-encoding
576 augroup! auto-encoding
579 augroup auto-encoding
581 autocmd BufWinEnter * call AutoEncoding()
587 " Value of a character under cursor; better than standard '0x%02B (%b)'
589 let char = matchstr(getline("."), ".", col(".") - 1)
591 let char = iconv(char, &encoding, &fileencoding)
592 let format = "0x%02X <%d>"
594 let format = "0x%02X (%d)"
596 let char = char2nr(char)
597 return printf(format, char, char)
602 " Helper function for :DecodeQP and :DecodeURL commands
603 function! DecodeHex(arg)
604 return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
607 " Custom completion for encoding names
608 function! EncList(ArgLead, CmdLine, CursorPos)
609 return filter(split(&fileencodings, ','),
610 \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
614 " Command for decoding qp-encoded text
615 command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
616 \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
618 " Command for decoding url-encoded text
619 command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
620 \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
626 function! SetupSpell()
627 if &fileencoding =~ 'ascii'
628 setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
629 elseif &fileencoding == 'koi8-r'
630 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
631 elseif &fileencoding == 'utf-8'
632 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
634 setlocal spelllang= spellfile=
637 autocmd BufReadPost * call SetupSpell()
641 function! SyntaxName()
642 echomsg synIDattr(synID(line("."), col("."), 1), "name")
648 python << END_OF_PYTHON
650 import sys, rlcompleter, unicodedata, vim
651 from itertools import *
652 vim_complete = rlcompleter.Completer().complete
655 """Implementation of CompList() function"""
656 arglead = vim.eval("a:ArgLead")
657 fence = int(vim.eval("match(a:ArgLead, '\(\w\|\.\)*$')"))
658 left, right = arglead[:fence], arglead[fence:]
660 completions = (vim_complete(right, i) for i in count())
661 candidates = list(takewhile(bool, completions))
664 suggestions = [left + x for x in candidates]
665 vim.command("return " + repr(suggestions))
667 def vim_calc(command):
668 """Implementation of :Calc command"""
671 result = eval(command)
673 exec command in globals()
678 xx = ''.join('\\x%02x' % ord(x) for x in str(_))
679 vim.command('let @" = "%s"' % xx)
681 def vim_pydo(command):
682 """Implementation of :Pydo command"""
683 codeobj = compile(command, "command", "eval")
684 line1 = vim.current.range.start
685 line2 = vim.current.range.end
687 for numz in range(line1, line2+1):
688 line = vim.current.buffer[numz-delta]
689 uline = unicode(line, vim.eval('&fileencoding'))
692 result = eval(codeobj, globals(), locals())
693 if result is None or result is False:
694 del vim.current.buffer[numz-delta]
697 if isinstance(result, list) or isinstance(result, tuple):
698 result = " ".join(map(str, result))
701 vim.current.buffer[numz-delta] = result
703 def vim_unicode_name():
705 char = vim.eval("matchstr(getline('.'), '.', col('.') - 1)")
706 print map(unicodedata.name, char.decode(vim.eval("&encoding")))
707 except (AttributeError, ValueError), target:
708 print "%s: %s" % (target.__class__.__name__, target.message)
712 " Custom completion for python expressions
713 function! CompList(ArgLead, CmdLine, CursorPos)
714 python vim_comp_list()
717 " Python command line calculator
718 command! -nargs=+ -range -complete=customlist,CompList Calc
719 \ <line1>,<line2> python vim_calc(<q-args>)
721 " Python text range filter
722 command! -nargs=+ -range -complete=customlist,CompList Pydo
723 \ <line1>,<line2> python vim_pydo(<q-args>)
725 " Display unicode name for the character under cursor
726 command! Uname python vim_unicode_name()
727 command! UName call Uname()
732 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
733 set secure " safer working with script files in the current directory