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 " Show tabs, non-breaking/trailing spaces, long lines
48 set listchars=tab:>_,nbsp:_,trail:_,extends:+,precedes:+
49 " Another usefull additions: eol:$,space:_
50 set wrap " Visually wrap long lines
52 " With 'set wrap' wrap long lines at a character in 'breakat'
53 " Please note 'nolist' is required to use 'linebreak'
54 set linebreak showbreak=+\ " A plus and a space
56 set sidescroll=1 " The minimal number of columns to scroll horizontally
61 set nohlsearch " Stop the search highlighting
65 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
66 set laststatus=2 " Always show status line
68 set splitbelow " A new window is put below of the current one
69 set splitright " A new window is put right of the current one
73 set ttyfast " terminal connection is fast
75 set title " Set title to the value of 'titlestring' or to 'filename - VIM'
76 set titleold= " string to restore the title to when exiting Vim
77 " String to use for the Vim window title; with statusline printf items:
78 " display filename, modification flag, full path, argument list status,
79 " the current user, host and program name (to distinguish vim/view/etc).
80 set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:p:h\")})%)%(\ %a%)\ -\ [%{$USER}@%{hostname()}]\ %{v:progname}
84 set mouse=ar " Use mouse in all modes, plus hit-return
86 " 12 messages and info
88 set ruler " Show cursor position below each window
89 set showcmd " Show (partial) command keys in the status line
91 " Short message for [Modified];
92 " overwrite message for writing a file with subsequent message;
93 " truncate long file messages
98 set backspace=indent,eol,start
99 set complete+=k " Scan spell dictionaries for completion in addition to standard places
100 set infercase " adjust case of a keyword completion match
101 set nojoinspaces " Do not insert two spaces after a '.', '?' and '!' with a join command
102 set nrformats=hex " I seldom edit octal numbers, but very often dates like 2001-02-01
104 " Default value 'croql' is a compromise for both natural and programming
105 " languages, but as any compromise it works good for neither natural nor
106 " programming languages. This value is good for natural texts,
107 " let ftplugins to set values suitable for programming languages.
108 set formatoptions=2t " list of flags that tell how automatic formatting works
110 " 15 tabs and indenting
112 set expandtab " expand <Tab> to spaces in Insert mode
113 set shiftwidth=3 " number of spaces used for each step of (auto)indent
114 set smarttab " a <Tab> in an indent inserts 'shiftwidth' spaces
115 set softtabstop=3 " number of spaces to insert for a <Tab>
117 set noautoindent " Do not automatically set the indent of a new line
121 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
123 " 19 reading and writing files
125 set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
130 let myUndoDir = expand('~/tmp/vim/undo')
131 if !isdirectory(myUndoDir)
133 call mkdir(myUndoDir, 'p')
136 " list of directories for the swap file; remove . (the current directory)
138 set directory=~/tmp/vim//,$TEMP//,c:/tmp//,c:/temp//
140 set directory=~/tmp/vim//,~/tmp//,/var/tmp//,/tmp//
142 " if a directory ends in two path separators "//"
143 " or "\\", the swap file name will be built from the complete path to
144 " the file with all path separators substituted to percent '%' signs.
145 " This will ensure file name uniqueness in the preserve directory.
147 " 21 command line editing
149 set history=1000 " how many command lines are remembered
150 set suffixes+=.pyc,.pyo " list of file name extensions that have a lower priority
151 set wildignore+=*.py[co] " Ignore these patterns when completing file names
152 set wildmenu " command-line completion shows a list of matches
153 set wildmode=longest,list:longest,full " Bash-vim completion behavior
155 " Keep undo history across sessions by storing it in a file
156 if has('persistent_undo')
157 let &undodir = myUndoDir
161 " 22 executing external commands
164 set noshelltemp " Use pipes on Unix
167 " 25 multi-byte characters
169 " Automatically detected character encodings
170 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
174 " ! - when included, save and restore global variables that start
175 " with an uppercase letter, and don't contain a lowercase letter;
176 " h - disable the effect of 'hlsearch';
177 " ' - number of files for which the marks are remembered;
178 " " and < - maximum number of lines saved for a register;
179 " s - maximum size of an item in Kbytes.
181 set viminfo=!,h,'50,\"1000
183 set viminfo=!,h,'50,<1000,s10
186 " c - convert viminfo to the current encoding;
191 " Removable media paths
198 if has("gui_running")
202 "set guifont=Courier_New:h18:cRUSSIAN
203 set guifont=Lucida_Console:h18:cRUSSIAN
205 set guifont=Monospace\ 16
206 set toolbar=icons,text " how to show the toolbar
209 set guicursor+=a:blinkon0 " Stop cursor blinking
211 " Make shift-insert work like in Xterm
212 " map <S-Insert> <MiddleMouse>
213 " map! <S-Insert> <MiddleMouse>
216 " From http://slobin.pp.ru/vim/_vimrc.html
218 " Arrows should go into wrapped lines, but not while popup menu is visible
219 imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
220 imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
222 " The <CR> key should select from completion menu without adding a newline
223 imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
227 if (&term =~ "linux") || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
229 " Background of the terminal is black or dark grey
235 if (&term =~ "linux")
236 execute 'set t_kb=' . nr2char(127)
239 if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
240 execute 'set t_kb=' . nr2char(127)
251 " 'autoselect' to always put selected text on the clipboard;
252 " 'unnamed' to use the * register like unnamed register '*'
253 " for all yank, delete and put operations;
254 " This allows to use mouse for copy/paste in local xterm,
255 " but prevents to save the unnamed register between sessions.
256 " set clipboard=autoselect,unnamed,exclude:cons\|linux
258 " Use xclip to copy/paste to/from X clipboard at remote host
259 " vmap "+y :!xclip -i -sel clip
260 " map "+p :r!xclip -o -sel clip
261 " Enable X11Forwarding and use ssh -X or even -Y
264 if (&term =~ "screen")
265 set ttymouse=xterm2 " Enable mouse codes under screen/tmux
267 " Enable window title under screen/tmux
273 " Automatically set paste mode in Vim when pasting in bracketed paste mode
274 " https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
275 function! WrapForTmux(s)
280 let tmux_start = "\<Esc>Ptmux;"
281 let tmux_end = "\<Esc>\\"
283 return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
286 let &t_SI .= WrapForTmux("\<Esc>[?2004h")
287 let &t_EI .= WrapForTmux("\<Esc>[?2004l")
289 function! XTermPasteBegin()
290 set pastetoggle=<Esc>[201~
295 inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()
298 " Multiline comments often confuse vim syntax highlighting - these maps
299 " allow to resynchronize; the first is faster, the second is more thorough
300 nmap \sc :syntax sync clear<Enter>
301 nmap \ss :syntax sync fromstart<Enter>
306 " Enable filetype detection
307 filetype plugin indent on
309 runtime macros/matchit.vim
311 " Reread me after editing
312 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
315 " Save all files before running any quickfix command (grep, makeprg, etc.)
316 autocmd QuickFixCmdPre * wall
317 " automatically close quickfix if it's the only window left
318 autocmd WinEnter * if winnr('$') == 1 && &buftype == "quickfix" | quit | endif
321 " Syntax highlighting
322 autocmd BufReadPost * syntax on
325 " Restore last known cursor position
326 function! RestorePosition()
327 if exists('b:position_restored')
332 call cursor(line("'\""), col("'\""))
334 let b:position_restored = 1
337 " When editing a file, always jump to the last cursor position (if saved)
338 autocmd BufReadPost * call RestorePosition()
341 function! SetupEncoding(encoding)
342 if !has("iconv") || exists('b:encoding_set') || strlen(a:encoding) == 0
346 call RestorePosition()
347 let b:encoding_set = 1
349 execute "edit ++enc=" . a:encoding
354 " From http://lwn.net/Articles/226514/
357 " Remove ALL autocommands for the current group.
359 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
360 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
361 autocmd BufReadPost *.gpg :%!gpg -q -d
362 autocmd BufReadPost *.gpg | redraw
363 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
364 autocmd BufWritePost *.gpg u
365 autocmd VimLeave *.gpg :!clear
367 " BufReadPost: use "openssl bf -d -a"
368 " BufWritePre: use "openssl bf -salt -a"
381 function! SetNoWrap()
388 command! SetWrap call SetWrap()
389 command! SetNoWrap call SetNoWrap()
391 " b:wrap can be set by an ftplugin
392 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
397 " Do not unindent #-comment
402 " map <C-Z> :shell<CR>
408 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"
410 function! ExtractURL()
411 let line = getline('.')
412 let parts = split(line, s:URL_re . '\zs')
415 throw 'ExtractURLCannotFindURL' " No URL found
419 let column = col('.')
422 let save_length = length
429 let pos = match(p, s:URL_re)
431 throw 'ExtractURLCannotFindURL' " No URL found
434 if save_length + pos >= column " cursor left of the URL
435 throw 'ExtractURLCannotFindURL'
438 return strpart(p, pos)
441 function! EscapeURL(url)
442 let url = substitute(a:url, ' ', '%20', 'g')
443 return escape(url, '!#$%')
446 function! OpenURL(url, newwin)
447 execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
450 function! ExtractOpenURL(newwin)
452 let url = ExtractURL()
453 catch /^ExtractURLCannotFindURL$/
454 echoerr 'No URL found under cursor'
458 call OpenURL(url, a:newwin)
461 function! EncodeOpenURL(url, newwin)
462 execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
466 " Send current link to a browser
467 nmap \b :call ExtractOpenURL('')<CR>
468 nmap \w :call ExtractOpenURL('-n')<CR>
469 nmap \t :call ExtractOpenURL('-t')<CR>
470 " Send visual block to a browser
471 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
472 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
473 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
474 " Encode and send visual block to a browser
475 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
476 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
477 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
478 " Send current file's name to a browser
479 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
480 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
481 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
483 endif " version >= 700
488 if has("spell") " Works in 7.0+
489 " Use builtin spellchecker
490 nmap \sv :syntax off <BAR> setlocal spell<CR>
492 nmap \sn :syntax on <BAR> setlocal nospell<CR>
496 " Russian letters mapped in normal mode
498 " set keymap=russian-jcuken
503 " langmap in utf-8 mode requires at least Vim 7.2.109
505 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
506 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
507 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
509 elseif &encoding != 'utf-8'
510 scriptencoding koi8-r
511 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
512 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
513 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
516 scriptencoding us-ascii
522 " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
523 let encodings = ['us-ascii']
524 if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
525 let encodings += ['utf-8']
526 elseif $LC_CTYPE == 'ru_RU.KOI8-R'
527 let encodings += ['koi8-r', 'utf-8']
528 elseif v:lc_time == 'Russian_Russia.1251'
529 let encodings += ['cp1251', 'utf-8']
534 execute 'set fileencoding=' . e
537 catch /E513: write error, conversion failed/
543 throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
558 set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
564 set wildmode=list:longest
565 set viminfo=!,h,'10,<100,s5
567 highlight NonText cterm=NONE ctermfg=NONE
570 if exists("$SLOWTERM")
576 python << END_OF_PYTHON
579 virtualenv_dir = os.environ.get('VIRTUAL_ENV')
581 sys.path.insert(0, virtualenv_dir)
582 activate_this = os.path.join(virtualenv_dir, 'bin', 'activate_this.py')
583 execfile(activate_this, dict(__file__=activate_this))
589 " http://vim.wikia.com/wiki/Setting_file_attributes_without_reloading_a_buffer
591 if executable('chmod')
592 function! SetExecutableBit(x)
594 " Avoid 'Reload Y/N?' question
595 autocmd FileChangedShell <buffer> call _BufChangedCB()
596 let fx = executable(expand("%:p"))
603 echoerr 'Error running chmod: ' . v:shell_error
607 function! _BufChangedCB()
608 autocmd! FileChangedShell <buffer>
610 command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
615 " From http://slobin.pp.ru/vim/_vimrc.html
617 " These options will be kept between editing sessions
620 " Called automagically after .viminfo and plugins are loaded, sets
621 " miscellaneous options from persistent global variables
622 " function! VimEnter()
623 " for optname in g:options
624 " let varname = "g:OPT_" . toupper(optname)
626 " execute "let &" . optname . " = " . varname
630 " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
631 " execute "winpos" g:WINPOSX g:WINPOSY
635 " Called automagically before .viminfo is saved, saves miscellaneous
636 " options into persistent global variables
637 " function! VimLeavePre()
638 " call filter(g:, 'v:key !~# "^OPT_"')
639 " for optname in g:options
640 " let varname = "g:OPT_" . toupper(optname)
641 " execute "let " . varname . " = &g:" . optname
644 " if has("gui_running")
645 " let g:WINPOSX = getwinposx()
646 " let g:WINPOSY = getwinposy()
650 " autocmd VimEnter * call VimEnter()
651 " autocmd VimLeavePre * call VimLeavePre()
654 " Called automagically after every buffer read, enables fileencoding
655 " setting from modeline (see Tip #911:
656 " http://vim.wikia.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
657 function! AutoEncoding()
658 if &modified && &fileencoding != ""
659 call SetupEncoding(&fileencoding)
663 autocmd! auto-encoding
664 augroup! auto-encoding
667 augroup auto-encoding
669 autocmd BufWinEnter * call AutoEncoding()
675 " Value of a character under cursor; better than standard '0x%02B (%b)'
677 let char = matchstr(getline("."), ".", col(".") - 1)
679 let char = iconv(char, &encoding, &fileencoding)
680 let format = "0x%02X <%d>"
682 let format = "0x%02X (%d)"
684 let char = char2nr(char)
685 return printf(format, char, char)
690 " Helper function for :DecodeQP and :DecodeURL commands
691 function! DecodeHex(arg)
692 return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
695 " Custom completion for encoding names
696 function! EncList(ArgLead, CmdLine, CursorPos)
697 return filter(split(&fileencodings, ','),
698 \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
702 " Command for decoding qp-encoded text
703 command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
704 \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
706 " Command for decoding url-encoded text
707 command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
708 \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
714 function! SetupSpell()
715 if &fileencoding =~ 'ascii'
716 setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
717 elseif &fileencoding == 'koi8-r'
718 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
719 elseif &fileencoding == 'utf-8'
720 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
722 setlocal spelllang= spellfile=
725 autocmd BufReadPost * call SetupSpell()
729 function! SyntaxName()
730 echomsg synIDattr(synID(line("."), col("."), 1), "name")
736 python << END_OF_PYTHON
738 import sys, rlcompleter, unicodedata, vim
739 from itertools import *
740 vim_complete = rlcompleter.Completer().complete
743 """Implementation of CompList() function"""
744 arglead = vim.eval("a:ArgLead")
745 fence = int(vim.eval("match(a:ArgLead, '\(\w\|\.\)*$')"))
746 left, right = arglead[:fence], arglead[fence:]
748 completions = (vim_complete(right, i) for i in count())
749 candidates = list(takewhile(bool, completions))
752 suggestions = [left + x for x in candidates]
753 vim.command("return " + repr(suggestions))
755 def vim_calc(command):
756 """Implementation of :Calc command"""
759 result = eval(command)
761 exec command in globals()
766 xx = ''.join('\\x%02x' % ord(x) for x in str(_))
767 vim.command('let @" = "%s"' % xx)
769 def vim_pydo(command):
770 """Implementation of :Pydo command"""
771 codeobj = compile(command, "command", "eval")
772 line1 = vim.current.range.start
773 line2 = vim.current.range.end
775 for numz in range(line1, line2+1):
776 line = vim.current.buffer[numz-delta]
777 uline = unicode(line, vim.eval('&fileencoding'))
780 result = eval(codeobj, globals(), locals())
781 if result is None or result is False:
782 del vim.current.buffer[numz-delta]
785 if isinstance(result, list) or isinstance(result, tuple):
786 result = " ".join(map(str, result))
789 vim.current.buffer[numz-delta] = result
791 def vim_unicode_name():
793 char = vim.eval("matchstr(getline('.'), '.', col('.') - 1)")
794 print map(unicodedata.name, char.decode(vim.eval("&encoding")))
795 except (AttributeError, ValueError), target:
796 print "%s: %s" % (target.__class__.__name__, target.message)
800 " Custom completion for python expressions
801 function! CompList(ArgLead, CmdLine, CursorPos)
802 python vim_comp_list()
805 " Python command line calculator
806 command! -nargs=+ -range -complete=customlist,CompList Calc
807 \ <line1>,<line2> python vim_calc(<q-args>)
809 " Python text range filter
810 command! -nargs=+ -range -complete=customlist,CompList Pydo
811 \ <line1>,<line2> python vim_pydo(<q-args>)
813 " Display unicode name for the character under cursor
814 command! Uname python vim_unicode_name()
815 command! UName call Uname()
820 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
821 set secure " safer working with script files in the current directory