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
77 " set statusline=%<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P " Default statusline
79 set splitbelow " A new window is put below of the current one
80 set splitright " A new window is put right of the current one
84 set ttyfast " terminal connection is fast
86 set title " Set title to the value of 'titlestring' or to 'filename - VIM'
87 set titleold= " string to restore the title to when exiting Vim
88 " String to use for the Vim window title; with statusline printf items.
89 " This is the default:
90 " display filename, modification flag, full path, and program name in uppercase.
91 " set titlestring=%t%(\ %M%)%(\ (%{substitute(expand(\"%:p:h\"),\ $HOME,\ \"~\",\ \"\")})%)%(\ %a%)\ -\ %{toupper(v:progname)}
92 " display filename, modification flag, full path, argument list status,
93 " the current user, host and program name (to distinguish vim/view/etc).
94 set titlestring=%t%(\ %M%)%(\ (%{substitute(expand(\"%:p:h\"),\ $HOME,\ \"~\",\ \"\")})%)%(\ %a%)\ -\ %{v:progname}\ [%{$USER}@%{hostname()}]
99 set mouse=ar " Use mouse in all modes, plus hit-return
102 " 12 messages and info
104 set ruler " Show cursor position below each window
105 set showcmd " Show (partial) command keys in the status line
106 set visualbell " Use visual bell instead of beeping
108 set belloff=error,insertmode " Do not ring the bell for these reasons
111 " Short message for [Modified];
112 " overwrite message for writing a file with subsequent message;
113 " truncate long file messages
118 set backspace=indent,eol,start
119 set complete+=k " Scan spell dictionaries for completion in addition to standard places
120 set infercase " adjust case of a keyword completion match
121 set nojoinspaces " Do not insert two spaces after a '.', '?' and '!' with a join command
122 set nrformats=hex " I seldom edit octal numbers, but very often dates like 2001-02-01
124 " Default value 'croql' is a compromise for both natural and programming
125 " languages, but as any compromise it works good for neither natural nor
126 " programming languages. This value is good for natural texts,
127 " let ftplugins to set values suitable for programming languages.
128 set formatoptions=2t " list of flags that tell how automatic formatting works
130 " 15 tabs and indenting
132 set expandtab " expand <Tab> to spaces in Insert mode
133 set shiftwidth=3 " number of spaces used for each step of (auto)indent
134 set smarttab " a <Tab> in an indent inserts 'shiftwidth' spaces
135 set softtabstop=3 " number of spaces to insert for a <Tab>
137 set noautoindent " Do not automatically set the indent of a new line
141 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
143 " 19 reading and writing files
145 set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
150 let myUndoDir = expand('~/tmp/vim/undo')
151 if !isdirectory(myUndoDir)
153 call mkdir(myUndoDir, 'p')
156 " list of directories for the swap file; remove . (the current directory)
158 set directory=~/tmp/vim//,$TEMP//,c:/tmp//,c:/temp//
160 set directory=~/tmp/vim//,~/tmp//,/var/tmp//,/tmp//
162 " if a directory ends in two path separators "//"
163 " or "\\", the swap file name will be built from the complete path to
164 " the file with all path separators substituted to percent '%' signs.
165 " This will ensure file name uniqueness in the preserve directory.
167 " 21 command line editing
169 set history=1000 " how many command lines are remembered
170 set suffixes+=.pyc,.pyo " list of file name extensions that have a lower priority
171 set wildignore+=*.py[co] " Ignore these patterns when completing file names
172 set wildmenu " command-line completion shows a list of matches
173 set wildmode=longest,list:longest,full " Bash-vim completion behavior
175 " Keep undo history across sessions by storing it in a file
176 if has('persistent_undo')
177 let &undodir = myUndoDir
181 " 22 executing external commands
184 set noshelltemp " Use pipes on Unix
187 " 25 multi-byte characters
189 " Automatically detected character encodings
190 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
194 " ! - when included, save and restore global variables that start
195 " with an uppercase letter, and don't contain a lowercase letter;
196 " h - disable the effect of 'hlsearch';
197 " ' - number of files for which the marks are remembered;
198 " " and < - maximum number of lines saved for a register;
199 " s - maximum size of an item in Kbytes.
204 set viminfo+=<1000,s10
207 " c - convert viminfo to the current encoding;
212 " Removable media paths
219 if has("gui_running")
223 "set guifont=Courier_New:h18:cRUSSIAN
224 set guifont=Lucida_Console:h18:cRUSSIAN
226 set guifont=Monospace\ 18
227 set toolbar=icons,text " how to show the toolbar
230 set guicursor+=n:block " Block cursor in normal mode
231 set guicursor+=i:ver10 " Solid vertical bar in insert mode
232 set guicursor+=a:blinkon0 " Stop cursor blinking
234 " Make shift-insert work like in Xterm
235 " map <S-Insert> <MiddleMouse>
236 " map! <S-Insert> <MiddleMouse>
239 " From http://slobin.pp.ru/vim/_vimrc.html
241 " Arrows should go into wrapped lines, but not while popup menu is visible
242 imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
243 imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
245 " The <CR> key should select from completion menu without adding a newline
246 imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
250 if (&term =~ "linux") || (&term =~ "cygwin") || (&term =~ "putty")
251 \ || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
253 " Background of the terminal is black or dark grey
259 if (&term =~ "linux")
260 execute 'set t_kb=' . nr2char(127)
263 if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
264 execute 'set t_kb=' . nr2char(127)
289 map! <Esc>Ow <Esc>[7~
292 map! <Esc>Oq <Esc>[8~
293 " KP_Prev (PgDn) and KP_Next (PgUp) work fine, no mapping is required
295 " 'autoselect' to always put selected text on the clipboard;
296 " 'unnamed' to use the * register like unnamed register '*'
297 " for all yank, delete and put operations;
298 " This allows to use mouse for copy/paste in local xterm,
299 " but prevents to save the unnamed register between sessions.
300 " set clipboard=autoselect,unnamed,exclude:cons\|linux
302 " Use xclip to copy/paste to/from X clipboard at remote host
303 " vmap "+y :!xclip -i -sel clip
304 " map "+p :r!xclip -o -sel clip
305 " Enable X11Forwarding and use ssh -X or even -Y
308 if (&term =~ "screen")
309 set ttymouse=xterm2 " Enable mouse codes under screen/tmux
311 " Enable window title under screen/tmux
317 " https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
318 " https://ttssh2.osdn.jp/manual/en/usage/tips/vim.html
319 function! WrapForScreenTmux(s)
320 if (&term =~ "screen")
321 let scr_start = "\<Esc>P"
322 let scr_end = "\<Esc>\\"
324 return scr_start . a:s . scr_end
328 let tmux_start = "\<Esc>Ptmux;"
329 let tmux_end = "\<Esc>\\"
331 return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
337 " https://vim.fandom.com/wiki/Change_cursor_shape_in_different_modes
338 let &t_EI.=WrapForScreenTmux("\e[2 q") "EI = NORMAL mode (ELSE)
339 let &t_SI.=WrapForScreenTmux("\e[6 q") "SI = INSERT mode
341 let &t_SR.=WrapForScreenTmux("\e[4 q") "SR = REPLACE mode
345 " 1 -> blinking block
347 " 3 -> blinking underscore
348 " 4 -> solid underscore
349 " 5 -> blinking vertical bar
350 " 6 -> solid vertical bar
353 " Multiline comments often confuse vim syntax highlighting - these maps
354 " allow to resynchronize; the first is faster, the second is more thorough
355 nmap \sc :syntax sync clear<Enter>
356 nmap \ss :syntax sync fromstart<Enter>
361 " Enable filetype detection
362 filetype plugin indent on
364 runtime macros/matchit.vim
366 " Reread me after editing
367 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
370 " Save all files before running any quickfix command (grep, makeprg, etc.)
371 autocmd QuickFixCmdPre * wall
372 " automatically close quickfix if it's the only window left
373 autocmd WinEnter * if winnr('$') == 1 &&
374 \ index(["nofile", "quickfix"], &buftype) >= 0 | quit | endif
377 " Syntax highlighting
378 autocmd BufReadPost * syntax on
381 " Restore last known cursor position
382 function! RestorePosition()
383 if exists('b:position_restored')
388 call cursor(line("'\""), col("'\""))
390 let b:position_restored = 1
393 " When editing a file, always jump to the last cursor position (if saved)
394 autocmd BufReadPost * call RestorePosition()
397 function! SetupEncoding(encoding)
398 if !has("iconv") || exists('b:encoding_set') || empty(a:encoding)
402 call RestorePosition()
403 let b:encoding_set = 1
404 if !empty(expand('%'))
405 execute "edit ++enc=" . a:encoding
410 " From http://lwn.net/Articles/226514/
413 " Remove ALL autocommands for the current group.
415 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
416 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
417 autocmd BufReadPost *.gpg :%!gpg -q -d
418 autocmd BufReadPost *.gpg | redraw
419 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
420 autocmd BufWritePost *.gpg u
421 autocmd VimLeave *.gpg :!clear
423 " BufReadPost: use "openssl bf -d -a"
424 " BufWritePre: use "openssl bf -salt -a"
437 function! SetNoWrap()
444 command! SetWrap call SetWrap()
445 command! SetNoWrap call SetNoWrap()
447 " b:wrap can be set by an ftplugin
448 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
453 " Do not unindent #-comment
458 " map <C-Z> :shell<CR>
464 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"
466 function! ExtractURL()
467 let line = getline('.')
468 let parts = split(line, s:URL_re . '\zs')
471 throw 'ExtractURLCannotFindURL' " No URL found
475 let column = col('.')
478 let save_length = length
485 let pos = match(p, s:URL_re)
487 throw 'ExtractURLCannotFindURL' " No URL found
490 if save_length + pos >= column " cursor left of the URL
491 throw 'ExtractURLCannotFindURL'
494 return strpart(p, pos)
497 function! EscapeURL(url)
498 let url = substitute(a:url, ' ', '%20', 'g')
499 return escape(url, '!#$%')
502 function! OpenURL(url, newwin)
503 execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
506 function! ExtractOpenURL(newwin)
508 let url = ExtractURL()
509 catch /^ExtractURLCannotFindURL$/
510 echoerr 'No URL found under cursor'
514 call OpenURL(url, a:newwin)
517 function! EncodeOpenURL(url, newwin)
518 execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
522 " Send current link to a browser
523 nmap \b :call ExtractOpenURL('')<CR>
524 nmap \w :call ExtractOpenURL('-n')<CR>
525 nmap \t :call ExtractOpenURL('-t')<CR>
526 " Send visual block to a browser
527 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
528 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
529 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
530 " Encode and send visual block to a browser
531 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
532 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
533 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
534 " Send current file's name to a browser
535 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
536 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
537 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
539 endif " version >= 700
544 if has("spell") " Works in 7.0+
545 " Use builtin spellchecker
546 nmap \sv :syntax off <BAR> setlocal spell<CR>
548 nmap \sn :syntax on <BAR> setlocal nospell<CR>
552 " Russian letters mapped in normal mode
554 " set keymap=russian-jcuken
559 " langmap in utf-8 mode requires at least Vim 7.2.109
561 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
562 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
563 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
565 elseif &encoding != 'utf-8'
566 scriptencoding koi8-r
567 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
568 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
569 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
572 scriptencoding us-ascii
578 " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
579 let encodings = ['us-ascii']
580 if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
581 let encodings += ['utf-8']
582 elseif $LC_CTYPE == 'ru_RU.KOI8-R'
583 let encodings += ['koi8-r', 'utf-8']
584 elseif v:lc_time == 'Russian_Russia.1251'
585 let encodings += ['cp1251', 'utf-8']
590 execute 'set fileencoding=' . e
593 catch /E513: write error, conversion failed/
599 throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
614 set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
620 set wildmode=list:longest
621 set viminfo=!,h,'10,<100,s5
626 highlight NonText cterm=NONE ctermfg=NONE
629 if exists("$SLOWTERM")
635 pyfile ~/.vim/python/virtualenv.py
639 py3file ~/.vim/python/virtualenv.py
644 " http://vim.fandom.com/wiki/Setting_file_attributes_without_reloading_a_buffer
646 if executable('chmod')
647 function! SetExecutableBit(x)
649 " Avoid 'Reload Y/N?' question
650 autocmd FileChangedShell <buffer> call _BufChangedCB()
651 let fx = executable(expand("%:p"))
658 echoerr 'Error running chmod: ' . v:shell_error
661 autocmd! FileChangedShell <buffer>
663 function! _BufChangedCB()
664 autocmd! FileChangedShell <buffer>
666 command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
670 setlocal expandtab tabstop=8 softtabstop=4 shiftwidth=4
672 command! Code call Code()
675 setlocal expandtab tabstop=8 softtabstop=3 shiftwidth=3
677 command! Text call Text()
680 " From http://slobin.pp.ru/vim/_vimrc.html
682 " These options will be kept between editing sessions
685 " Called automagically after .viminfo and plugins are loaded, sets
686 " miscellaneous options from persistent global variables
687 " function! VimEnter()
688 " for optname in g:options
689 " let varname = "g:OPT_" . toupper(optname)
691 " execute "let &" . optname . " = " . varname
695 " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
696 " execute "winpos" g:WINPOSX g:WINPOSY
700 " Called automagically before .viminfo is saved, saves miscellaneous
701 " options into persistent global variables
702 " function! VimLeavePre()
703 " call filter(g:, 'v:key !~# "^OPT_"')
704 " for optname in g:options
705 " let varname = "g:OPT_" . toupper(optname)
706 " execute "let " . varname . " = &g:" . optname
709 " if has("gui_running")
710 " let g:WINPOSX = getwinposx()
711 " let g:WINPOSY = getwinposy()
715 " autocmd VimEnter * call VimEnter()
716 " autocmd VimLeavePre * call VimLeavePre()
719 " Called automagically after every buffer read, enables fileencoding
720 " setting from modeline (see Tip #911:
721 " http://vim.fandom.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
722 function! AutoEncoding()
723 if &modified && &fileencoding != ""
724 call SetupEncoding(&fileencoding)
726 autocmd! auto-encoding
727 augroup! auto-encoding
730 augroup auto-encoding
732 autocmd BufWinEnter * call AutoEncoding()
738 " Value of a character under cursor; better than standard '0x%02B (%b)'
740 let char = matchstr(getline("."), ".", col(".") - 1)
742 let char = iconv(char, &encoding, &fileencoding)
743 let format = "0x%02X <%d>"
745 let format = "0x%02X (%d)"
747 let char = char2nr(char)
748 return printf(format, char, char)
753 " Helper function for :DecodeQP and :DecodeURL commands
754 function! DecodeHex(arg)
755 return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
758 " Custom completion for encoding names
759 function! EncList(ArgLead, CmdLine, CursorPos)
760 return filter(split(&fileencodings, ','),
761 \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
765 " Command for decoding qp-encoded text
766 command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
767 \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
769 " Command for decoding url-encoded text
770 command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
771 \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
777 function! SetupSpell()
778 if &fileencoding =~ 'ascii'
779 setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
780 elseif &fileencoding == 'koi8-r'
781 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
782 elseif &fileencoding == 'utf-8'
783 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
785 setlocal spelllang= spellfile=
788 autocmd BufReadPost * call SetupSpell()
790 function! SaveSpell()
791 if expand('%:p') == expand('~/.vim/spell/en.ascii.add')
797 autocmd BufWritePost ~/.vim/spell/*.add call SaveSpell()
801 function! SyntaxName()
802 echomsg synIDattr(synID(line("."), col("."), 1), "name")
807 pyfile ~/.vim/python/completion.py
809 " Custom completion for python expressions
810 function! CompList(ArgLead, CmdLine, CursorPos)
811 python vim_comp_list()
814 " Python command line calculator
815 command! -nargs=+ -range -complete=customlist,CompList Calc
816 \ <line1>,<line2> python vim_calc(<q-args>)
818 " Python text range filter
819 command! -nargs=+ -range -complete=customlist,CompList Pydo
820 \ <line1>,<line2> python vim_pydo(<q-args>)
822 " Display unicode name for the character under cursor
823 command! Uname python vim_unicode_name()
827 py3file ~/.vim/python/completion.py
829 " Custom completion for python expressions
830 function! CompList(ArgLead, CmdLine, CursorPos)
831 python3 vim_comp_list()
834 " Python command line calculator
835 command! -nargs=+ -range -complete=customlist,CompList Calc
836 \ <line1>,<line2> python3 vim_calc(<q-args>)
838 " Python text range filter
839 command! -nargs=+ -range -complete=customlist,CompList Pydo
840 \ <line1>,<line2> python3 vim_pydo(<q-args>)
842 " Display unicode name for the character under cursor
843 command! Uname python3 vim_unicode_name()
846 if has("python") || has("python3")
852 function! SetLazyRedraw(timer_id)
853 call timer_stop(a:timer_id) " One-time event
856 call timer_start(500, 'SetLazyRedraw')
859 autocmd VimLeave * call writefile([getcwd()], expand('~/tmp/vim/cwd'))
861 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
862 set secure " safer working with script files in the current directory