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
26 elseif filereadable($VIMRUNTIME . "/defaults.vim")
27 unlet! skip_defaults_vim
28 source $VIMRUNTIME/defaults.vim
31 " No, it is not VI, it is VIM! It is important to set this first, because this
32 " command resets many other options.
35 " Set behavior to xterm, not mswin
38 " 2 moving around, searching and patterns
40 set ignorecase " Ignore case in search patterns
41 set smartcase " Match 'word' case-insensitive and 'Word' case-sensitive
43 set nostartofline " Keep cursor's column
44 set whichwrap=b,s,h,l,<,>,[,],~ " Wrap to the previous/next line on all keys and ~ command
48 set display=lastline,uhex " Show the last line instead of '@'; show non-printable chars as <hex>
49 set lazyredraw " Do not update screen while executing macros
50 set list " listchars only works with 'list'
51 " Show tabs, non-breaking/trailing spaces, long lines
52 set listchars=tab:>_,nbsp:_,trail:_,extends:+,precedes:+
53 " Another usefull additions: eol:$,space:_
54 set scrolloff=0 " number of screen lines to show around the cursor
55 set wrap " Visually wrap long lines
57 " With 'set wrap' wrap long lines at a character in 'breakat'
58 " Please note 'nolist' is required to use 'linebreak'
59 set linebreak showbreak=+\ " A plus and a space
61 set sidescroll=1 " The minimal number of columns to scroll horizontally
66 set nohlsearch " Stop the search highlighting
70 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
71 set laststatus=2 " Always show status line
73 set splitbelow " A new window is put below of the current one
74 set splitright " A new window is put right of the current one
78 set ttyfast " terminal connection is fast
80 set title " Set title to the value of 'titlestring' or to 'filename - VIM'
81 set titleold= " string to restore the title to when exiting Vim
82 " String to use for the Vim window title; with statusline printf items:
83 " display filename, modification flag, full path, argument list status,
84 " the current user, host and program name (to distinguish vim/view/etc).
85 set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:p:h\")})%)%(\ %a%)\ -\ [%{$USER}@%{hostname()}]\ %{v:progname}
89 set mouse=ar " Use mouse in all modes, plus hit-return
91 " 12 messages and info
93 set ruler " Show cursor position below each window
94 set showcmd " Show (partial) command keys in the status line
96 " Short message for [Modified];
97 " overwrite message for writing a file with subsequent message;
98 " truncate long file messages
103 set backspace=indent,eol,start
104 set complete+=k " Scan spell dictionaries for completion in addition to standard places
105 set infercase " adjust case of a keyword completion match
106 set nojoinspaces " Do not insert two spaces after a '.', '?' and '!' with a join command
107 set nrformats=hex " I seldom edit octal numbers, but very often dates like 2001-02-01
109 " Default value 'croql' is a compromise for both natural and programming
110 " languages, but as any compromise it works good for neither natural nor
111 " programming languages. This value is good for natural texts,
112 " let ftplugins to set values suitable for programming languages.
113 set formatoptions=2t " list of flags that tell how automatic formatting works
115 " 15 tabs and indenting
117 set expandtab " expand <Tab> to spaces in Insert mode
118 set shiftwidth=3 " number of spaces used for each step of (auto)indent
119 set smarttab " a <Tab> in an indent inserts 'shiftwidth' spaces
120 set softtabstop=3 " number of spaces to insert for a <Tab>
122 set noautoindent " Do not automatically set the indent of a new line
126 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
128 " 19 reading and writing files
130 set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
135 let myUndoDir = expand('~/tmp/vim/undo')
136 if !isdirectory(myUndoDir)
138 call mkdir(myUndoDir, 'p')
141 " list of directories for the swap file; remove . (the current directory)
143 set directory=~/tmp/vim//,$TEMP//,c:/tmp//,c:/temp//
145 set directory=~/tmp/vim//,~/tmp//,/var/tmp//,/tmp//
147 " if a directory ends in two path separators "//"
148 " or "\\", the swap file name will be built from the complete path to
149 " the file with all path separators substituted to percent '%' signs.
150 " This will ensure file name uniqueness in the preserve directory.
152 " 21 command line editing
154 set history=1000 " how many command lines are remembered
155 set suffixes+=.pyc,.pyo " list of file name extensions that have a lower priority
156 set wildignore+=*.py[co] " Ignore these patterns when completing file names
157 set wildmenu " command-line completion shows a list of matches
158 set wildmode=longest,list:longest,full " Bash-vim completion behavior
160 " Keep undo history across sessions by storing it in a file
161 if has('persistent_undo')
162 let &undodir = myUndoDir
166 " 22 executing external commands
169 set noshelltemp " Use pipes on Unix
172 " 25 multi-byte characters
174 " Automatically detected character encodings
175 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
179 " ! - when included, save and restore global variables that start
180 " with an uppercase letter, and don't contain a lowercase letter;
181 " h - disable the effect of 'hlsearch';
182 " ' - number of files for which the marks are remembered;
183 " " and < - maximum number of lines saved for a register;
184 " s - maximum size of an item in Kbytes.
186 set viminfo=!,h,'50,\"1000
188 set viminfo=!,h,'50,<1000,s10
191 " c - convert viminfo to the current encoding;
196 " Removable media paths
203 if has("gui_running")
207 "set guifont=Courier_New:h18:cRUSSIAN
208 set guifont=Lucida_Console:h18:cRUSSIAN
210 set guifont=Monospace\ 16
211 set toolbar=icons,text " how to show the toolbar
214 set guicursor+=a:blinkon0 " Stop cursor blinking
216 " Make shift-insert work like in Xterm
217 " map <S-Insert> <MiddleMouse>
218 " map! <S-Insert> <MiddleMouse>
221 " From http://slobin.pp.ru/vim/_vimrc.html
223 " Arrows should go into wrapped lines, but not while popup menu is visible
224 imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
225 imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
227 " The <CR> key should select from completion menu without adding a newline
228 imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
232 if (&term =~ "linux") || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
234 " Background of the terminal is black or dark grey
240 if (&term =~ "linux")
241 execute 'set t_kb=' . nr2char(127)
244 if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
245 execute 'set t_kb=' . nr2char(127)
256 " 'autoselect' to always put selected text on the clipboard;
257 " 'unnamed' to use the * register like unnamed register '*'
258 " for all yank, delete and put operations;
259 " This allows to use mouse for copy/paste in local xterm,
260 " but prevents to save the unnamed register between sessions.
261 " set clipboard=autoselect,unnamed,exclude:cons\|linux
263 " Use xclip to copy/paste to/from X clipboard at remote host
264 " vmap "+y :!xclip -i -sel clip
265 " map "+p :r!xclip -o -sel clip
266 " Enable X11Forwarding and use ssh -X or even -Y
269 if (&term =~ "screen")
270 set ttymouse=xterm2 " Enable mouse codes under screen/tmux
272 " Enable window title under screen/tmux
278 " Automatically set paste mode in Vim when pasting in bracketed paste mode
279 " https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
280 function! WrapForTmux(s)
285 let tmux_start = "\<Esc>Ptmux;"
286 let tmux_end = "\<Esc>\\"
288 return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
291 let &t_SI .= WrapForTmux("\<Esc>[?2004h")
292 let &t_EI .= WrapForTmux("\<Esc>[?2004l")
294 function! XTermPasteBegin()
295 set pastetoggle=<Esc>[201~
300 inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()
303 " Multiline comments often confuse vim syntax highlighting - these maps
304 " allow to resynchronize; the first is faster, the second is more thorough
305 nmap \sc :syntax sync clear<Enter>
306 nmap \ss :syntax sync fromstart<Enter>
311 " Enable filetype detection
312 filetype plugin indent on
314 runtime macros/matchit.vim
316 " Reread me after editing
317 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
320 " Save all files before running any quickfix command (grep, makeprg, etc.)
321 autocmd QuickFixCmdPre * wall
322 " automatically close quickfix if it's the only window left
323 autocmd WinEnter * if winnr('$') == 1 &&
324 \ index(["nofile", "quickfix"], &buftype) >= 0 | quit | endif
327 " Syntax highlighting
328 autocmd BufReadPost * syntax on
331 " Restore last known cursor position
332 function! RestorePosition()
333 if exists('b:position_restored')
338 call cursor(line("'\""), col("'\""))
340 let b:position_restored = 1
343 " When editing a file, always jump to the last cursor position (if saved)
344 autocmd BufReadPost * call RestorePosition()
347 function! SetupEncoding(encoding)
348 if !has("iconv") || exists('b:encoding_set') || strlen(a:encoding) == 0
352 call RestorePosition()
353 let b:encoding_set = 1
355 execute "edit ++enc=" . a:encoding
360 " From http://lwn.net/Articles/226514/
363 " Remove ALL autocommands for the current group.
365 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
366 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
367 autocmd BufReadPost *.gpg :%!gpg -q -d
368 autocmd BufReadPost *.gpg | redraw
369 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
370 autocmd BufWritePost *.gpg u
371 autocmd VimLeave *.gpg :!clear
373 " BufReadPost: use "openssl bf -d -a"
374 " BufWritePre: use "openssl bf -salt -a"
387 function! SetNoWrap()
394 command! SetWrap call SetWrap()
395 command! SetNoWrap call SetNoWrap()
397 " b:wrap can be set by an ftplugin
398 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
403 " Do not unindent #-comment
408 " map <C-Z> :shell<CR>
414 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"
416 function! ExtractURL()
417 let line = getline('.')
418 let parts = split(line, s:URL_re . '\zs')
421 throw 'ExtractURLCannotFindURL' " No URL found
425 let column = col('.')
428 let save_length = length
435 let pos = match(p, s:URL_re)
437 throw 'ExtractURLCannotFindURL' " No URL found
440 if save_length + pos >= column " cursor left of the URL
441 throw 'ExtractURLCannotFindURL'
444 return strpart(p, pos)
447 function! EscapeURL(url)
448 let url = substitute(a:url, ' ', '%20', 'g')
449 return escape(url, '!#$%')
452 function! OpenURL(url, newwin)
453 execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
456 function! ExtractOpenURL(newwin)
458 let url = ExtractURL()
459 catch /^ExtractURLCannotFindURL$/
460 echoerr 'No URL found under cursor'
464 call OpenURL(url, a:newwin)
467 function! EncodeOpenURL(url, newwin)
468 execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
472 " Send current link to a browser
473 nmap \b :call ExtractOpenURL('')<CR>
474 nmap \w :call ExtractOpenURL('-n')<CR>
475 nmap \t :call ExtractOpenURL('-t')<CR>
476 " Send visual block to a browser
477 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
478 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
479 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
480 " Encode and send visual block to a browser
481 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
482 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
483 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
484 " Send current file's name to a browser
485 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
486 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
487 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
489 endif " version >= 700
494 if has("spell") " Works in 7.0+
495 " Use builtin spellchecker
496 nmap \sv :syntax off <BAR> setlocal spell<CR>
498 nmap \sn :syntax on <BAR> setlocal nospell<CR>
502 " Russian letters mapped in normal mode
504 " set keymap=russian-jcuken
509 " langmap in utf-8 mode requires at least Vim 7.2.109
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Б<Ю>
515 elseif &encoding != 'utf-8'
516 scriptencoding koi8-r
517 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
518 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
519 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
522 scriptencoding us-ascii
528 " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
529 let encodings = ['us-ascii']
530 if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
531 let encodings += ['utf-8']
532 elseif $LC_CTYPE == 'ru_RU.KOI8-R'
533 let encodings += ['koi8-r', 'utf-8']
534 elseif v:lc_time == 'Russian_Russia.1251'
535 let encodings += ['cp1251', 'utf-8']
540 execute 'set fileencoding=' . e
543 catch /E513: write error, conversion failed/
549 throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
564 set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
570 set wildmode=list:longest
571 set viminfo=!,h,'10,<100,s5
573 highlight NonText cterm=NONE ctermfg=NONE
576 if exists("$SLOWTERM")
582 pyfile ~/.vim/python/virtualenv.py
586 py3file ~/.vim/python/virtualenv.py
591 " http://vim.wikia.com/wiki/Setting_file_attributes_without_reloading_a_buffer
593 if executable('chmod')
594 function! SetExecutableBit(x)
596 " Avoid 'Reload Y/N?' question
597 autocmd FileChangedShell <buffer> call _BufChangedCB()
598 let fx = executable(expand("%:p"))
605 echoerr 'Error running chmod: ' . v:shell_error
609 function! _BufChangedCB()
610 autocmd! FileChangedShell <buffer>
612 command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
617 " From http://slobin.pp.ru/vim/_vimrc.html
619 " These options will be kept between editing sessions
622 " Called automagically after .viminfo and plugins are loaded, sets
623 " miscellaneous options from persistent global variables
624 " function! VimEnter()
625 " for optname in g:options
626 " let varname = "g:OPT_" . toupper(optname)
628 " execute "let &" . optname . " = " . varname
632 " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
633 " execute "winpos" g:WINPOSX g:WINPOSY
637 " Called automagically before .viminfo is saved, saves miscellaneous
638 " options into persistent global variables
639 " function! VimLeavePre()
640 " call filter(g:, 'v:key !~# "^OPT_"')
641 " for optname in g:options
642 " let varname = "g:OPT_" . toupper(optname)
643 " execute "let " . varname . " = &g:" . optname
646 " if has("gui_running")
647 " let g:WINPOSX = getwinposx()
648 " let g:WINPOSY = getwinposy()
652 " autocmd VimEnter * call VimEnter()
653 " autocmd VimLeavePre * call VimLeavePre()
656 " Called automagically after every buffer read, enables fileencoding
657 " setting from modeline (see Tip #911:
658 " http://vim.wikia.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
659 function! AutoEncoding()
660 if &modified && &fileencoding != ""
661 call SetupEncoding(&fileencoding)
665 autocmd! auto-encoding
666 augroup! auto-encoding
669 augroup auto-encoding
671 autocmd BufWinEnter * call AutoEncoding()
677 " Value of a character under cursor; better than standard '0x%02B (%b)'
679 let char = matchstr(getline("."), ".", col(".") - 1)
681 let char = iconv(char, &encoding, &fileencoding)
682 let format = "0x%02X <%d>"
684 let format = "0x%02X (%d)"
686 let char = char2nr(char)
687 return printf(format, char, char)
692 " Helper function for :DecodeQP and :DecodeURL commands
693 function! DecodeHex(arg)
694 return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
697 " Custom completion for encoding names
698 function! EncList(ArgLead, CmdLine, CursorPos)
699 return filter(split(&fileencodings, ','),
700 \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
704 " Command for decoding qp-encoded text
705 command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
706 \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
708 " Command for decoding url-encoded text
709 command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
710 \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
716 function! SetupSpell()
717 if &fileencoding =~ 'ascii'
718 setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
719 elseif &fileencoding == 'koi8-r'
720 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
721 elseif &fileencoding == 'utf-8'
722 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
724 setlocal spelllang= spellfile=
727 autocmd BufReadPost * call SetupSpell()
731 function! SyntaxName()
732 echomsg synIDattr(synID(line("."), col("."), 1), "name")
737 pyfile ~/.vim/python/completion.py
739 " Custom completion for python expressions
740 function! CompList(ArgLead, CmdLine, CursorPos)
741 python vim_comp_list()
744 " Python command line calculator
745 command! -nargs=+ -range -complete=customlist,CompList Calc
746 \ <line1>,<line2> python vim_calc(<q-args>)
748 " Python text range filter
749 command! -nargs=+ -range -complete=customlist,CompList Pydo
750 \ <line1>,<line2> python vim_pydo(<q-args>)
752 " Display unicode name for the character under cursor
753 command! Uname python vim_unicode_name()
757 py3file ~/.vim/python/completion.py
759 " Custom completion for python expressions
760 function! CompList(ArgLead, CmdLine, CursorPos)
761 python3 vim_comp_list()
764 " Python command line calculator
765 command! -nargs=+ -range -complete=customlist,CompList Calc
766 \ <line1>,<line2> python3 vim_calc(<q-args>)
768 " Python text range filter
769 command! -nargs=+ -range -complete=customlist,CompList Pydo
770 \ <line1>,<line2> python3 vim_pydo(<q-args>)
772 " Display unicode name for the character under cursor
773 command! Uname python3 vim_unicode_name()
776 if has("python") || has("python3")
781 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
782 set secure " safer working with script files in the current directory