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>
50 set lazyredraw " Do not update screen while executing macros
51 set list " listchars only works with 'list'
52 " Show tabs, non-breaking/trailing spaces, long lines
53 set listchars=tab:>_,nbsp:_,trail:_,extends:+,precedes:+
54 " Another usefull additions: eol:$,space:_
55 set scrolloff=0 " number of screen lines to show around the cursor
56 set wrap " Visually wrap long lines
58 " With 'set wrap' wrap long lines at a character in 'breakat'
59 " Please note 'nolist' is required to use 'linebreak'
60 set linebreak showbreak=+\ " A plus and a space
62 set sidescroll=1 " The minimal number of columns to scroll horizontally
67 set nohlsearch " Stop the search highlighting
71 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
72 set laststatus=2 " Always show status line
74 set splitbelow " A new window is put below of the current one
75 set splitright " A new window is put right of the current one
79 set ttyfast " terminal connection is fast
81 set title " Set title to the value of 'titlestring' or to 'filename - VIM'
82 set titleold= " string to restore the title to when exiting Vim
83 " String to use for the Vim window title; with statusline printf items:
84 " display filename, modification flag, full path, argument list status,
85 " the current user, host and program name (to distinguish vim/view/etc).
86 set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:p:h\")})%)%(\ %a%)\ -\ [%{$USER}@%{hostname()}]\ %{v:progname}
91 set mouse=ar " Use mouse in all modes, plus hit-return
94 " 12 messages and info
96 set ruler " Show cursor position below each window
97 set showcmd " Show (partial) command keys in the status line
99 " Short message for [Modified];
100 " overwrite message for writing a file with subsequent message;
101 " truncate long file messages
106 set backspace=indent,eol,start
107 set complete+=k " Scan spell dictionaries for completion in addition to standard places
108 set infercase " adjust case of a keyword completion match
109 set nojoinspaces " Do not insert two spaces after a '.', '?' and '!' with a join command
110 set nrformats=hex " I seldom edit octal numbers, but very often dates like 2001-02-01
112 " Default value 'croql' is a compromise for both natural and programming
113 " languages, but as any compromise it works good for neither natural nor
114 " programming languages. This value is good for natural texts,
115 " let ftplugins to set values suitable for programming languages.
116 set formatoptions=2t " list of flags that tell how automatic formatting works
118 " 15 tabs and indenting
120 set expandtab " expand <Tab> to spaces in Insert mode
121 set shiftwidth=3 " number of spaces used for each step of (auto)indent
122 set smarttab " a <Tab> in an indent inserts 'shiftwidth' spaces
123 set softtabstop=3 " number of spaces to insert for a <Tab>
125 set noautoindent " Do not automatically set the indent of a new line
129 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
131 " 19 reading and writing files
133 set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
138 let myUndoDir = expand('~/tmp/vim/undo')
139 if !isdirectory(myUndoDir)
141 call mkdir(myUndoDir, 'p')
144 " list of directories for the swap file; remove . (the current directory)
146 set directory=~/tmp/vim//,$TEMP//,c:/tmp//,c:/temp//
148 set directory=~/tmp/vim//,~/tmp//,/var/tmp//,/tmp//
150 " if a directory ends in two path separators "//"
151 " or "\\", the swap file name will be built from the complete path to
152 " the file with all path separators substituted to percent '%' signs.
153 " This will ensure file name uniqueness in the preserve directory.
155 " 21 command line editing
157 set history=1000 " how many command lines are remembered
158 set suffixes+=.pyc,.pyo " list of file name extensions that have a lower priority
159 set wildignore+=*.py[co] " Ignore these patterns when completing file names
160 set wildmenu " command-line completion shows a list of matches
161 set wildmode=longest,list:longest,full " Bash-vim completion behavior
163 " Keep undo history across sessions by storing it in a file
164 if has('persistent_undo')
165 let &undodir = myUndoDir
169 " 22 executing external commands
172 set noshelltemp " Use pipes on Unix
175 " 25 multi-byte characters
177 " Automatically detected character encodings
178 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
182 " ! - when included, save and restore global variables that start
183 " with an uppercase letter, and don't contain a lowercase letter;
184 " h - disable the effect of 'hlsearch';
185 " ' - number of files for which the marks are remembered;
186 " " and < - maximum number of lines saved for a register;
187 " s - maximum size of an item in Kbytes.
192 set viminfo+=<1000,s10
195 " c - convert viminfo to the current encoding;
200 " Removable media paths
207 if has("gui_running")
211 "set guifont=Courier_New:h18:cRUSSIAN
212 set guifont=Lucida_Console:h18:cRUSSIAN
214 set guifont=Monospace\ 16
215 set toolbar=icons,text " how to show the toolbar
218 set guicursor+=a:blinkon0 " Stop cursor blinking
220 " Make shift-insert work like in Xterm
221 " map <S-Insert> <MiddleMouse>
222 " map! <S-Insert> <MiddleMouse>
225 " From http://slobin.pp.ru/vim/_vimrc.html
227 " Arrows should go into wrapped lines, but not while popup menu is visible
228 imap <expr> <Down> pumvisible() ? "<Down>" : "<C-O>gj"
229 imap <expr> <Up> pumvisible() ? "<Up>" : "<C-O>gk"
231 " The <CR> key should select from completion menu without adding a newline
232 imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
236 if (&term =~ "linux") || (&term =~ "cygwin") || (&term =~ "putty")
237 \ || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
239 " Background of the terminal is black or dark grey
245 if (&term =~ "linux")
246 execute 'set t_kb=' . nr2char(127)
249 if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
250 execute 'set t_kb=' . nr2char(127)
261 " 'autoselect' to always put selected text on the clipboard;
262 " 'unnamed' to use the * register like unnamed register '*'
263 " for all yank, delete and put operations;
264 " This allows to use mouse for copy/paste in local xterm,
265 " but prevents to save the unnamed register between sessions.
266 " set clipboard=autoselect,unnamed,exclude:cons\|linux
268 " Use xclip to copy/paste to/from X clipboard at remote host
269 " vmap "+y :!xclip -i -sel clip
270 " map "+p :r!xclip -o -sel clip
271 " Enable X11Forwarding and use ssh -X or even -Y
274 if (&term =~ "screen")
275 set ttymouse=xterm2 " Enable mouse codes under screen/tmux
277 " Enable window title under screen/tmux
283 " Bracketed paste mode
284 " https://github.com/ConradIrwin/vim-bracketed-paste/blob/master/plugin/bracketed-paste.vim
285 let &t_ti .= "\<Esc>[?2004h"
286 let &t_te = "\e[?2004l" . &t_te
288 function! XTermPasteBegin(ret)
289 set pastetoggle=<f29>
294 execute "set <f28>=\<Esc>[200~"
295 execute "set <f29>=\<Esc>[201~"
296 map <expr> <f28> XTermPasteBegin("i")
297 imap <expr> <f28> XTermPasteBegin("")
298 vmap <expr> <f28> XTermPasteBegin("c")
302 "https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
303 " https://ttssh2.osdn.jp/manual/en/usage/tips/vim.html
304 function! WrapForScreenTmux(s)
305 if (&term =~ "screen")
306 let scr_start = "\<Esc>P"
307 let scr_end = "\<Esc>\\"
309 return scr_start . a:s . scr_end
313 let tmux_start = "\<Esc>Ptmux;"
314 let tmux_end = "\<Esc>\\"
316 return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
322 " https://vim.fandom.com/wiki/Change_cursor_shape_in_different_modes
323 let &t_EI.=WrapForScreenTmux("\e[2 q") "EI = NORMAL mode (ELSE)
324 let &t_SI.=WrapForScreenTmux("\e[6 q") "SI = INSERT mode
326 let &t_SR.=WrapForScreenTmux("\e[4 q") "SR = REPLACE mode
330 " 1 -> blinking block
332 " 3 -> blinking underscore
333 " 4 -> solid underscore
334 " 5 -> blinking vertical bar
335 " 6 -> solid vertical bar
338 " Multiline comments often confuse vim syntax highlighting - these maps
339 " allow to resynchronize; the first is faster, the second is more thorough
340 nmap \sc :syntax sync clear<Enter>
341 nmap \ss :syntax sync fromstart<Enter>
346 " Enable filetype detection
347 filetype plugin indent on
349 runtime macros/matchit.vim
351 " Reread me after editing
352 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
355 " Save all files before running any quickfix command (grep, makeprg, etc.)
356 autocmd QuickFixCmdPre * wall
357 " automatically close quickfix if it's the only window left
358 autocmd WinEnter * if winnr('$') == 1 &&
359 \ index(["nofile", "quickfix"], &buftype) >= 0 | quit | endif
362 " Syntax highlighting
363 autocmd BufReadPost * syntax on
366 " Restore last known cursor position
367 function! RestorePosition()
368 if exists('b:position_restored')
373 call cursor(line("'\""), col("'\""))
375 let b:position_restored = 1
378 " When editing a file, always jump to the last cursor position (if saved)
379 autocmd BufReadPost * call RestorePosition()
382 function! SetupEncoding(encoding)
383 if !has("iconv") || exists('b:encoding_set') || strlen(a:encoding) == 0
387 call RestorePosition()
388 let b:encoding_set = 1
390 execute "edit ++enc=" . a:encoding
395 " From http://lwn.net/Articles/226514/
398 " Remove ALL autocommands for the current group.
400 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
401 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
402 autocmd BufReadPost *.gpg :%!gpg -q -d
403 autocmd BufReadPost *.gpg | redraw
404 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
405 autocmd BufWritePost *.gpg u
406 autocmd VimLeave *.gpg :!clear
408 " BufReadPost: use "openssl bf -d -a"
409 " BufWritePre: use "openssl bf -salt -a"
422 function! SetNoWrap()
429 command! SetWrap call SetWrap()
430 command! SetNoWrap call SetNoWrap()
432 " b:wrap can be set by an ftplugin
433 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
438 " Do not unindent #-comment
443 " map <C-Z> :shell<CR>
449 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"
451 function! ExtractURL()
452 let line = getline('.')
453 let parts = split(line, s:URL_re . '\zs')
456 throw 'ExtractURLCannotFindURL' " No URL found
460 let column = col('.')
463 let save_length = length
470 let pos = match(p, s:URL_re)
472 throw 'ExtractURLCannotFindURL' " No URL found
475 if save_length + pos >= column " cursor left of the URL
476 throw 'ExtractURLCannotFindURL'
479 return strpart(p, pos)
482 function! EscapeURL(url)
483 let url = substitute(a:url, ' ', '%20', 'g')
484 return escape(url, '!#$%')
487 function! OpenURL(url, newwin)
488 execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
491 function! ExtractOpenURL(newwin)
493 let url = ExtractURL()
494 catch /^ExtractURLCannotFindURL$/
495 echoerr 'No URL found under cursor'
499 call OpenURL(url, a:newwin)
502 function! EncodeOpenURL(url, newwin)
503 execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
507 " Send current link to a browser
508 nmap \b :call ExtractOpenURL('')<CR>
509 nmap \w :call ExtractOpenURL('-n')<CR>
510 nmap \t :call ExtractOpenURL('-t')<CR>
511 " Send visual block to a browser
512 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
513 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
514 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
515 " Encode and send visual block to a browser
516 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
517 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
518 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
519 " Send current file's name to a browser
520 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
521 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
522 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
524 endif " version >= 700
529 if has("spell") " Works in 7.0+
530 " Use builtin spellchecker
531 nmap \sv :syntax off <BAR> setlocal spell<CR>
533 nmap \sn :syntax on <BAR> setlocal nospell<CR>
537 " Russian letters mapped in normal mode
539 " set keymap=russian-jcuken
544 " langmap in utf-8 mode requires at least Vim 7.2.109
546 set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
547 \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
548 \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
550 elseif &encoding != 'utf-8'
551 scriptencoding koi8-r
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Б<Ю>
557 scriptencoding us-ascii
563 " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
564 let encodings = ['us-ascii']
565 if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
566 let encodings += ['utf-8']
567 elseif $LC_CTYPE == 'ru_RU.KOI8-R'
568 let encodings += ['koi8-r', 'utf-8']
569 elseif v:lc_time == 'Russian_Russia.1251'
570 let encodings += ['cp1251', 'utf-8']
575 execute 'set fileencoding=' . e
578 catch /E513: write error, conversion failed/
584 throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
599 set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
605 set wildmode=list:longest
606 set viminfo=!,h,'10,<100,s5
611 highlight NonText cterm=NONE ctermfg=NONE
614 if exists("$SLOWTERM")
620 pyfile ~/.vim/python/virtualenv.py
624 py3file ~/.vim/python/virtualenv.py
629 " http://vim.fandom.com/wiki/Setting_file_attributes_without_reloading_a_buffer
631 if executable('chmod')
632 function! SetExecutableBit(x)
634 " Avoid 'Reload Y/N?' question
635 autocmd FileChangedShell <buffer> call _BufChangedCB()
636 let fx = executable(expand("%:p"))
643 echoerr 'Error running chmod: ' . v:shell_error
646 autocmd! FileChangedShell <buffer>
648 function! _BufChangedCB()
649 autocmd! FileChangedShell <buffer>
651 command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
655 setlocal expandtab tabstop=8 softtabstop=4 shiftwidth=4
657 command! Code call Code()
660 setlocal expandtab tabstop=8 softtabstop=3 shiftwidth=3
662 command! Text call Text()
665 " From http://slobin.pp.ru/vim/_vimrc.html
667 " These options will be kept between editing sessions
670 " Called automagically after .viminfo and plugins are loaded, sets
671 " miscellaneous options from persistent global variables
672 " function! VimEnter()
673 " for optname in g:options
674 " let varname = "g:OPT_" . toupper(optname)
676 " execute "let &" . optname . " = " . varname
680 " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
681 " execute "winpos" g:WINPOSX g:WINPOSY
685 " Called automagically before .viminfo is saved, saves miscellaneous
686 " options into persistent global variables
687 " function! VimLeavePre()
688 " call filter(g:, 'v:key !~# "^OPT_"')
689 " for optname in g:options
690 " let varname = "g:OPT_" . toupper(optname)
691 " execute "let " . varname . " = &g:" . optname
694 " if has("gui_running")
695 " let g:WINPOSX = getwinposx()
696 " let g:WINPOSY = getwinposy()
700 " autocmd VimEnter * call VimEnter()
701 " autocmd VimLeavePre * call VimLeavePre()
704 " Called automagically after every buffer read, enables fileencoding
705 " setting from modeline (see Tip #911:
706 " http://vim.fandom.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
707 function! AutoEncoding()
708 if &modified && &fileencoding != ""
709 call SetupEncoding(&fileencoding)
713 autocmd! auto-encoding
714 augroup! auto-encoding
717 augroup auto-encoding
719 autocmd BufWinEnter * call AutoEncoding()
725 " Value of a character under cursor; better than standard '0x%02B (%b)'
727 let char = matchstr(getline("."), ".", col(".") - 1)
729 let char = iconv(char, &encoding, &fileencoding)
730 let format = "0x%02X <%d>"
732 let format = "0x%02X (%d)"
734 let char = char2nr(char)
735 return printf(format, char, char)
740 " Helper function for :DecodeQP and :DecodeURL commands
741 function! DecodeHex(arg)
742 return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
745 " Custom completion for encoding names
746 function! EncList(ArgLead, CmdLine, CursorPos)
747 return filter(split(&fileencodings, ','),
748 \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
752 " Command for decoding qp-encoded text
753 command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
754 \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
756 " Command for decoding url-encoded text
757 command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
758 \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
764 function! SetupSpell()
765 if &fileencoding =~ 'ascii'
766 setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
767 elseif &fileencoding == 'koi8-r'
768 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
769 elseif &fileencoding == 'utf-8'
770 setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
772 setlocal spelllang= spellfile=
775 autocmd BufReadPost * call SetupSpell()
777 function! SaveSpell()
778 if expand('%') == expand('~/.vim/spell/en.ascii.add')
784 autocmd BufWritePost ~/.vim/spell/*.add call SaveSpell()
788 function! SyntaxName()
789 echomsg synIDattr(synID(line("."), col("."), 1), "name")
794 pyfile ~/.vim/python/completion.py
796 " Custom completion for python expressions
797 function! CompList(ArgLead, CmdLine, CursorPos)
798 python vim_comp_list()
801 " Python command line calculator
802 command! -nargs=+ -range -complete=customlist,CompList Calc
803 \ <line1>,<line2> python vim_calc(<q-args>)
805 " Python text range filter
806 command! -nargs=+ -range -complete=customlist,CompList Pydo
807 \ <line1>,<line2> python vim_pydo(<q-args>)
809 " Display unicode name for the character under cursor
810 command! Uname python vim_unicode_name()
814 py3file ~/.vim/python/completion.py
816 " Custom completion for python expressions
817 function! CompList(ArgLead, CmdLine, CursorPos)
818 python3 vim_comp_list()
821 " Python command line calculator
822 command! -nargs=+ -range -complete=customlist,CompList Calc
823 \ <line1>,<line2> python3 vim_calc(<q-args>)
825 " Python text range filter
826 command! -nargs=+ -range -complete=customlist,CompList Pydo
827 \ <line1>,<line2> python3 vim_pydo(<q-args>)
829 " Display unicode name for the character under cursor
830 command! Uname python3 vim_unicode_name()
833 if has("python") || has("python3")
838 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
839 set secure " safer working with script files in the current directory