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
103 " Short message for [Modified];
104 " overwrite message for writing a file with subsequent message;
105 " truncate long file messages
110 set backspace=indent,eol,start
111 set complete+=k " Scan spell dictionaries for completion in addition to standard places
112 set infercase " adjust case of a keyword completion match
113 set nojoinspaces " Do not insert two spaces after a '.', '?' and '!' with a join command
114 set nrformats=hex " I seldom edit octal numbers, but very often dates like 2001-02-01
116 " Default value 'croql' is a compromise for both natural and programming
117 " languages, but as any compromise it works good for neither natural nor
118 " programming languages. This value is good for natural texts,
119 " let ftplugins to set values suitable for programming languages.
120 set formatoptions=2t " list of flags that tell how automatic formatting works
122 " 15 tabs and indenting
124 set expandtab " expand <Tab> to spaces in Insert mode
125 set shiftwidth=3 " number of spaces used for each step of (auto)indent
126 set smarttab " a <Tab> in an indent inserts 'shiftwidth' spaces
127 set softtabstop=3 " number of spaces to insert for a <Tab>
129 set noautoindent " Do not automatically set the indent of a new line
133 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
135 " 19 reading and writing files
137 set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
142 let myUndoDir = expand('~/tmp/vim/undo')
143 if !isdirectory(myUndoDir)
145 call mkdir(myUndoDir, 'p')
148 " list of directories for the swap file; remove . (the current directory)
150 set directory=~/tmp/vim//,$TEMP//,c:/tmp//,c:/temp//
152 set directory=~/tmp/vim//,~/tmp//,/var/tmp//,/tmp//
154 " if a directory ends in two path separators "//"
155 " or "\\", the swap file name will be built from the complete path to
156 " the file with all path separators substituted to percent '%' signs.
157 " This will ensure file name uniqueness in the preserve directory.
159 " 21 command line editing
161 set history=1000 " how many command lines are remembered
162 set suffixes+=.pyc,.pyo " list of file name extensions that have a lower priority
163 set wildignore+=*.py[co] " Ignore these patterns when completing file names
164 set wildmenu " command-line completion shows a list of matches
165 set wildmode=longest,list:longest,full " Bash-vim completion behavior
167 " Keep undo history across sessions by storing it in a file
168 if has('persistent_undo')
169 let &undodir = myUndoDir
173 " 22 executing external commands
176 set noshelltemp " Use pipes on Unix
179 " 25 multi-byte characters
181 " Automatically detected character encodings
182 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
186 " ! - when included, save and restore global variables that start
187 " with an uppercase letter, and don't contain a lowercase letter;
188 " h - disable the effect of 'hlsearch';
189 " ' - number of files for which the marks are remembered;
190 " " and < - maximum number of lines saved for a register;
191 " s - maximum size of an item in Kbytes.
196 set viminfo+=<1000,s10
199 " c - convert viminfo to the current encoding;
204 " Removable media paths
211 if has("gui_running")
215 "set guifont=Courier_New:h18:cRUSSIAN
216 set guifont=Lucida_Console:h18:cRUSSIAN
218 set guifont=Monospace\ 16
219 set toolbar=icons,text " how to show the toolbar
222 set guicursor+=n:block " Block cursor in normal mode
223 set guicursor+=i:ver10 " Solid vertical bar in insert mode
224 set guicursor+=a:blinkon0 " Stop cursor blinking
226 " Make shift-insert work like in Xterm
227 " map <S-Insert> <MiddleMouse>
228 " map! <S-Insert> <MiddleMouse>
231 " From http://slobin.pp.ru/vim/_vimrc.html
233 " Arrows should go into wrapped lines, but not while popup menu is visible
234 imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
235 imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
237 " The <CR> key should select from completion menu without adding a newline
238 imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
242 if (&term =~ "linux") || (&term =~ "cygwin") || (&term =~ "putty")
243 \ || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
245 " Background of the terminal is black or dark grey
251 if (&term =~ "linux")
252 execute 'set t_kb=' . nr2char(127)
255 if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
256 execute 'set t_kb=' . nr2char(127)
267 " 'autoselect' to always put selected text on the clipboard;
268 " 'unnamed' to use the * register like unnamed register '*'
269 " for all yank, delete and put operations;
270 " This allows to use mouse for copy/paste in local xterm,
271 " but prevents to save the unnamed register between sessions.
272 " set clipboard=autoselect,unnamed,exclude:cons\|linux
274 " Use xclip to copy/paste to/from X clipboard at remote host
275 " vmap "+y :!xclip -i -sel clip
276 " map "+p :r!xclip -o -sel clip
277 " Enable X11Forwarding and use ssh -X or even -Y
280 if (&term =~ "screen")
281 set ttymouse=xterm2 " Enable mouse codes under screen/tmux
283 " Enable window title under screen/tmux
289 " Bracketed paste mode
290 " https://github.com/ConradIrwin/vim-bracketed-paste/blob/master/plugin/bracketed-paste.vim
291 let &t_ti .= "\<Esc>[?2004h"
292 let &t_te = "\e[?2004l" . &t_te
294 function! XTermPasteBegin(ret)
295 set pastetoggle=<f29>
300 execute "set <f28>=\<Esc>[200~"
301 execute "set <f29>=\<Esc>[201~"
302 map <expr> <f28> XTermPasteBegin("i")
303 imap <expr> <f28> XTermPasteBegin("")
304 vmap <expr> <f28> XTermPasteBegin("c")
308 "https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
309 " https://ttssh2.osdn.jp/manual/en/usage/tips/vim.html
310 function! WrapForScreenTmux(s)
311 if (&term =~ "screen")
312 let scr_start = "\<Esc>P"
313 let scr_end = "\<Esc>\\"
315 return scr_start . a:s . scr_end
319 let tmux_start = "\<Esc>Ptmux;"
320 let tmux_end = "\<Esc>\\"
322 return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
328 " https://vim.fandom.com/wiki/Change_cursor_shape_in_different_modes
329 let &t_EI.=WrapForScreenTmux("\e[2 q") "EI = NORMAL mode (ELSE)
330 let &t_SI.=WrapForScreenTmux("\e[6 q") "SI = INSERT mode
332 let &t_SR.=WrapForScreenTmux("\e[4 q") "SR = REPLACE mode
336 " 1 -> blinking block
338 " 3 -> blinking underscore
339 " 4 -> solid underscore
340 " 5 -> blinking vertical bar
341 " 6 -> solid vertical bar
344 " Multiline comments often confuse vim syntax highlighting - these maps
345 " allow to resynchronize; the first is faster, the second is more thorough
346 nmap \sc :syntax sync clear<Enter>
347 nmap \ss :syntax sync fromstart<Enter>
352 " Enable filetype detection
353 filetype plugin indent on
355 runtime macros/matchit.vim
357 " Reread me after editing
358 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
361 " Save all files before running any quickfix command (grep, makeprg, etc.)
362 autocmd QuickFixCmdPre * wall
363 " automatically close quickfix if it's the only window left
364 autocmd WinEnter * if winnr('$') == 1 &&
365 \ index(["nofile", "quickfix"], &buftype) >= 0 | quit | endif
368 " Syntax highlighting
369 autocmd BufReadPost * syntax on
372 " Restore last known cursor position
373 function! RestorePosition()
374 if exists('b:position_restored')
379 call cursor(line("'\""), col("'\""))
381 let b:position_restored = 1
384 " When editing a file, always jump to the last cursor position (if saved)
385 autocmd BufReadPost * call RestorePosition()
388 function! SetupEncoding(encoding)
389 if !has("iconv") || exists('b:encoding_set') || empty(a:encoding)
393 call RestorePosition()
394 let b:encoding_set = 1
395 if !empty(expand('%'))
396 execute "edit ++enc=" . a:encoding
401 " From http://lwn.net/Articles/226514/
404 " Remove ALL autocommands for the current group.
406 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
407 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
408 autocmd BufReadPost *.gpg :%!gpg -q -d
409 autocmd BufReadPost *.gpg | redraw
410 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
411 autocmd BufWritePost *.gpg u
412 autocmd VimLeave *.gpg :!clear
414 " BufReadPost: use "openssl bf -d -a"
415 " BufWritePre: use "openssl bf -salt -a"
428 function! SetNoWrap()
435 command! SetWrap call SetWrap()
436 command! SetNoWrap call SetNoWrap()
438 " b:wrap can be set by an ftplugin
439 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
444 " Do not unindent #-comment
449 " map <C-Z> :shell<CR>
455 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"
457 function! ExtractURL()
458 let line = getline('.')
459 let parts = split(line, s:URL_re . '\zs')
462 throw 'ExtractURLCannotFindURL' " No URL found
466 let column = col('.')
469 let save_length = length
476 let pos = match(p, s:URL_re)
478 throw 'ExtractURLCannotFindURL' " No URL found
481 if save_length + pos >= column " cursor left of the URL
482 throw 'ExtractURLCannotFindURL'
485 return strpart(p, pos)
488 function! EscapeURL(url)
489 let url = substitute(a:url, ' ', '%20', 'g')
490 return escape(url, '!#$%')
493 function! OpenURL(url, newwin)
494 execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
497 function! ExtractOpenURL(newwin)
499 let url = ExtractURL()
500 catch /^ExtractURLCannotFindURL$/
501 echoerr 'No URL found under cursor'
505 call OpenURL(url, a:newwin)
508 function! EncodeOpenURL(url, newwin)
509 execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
513 " Send current link to a browser
514 nmap \b :call ExtractOpenURL('')<CR>
515 nmap \w :call ExtractOpenURL('-n')<CR>
516 nmap \t :call ExtractOpenURL('-t')<CR>
517 " Send visual block to a browser
518 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
519 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
520 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
521 " Encode and send visual block to a browser
522 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
523 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
524 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
525 " Send current file's name to a browser
526 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
527 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
528 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
530 endif " version >= 700
535 if has("spell") " Works in 7.0+
536 " Use builtin spellchecker
537 nmap \sv :syntax off <BAR> setlocal spell<CR>
539 nmap \sn :syntax on <BAR> setlocal nospell<CR>
543 " Russian letters mapped in normal mode
545 " set keymap=russian-jcuken
550 " langmap in utf-8 mode requires at least Vim 7.2.109
552 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
553 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
554 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
556 elseif &encoding != 'utf-8'
557 scriptencoding koi8-r
558 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
559 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
560 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
563 scriptencoding us-ascii
569 " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
570 let encodings = ['us-ascii']
571 if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
572 let encodings += ['utf-8']
573 elseif $LC_CTYPE == 'ru_RU.KOI8-R'
574 let encodings += ['koi8-r', 'utf-8']
575 elseif v:lc_time == 'Russian_Russia.1251'
576 let encodings += ['cp1251', 'utf-8']
581 execute 'set fileencoding=' . e
584 catch /E513: write error, conversion failed/
590 throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
605 set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
611 set wildmode=list:longest
612 set viminfo=!,h,'10,<100,s5
617 highlight NonText cterm=NONE ctermfg=NONE
620 if exists("$SLOWTERM")
626 pyfile ~/.vim/python/virtualenv.py
630 py3file ~/.vim/python/virtualenv.py
635 " http://vim.fandom.com/wiki/Setting_file_attributes_without_reloading_a_buffer
637 if executable('chmod')
638 function! SetExecutableBit(x)
640 " Avoid 'Reload Y/N?' question
641 autocmd FileChangedShell <buffer> call _BufChangedCB()
642 let fx = executable(expand("%:p"))
649 echoerr 'Error running chmod: ' . v:shell_error
652 autocmd! FileChangedShell <buffer>
654 function! _BufChangedCB()
655 autocmd! FileChangedShell <buffer>
657 command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
661 setlocal expandtab tabstop=8 softtabstop=4 shiftwidth=4
663 command! Code call Code()
666 setlocal expandtab tabstop=8 softtabstop=3 shiftwidth=3
668 command! Text call Text()
671 " From http://slobin.pp.ru/vim/_vimrc.html
673 " These options will be kept between editing sessions
676 " Called automagically after .viminfo and plugins are loaded, sets
677 " miscellaneous options from persistent global variables
678 " function! VimEnter()
679 " for optname in g:options
680 " let varname = "g:OPT_" . toupper(optname)
682 " execute "let &" . optname . " = " . varname
686 " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
687 " execute "winpos" g:WINPOSX g:WINPOSY
691 " Called automagically before .viminfo is saved, saves miscellaneous
692 " options into persistent global variables
693 " function! VimLeavePre()
694 " call filter(g:, 'v:key !~# "^OPT_"')
695 " for optname in g:options
696 " let varname = "g:OPT_" . toupper(optname)
697 " execute "let " . varname . " = &g:" . optname
700 " if has("gui_running")
701 " let g:WINPOSX = getwinposx()
702 " let g:WINPOSY = getwinposy()
706 " autocmd VimEnter * call VimEnter()
707 " autocmd VimLeavePre * call VimLeavePre()
710 " Called automagically after every buffer read, enables fileencoding
711 " setting from modeline (see Tip #911:
712 " http://vim.fandom.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
713 function! AutoEncoding()
714 if &modified && &fileencoding != ""
715 call SetupEncoding(&fileencoding)
717 autocmd! auto-encoding
718 augroup! auto-encoding
721 augroup auto-encoding
723 autocmd BufWinEnter * call AutoEncoding()
729 " Value of a character under cursor; better than standard '0x%02B (%b)'
731 let char = matchstr(getline("."), ".", col(".") - 1)
733 let char = iconv(char, &encoding, &fileencoding)
734 let format = "0x%02X <%d>"
736 let format = "0x%02X (%d)"
738 let char = char2nr(char)
739 return printf(format, char, char)
744 " Helper function for :DecodeQP and :DecodeURL commands
745 function! DecodeHex(arg)
746 return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
749 " Custom completion for encoding names
750 function! EncList(ArgLead, CmdLine, CursorPos)
751 return filter(split(&fileencodings, ','),
752 \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
756 " Command for decoding qp-encoded text
757 command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
758 \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
760 " Command for decoding url-encoded text
761 command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
762 \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
768 function! SetupSpell()
769 if &fileencoding =~ 'ascii'
770 setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
771 elseif &fileencoding == 'koi8-r'
772 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
773 elseif &fileencoding == 'utf-8'
774 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
776 setlocal spelllang= spellfile=
779 autocmd BufReadPost * call SetupSpell()
781 function! SaveSpell()
782 if expand('%:p') == expand('~/.vim/spell/en.ascii.add')
788 autocmd BufWritePost ~/.vim/spell/*.add call SaveSpell()
792 function! SyntaxName()
793 echomsg synIDattr(synID(line("."), col("."), 1), "name")
798 pyfile ~/.vim/python/completion.py
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()
818 py3file ~/.vim/python/completion.py
820 " Custom completion for python expressions
821 function! CompList(ArgLead, CmdLine, CursorPos)
822 python3 vim_comp_list()
825 " Python command line calculator
826 command! -nargs=+ -range -complete=customlist,CompList Calc
827 \ <line1>,<line2> python3 vim_calc(<q-args>)
829 " Python text range filter
830 command! -nargs=+ -range -complete=customlist,CompList Pydo
831 \ <line1>,<line2> python3 vim_pydo(<q-args>)
833 " Display unicode name for the character under cursor
834 command! Uname python3 vim_unicode_name()
837 if has("python") || has("python3")
843 function! SetLazyRedraw(timer_id)
844 call timer_stop(a:timer_id) " One-time event
847 call timer_start(500, 'SetLazyRedraw')
850 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
851 set secure " safer working with script files in the current directory