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 noincsearch " No incremental searching
42 set smartcase " Match 'word' case-insensitive and 'Word' case-sensitive
44 set nostartofline " Keep cursor's column
45 set whichwrap=b,s,h,l,<,>,[,],~ " Wrap to the previous/next line on all keys and ~ command
49 set display=lastline,uhex " Show the last line instead of '@'; show non-printable chars as <hex>
51 " Do not set it here, it breaks initial screen drawing and cursor positioning.
52 " See SetLazyRedraw at the end of the script.
53 " set lazyredraw " Do not update screen while executing macros
55 set list " listchars only works with 'list'
56 " Show tabs, non-breaking/trailing spaces, long lines
57 set listchars=tab:>_,nbsp:_,trail:_,extends:+,precedes:+
58 " Another usefull additions: eol:$,space:_
59 set scrolloff=0 " number of screen lines to show around the cursor
60 set wrap " Visually wrap long lines
62 " With 'set wrap' wrap long lines at a character in 'breakat'
63 " Please note 'nolist' is required to use 'linebreak'
64 set linebreak showbreak=+\ " A plus and a space
66 set sidescroll=1 " The minimal number of columns to scroll horizontally
71 set nohlsearch " Stop the search highlighting
75 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
76 set laststatus=2 " Always show status line
78 set splitbelow " A new window is put below of the current one
79 set splitright " A new window is put right of the current one
83 set ttyfast " terminal connection is fast
85 set title " Set title to the value of 'titlestring' or to 'filename - VIM'
86 set titleold= " string to restore the title to when exiting Vim
87 " String to use for the Vim window title; with statusline printf items:
88 " display filename, modification flag, full path, argument list status,
89 " the current user, host and program name (to distinguish vim/view/etc).
90 set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:p:h\")})%)%(\ %a%)\ -\ [%{$USER}@%{hostname()}]\ %{v:progname}
95 set mouse=ar " Use mouse in all modes, plus hit-return
98 " 12 messages and info
100 set ruler " Show cursor position below each window
101 set showcmd " Show (partial) command keys in the status line
102 set visualbell " Use visual bell instead of beeping
104 set belloff=error,insertmode " Do not ring the bell for these reasons
107 " Short message for [Modified];
108 " overwrite message for writing a file with subsequent message;
109 " truncate long file messages
114 set backspace=indent,eol,start
115 set complete+=k " Scan spell dictionaries for completion in addition to standard places
116 set infercase " adjust case of a keyword completion match
117 set nojoinspaces " Do not insert two spaces after a '.', '?' and '!' with a join command
118 set nrformats=hex " I seldom edit octal numbers, but very often dates like 2001-02-01
120 " Default value 'croql' is a compromise for both natural and programming
121 " languages, but as any compromise it works good for neither natural nor
122 " programming languages. This value is good for natural texts,
123 " let ftplugins to set values suitable for programming languages.
124 set formatoptions=2t " list of flags that tell how automatic formatting works
126 " 15 tabs and indenting
128 set expandtab " expand <Tab> to spaces in Insert mode
129 set shiftwidth=3 " number of spaces used for each step of (auto)indent
130 set smarttab " a <Tab> in an indent inserts 'shiftwidth' spaces
131 set softtabstop=3 " number of spaces to insert for a <Tab>
133 set noautoindent " Do not automatically set the indent of a new line
137 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
139 " 19 reading and writing files
141 set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
146 let myUndoDir = expand('~/tmp/vim/undo')
147 if !isdirectory(myUndoDir)
149 call mkdir(myUndoDir, 'p')
152 " list of directories for the swap file; remove . (the current directory)
154 set directory=~/tmp/vim//,$TEMP//,c:/tmp//,c:/temp//
156 set directory=~/tmp/vim//,~/tmp//,/var/tmp//,/tmp//
158 " if a directory ends in two path separators "//"
159 " or "\\", the swap file name will be built from the complete path to
160 " the file with all path separators substituted to percent '%' signs.
161 " This will ensure file name uniqueness in the preserve directory.
163 " 21 command line editing
165 set history=1000 " how many command lines are remembered
166 set suffixes+=.pyc,.pyo " list of file name extensions that have a lower priority
167 set wildignore+=*.py[co] " Ignore these patterns when completing file names
168 set wildmenu " command-line completion shows a list of matches
169 set wildmode=longest,list:longest,full " Bash-vim completion behavior
171 " Keep undo history across sessions by storing it in a file
172 if has('persistent_undo')
173 let &undodir = myUndoDir
177 " 22 executing external commands
180 set noshelltemp " Use pipes on Unix
183 " 25 multi-byte characters
185 " Automatically detected character encodings
186 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
190 " ! - when included, save and restore global variables that start
191 " with an uppercase letter, and don't contain a lowercase letter;
192 " h - disable the effect of 'hlsearch';
193 " ' - number of files for which the marks are remembered;
194 " " and < - maximum number of lines saved for a register;
195 " s - maximum size of an item in Kbytes.
200 set viminfo+=<1000,s10
203 " c - convert viminfo to the current encoding;
208 " Removable media paths
215 if has("gui_running")
219 "set guifont=Courier_New:h18:cRUSSIAN
220 set guifont=Lucida_Console:h18:cRUSSIAN
222 set guifont=Monospace\ 16
223 set toolbar=icons,text " how to show the toolbar
226 set guicursor+=n:block " Block cursor in normal mode
227 set guicursor+=i:ver10 " Solid vertical bar in insert mode
228 set guicursor+=a:blinkon0 " Stop cursor blinking
230 " Make shift-insert work like in Xterm
231 " map <S-Insert> <MiddleMouse>
232 " map! <S-Insert> <MiddleMouse>
235 " From http://slobin.pp.ru/vim/_vimrc.html
237 " Arrows should go into wrapped lines, but not while popup menu is visible
238 imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
239 imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
241 " The <CR> key should select from completion menu without adding a newline
242 imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
246 if (&term =~ "linux") || (&term =~ "cygwin") || (&term =~ "putty")
247 \ || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
249 " Background of the terminal is black or dark grey
255 if (&term =~ "linux")
256 execute 'set t_kb=' . nr2char(127)
259 if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
260 execute 'set t_kb=' . nr2char(127)
271 " 'autoselect' to always put selected text on the clipboard;
272 " 'unnamed' to use the * register like unnamed register '*'
273 " for all yank, delete and put operations;
274 " This allows to use mouse for copy/paste in local xterm,
275 " but prevents to save the unnamed register between sessions.
276 " set clipboard=autoselect,unnamed,exclude:cons\|linux
278 " Use xclip to copy/paste to/from X clipboard at remote host
279 " vmap "+y :!xclip -i -sel clip
280 " map "+p :r!xclip -o -sel clip
281 " Enable X11Forwarding and use ssh -X or even -Y
284 if (&term =~ "screen")
285 set ttymouse=xterm2 " Enable mouse codes under screen/tmux
287 " Enable window title under screen/tmux
293 " Bracketed paste mode
294 " https://github.com/ConradIrwin/vim-bracketed-paste/blob/master/plugin/bracketed-paste.vim
295 let &t_ti .= "\<Esc>[?2004h"
296 let &t_te = "\e[?2004l" . &t_te
298 function! XTermPasteBegin(ret)
299 set pastetoggle=<f29>
304 execute "set <f28>=\<Esc>[200~"
305 execute "set <f29>=\<Esc>[201~"
306 map <expr> <f28> XTermPasteBegin("i")
307 imap <expr> <f28> XTermPasteBegin("")
308 vmap <expr> <f28> XTermPasteBegin("c")
312 "https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
313 " https://ttssh2.osdn.jp/manual/en/usage/tips/vim.html
314 function! WrapForScreenTmux(s)
315 if (&term =~ "screen")
316 let scr_start = "\<Esc>P"
317 let scr_end = "\<Esc>\\"
319 return scr_start . a:s . scr_end
323 let tmux_start = "\<Esc>Ptmux;"
324 let tmux_end = "\<Esc>\\"
326 return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
332 " https://vim.fandom.com/wiki/Change_cursor_shape_in_different_modes
333 let &t_EI.=WrapForScreenTmux("\e[2 q") "EI = NORMAL mode (ELSE)
334 let &t_SI.=WrapForScreenTmux("\e[6 q") "SI = INSERT mode
336 let &t_SR.=WrapForScreenTmux("\e[4 q") "SR = REPLACE mode
340 " 1 -> blinking block
342 " 3 -> blinking underscore
343 " 4 -> solid underscore
344 " 5 -> blinking vertical bar
345 " 6 -> solid vertical bar
348 " Multiline comments often confuse vim syntax highlighting - these maps
349 " allow to resynchronize; the first is faster, the second is more thorough
350 nmap \sc :syntax sync clear<Enter>
351 nmap \ss :syntax sync fromstart<Enter>
356 " Enable filetype detection
357 filetype plugin indent on
359 runtime macros/matchit.vim
361 " Reread me after editing
362 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
365 " Save all files before running any quickfix command (grep, makeprg, etc.)
366 autocmd QuickFixCmdPre * wall
367 " automatically close quickfix if it's the only window left
368 autocmd WinEnter * if winnr('$') == 1 &&
369 \ index(["nofile", "quickfix"], &buftype) >= 0 | quit | endif
372 " Syntax highlighting
373 autocmd BufReadPost * syntax on
376 " Restore last known cursor position
377 function! RestorePosition()
378 if exists('b:position_restored')
383 call cursor(line("'\""), col("'\""))
385 let b:position_restored = 1
388 " When editing a file, always jump to the last cursor position (if saved)
389 autocmd BufReadPost * call RestorePosition()
392 function! SetupEncoding(encoding)
393 if !has("iconv") || exists('b:encoding_set') || empty(a:encoding)
397 call RestorePosition()
398 let b:encoding_set = 1
399 if !empty(expand('%'))
400 execute "edit ++enc=" . a:encoding
405 " From http://lwn.net/Articles/226514/
408 " Remove ALL autocommands for the current group.
410 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
411 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
412 autocmd BufReadPost *.gpg :%!gpg -q -d
413 autocmd BufReadPost *.gpg | redraw
414 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
415 autocmd BufWritePost *.gpg u
416 autocmd VimLeave *.gpg :!clear
418 " BufReadPost: use "openssl bf -d -a"
419 " BufWritePre: use "openssl bf -salt -a"
432 function! SetNoWrap()
439 command! SetWrap call SetWrap()
440 command! SetNoWrap call SetNoWrap()
442 " b:wrap can be set by an ftplugin
443 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
448 " Do not unindent #-comment
453 " map <C-Z> :shell<CR>
459 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"
461 function! ExtractURL()
462 let line = getline('.')
463 let parts = split(line, s:URL_re . '\zs')
466 throw 'ExtractURLCannotFindURL' " No URL found
470 let column = col('.')
473 let save_length = length
480 let pos = match(p, s:URL_re)
482 throw 'ExtractURLCannotFindURL' " No URL found
485 if save_length + pos >= column " cursor left of the URL
486 throw 'ExtractURLCannotFindURL'
489 return strpart(p, pos)
492 function! EscapeURL(url)
493 let url = substitute(a:url, ' ', '%20', 'g')
494 return escape(url, '!#$%')
497 function! OpenURL(url, newwin)
498 execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
501 function! ExtractOpenURL(newwin)
503 let url = ExtractURL()
504 catch /^ExtractURLCannotFindURL$/
505 echoerr 'No URL found under cursor'
509 call OpenURL(url, a:newwin)
512 function! EncodeOpenURL(url, newwin)
513 execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
517 " Send current link to a browser
518 nmap \b :call ExtractOpenURL('')<CR>
519 nmap \w :call ExtractOpenURL('-n')<CR>
520 nmap \t :call ExtractOpenURL('-t')<CR>
521 " Send visual block to a browser
522 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
523 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
524 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
525 " Encode and send visual block to a browser
526 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
527 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
528 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
529 " Send current file's name to a browser
530 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
531 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
532 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
534 endif " version >= 700
539 if has("spell") " Works in 7.0+
540 " Use builtin spellchecker
541 nmap \sv :syntax off <BAR> setlocal spell<CR>
543 nmap \sn :syntax on <BAR> setlocal nospell<CR>
547 " Russian letters mapped in normal mode
549 " set keymap=russian-jcuken
554 " langmap in utf-8 mode requires at least Vim 7.2.109
556 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
557 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
558 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
560 elseif &encoding != 'utf-8'
561 scriptencoding koi8-r
562 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
563 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
564 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
567 scriptencoding us-ascii
573 " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
574 let encodings = ['us-ascii']
575 if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
576 let encodings += ['utf-8']
577 elseif $LC_CTYPE == 'ru_RU.KOI8-R'
578 let encodings += ['koi8-r', 'utf-8']
579 elseif v:lc_time == 'Russian_Russia.1251'
580 let encodings += ['cp1251', 'utf-8']
585 execute 'set fileencoding=' . e
588 catch /E513: write error, conversion failed/
594 throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
609 set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
615 set wildmode=list:longest
616 set viminfo=!,h,'10,<100,s5
621 highlight NonText cterm=NONE ctermfg=NONE
624 if exists("$SLOWTERM")
630 pyfile ~/.vim/python/virtualenv.py
634 py3file ~/.vim/python/virtualenv.py
639 " http://vim.fandom.com/wiki/Setting_file_attributes_without_reloading_a_buffer
641 if executable('chmod')
642 function! SetExecutableBit(x)
644 " Avoid 'Reload Y/N?' question
645 autocmd FileChangedShell <buffer> call _BufChangedCB()
646 let fx = executable(expand("%:p"))
653 echoerr 'Error running chmod: ' . v:shell_error
656 autocmd! FileChangedShell <buffer>
658 function! _BufChangedCB()
659 autocmd! FileChangedShell <buffer>
661 command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
665 setlocal expandtab tabstop=8 softtabstop=4 shiftwidth=4
667 command! Code call Code()
670 setlocal expandtab tabstop=8 softtabstop=3 shiftwidth=3
672 command! Text call Text()
675 " From http://slobin.pp.ru/vim/_vimrc.html
677 " These options will be kept between editing sessions
680 " Called automagically after .viminfo and plugins are loaded, sets
681 " miscellaneous options from persistent global variables
682 " function! VimEnter()
683 " for optname in g:options
684 " let varname = "g:OPT_" . toupper(optname)
686 " execute "let &" . optname . " = " . varname
690 " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
691 " execute "winpos" g:WINPOSX g:WINPOSY
695 " Called automagically before .viminfo is saved, saves miscellaneous
696 " options into persistent global variables
697 " function! VimLeavePre()
698 " call filter(g:, 'v:key !~# "^OPT_"')
699 " for optname in g:options
700 " let varname = "g:OPT_" . toupper(optname)
701 " execute "let " . varname . " = &g:" . optname
704 " if has("gui_running")
705 " let g:WINPOSX = getwinposx()
706 " let g:WINPOSY = getwinposy()
710 " autocmd VimEnter * call VimEnter()
711 " autocmd VimLeavePre * call VimLeavePre()
714 " Called automagically after every buffer read, enables fileencoding
715 " setting from modeline (see Tip #911:
716 " http://vim.fandom.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
717 function! AutoEncoding()
718 if &modified && &fileencoding != ""
719 call SetupEncoding(&fileencoding)
721 autocmd! auto-encoding
722 augroup! auto-encoding
725 augroup auto-encoding
727 autocmd BufWinEnter * call AutoEncoding()
733 " Value of a character under cursor; better than standard '0x%02B (%b)'
735 let char = matchstr(getline("."), ".", col(".") - 1)
737 let char = iconv(char, &encoding, &fileencoding)
738 let format = "0x%02X <%d>"
740 let format = "0x%02X (%d)"
742 let char = char2nr(char)
743 return printf(format, char, char)
748 " Helper function for :DecodeQP and :DecodeURL commands
749 function! DecodeHex(arg)
750 return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
753 " Custom completion for encoding names
754 function! EncList(ArgLead, CmdLine, CursorPos)
755 return filter(split(&fileencodings, ','),
756 \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
760 " Command for decoding qp-encoded text
761 command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
762 \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
764 " Command for decoding url-encoded text
765 command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
766 \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
772 function! SetupSpell()
773 if &fileencoding =~ 'ascii'
774 setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
775 elseif &fileencoding == 'koi8-r'
776 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
777 elseif &fileencoding == 'utf-8'
778 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
780 setlocal spelllang= spellfile=
783 autocmd BufReadPost * call SetupSpell()
785 function! SaveSpell()
786 if expand('%:p') == expand('~/.vim/spell/en.ascii.add')
792 autocmd BufWritePost ~/.vim/spell/*.add call SaveSpell()
796 function! SyntaxName()
797 echomsg synIDattr(synID(line("."), col("."), 1), "name")
802 pyfile ~/.vim/python/completion.py
804 " Custom completion for python expressions
805 function! CompList(ArgLead, CmdLine, CursorPos)
806 python vim_comp_list()
809 " Python command line calculator
810 command! -nargs=+ -range -complete=customlist,CompList Calc
811 \ <line1>,<line2> python vim_calc(<q-args>)
813 " Python text range filter
814 command! -nargs=+ -range -complete=customlist,CompList Pydo
815 \ <line1>,<line2> python vim_pydo(<q-args>)
817 " Display unicode name for the character under cursor
818 command! Uname python vim_unicode_name()
822 py3file ~/.vim/python/completion.py
824 " Custom completion for python expressions
825 function! CompList(ArgLead, CmdLine, CursorPos)
826 python3 vim_comp_list()
829 " Python command line calculator
830 command! -nargs=+ -range -complete=customlist,CompList Calc
831 \ <line1>,<line2> python3 vim_calc(<q-args>)
833 " Python text range filter
834 command! -nargs=+ -range -complete=customlist,CompList Pydo
835 \ <line1>,<line2> python3 vim_pydo(<q-args>)
837 " Display unicode name for the character under cursor
838 command! Uname python3 vim_unicode_name()
841 if has("python") || has("python3")
847 function! SetLazyRedraw(timer_id)
848 call timer_stop(a:timer_id) " One-time event
851 call timer_start(500, 'SetLazyRedraw')
854 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
855 set secure " safer working with script files in the current directory