]> git.phdru.name Git - dotfiles.git/blob - .vimrc
.vimrc: Update `titlestring` from default
[dotfiles.git] / .vimrc
1 " User configuration file for Vi IMproved.
2 "
3 " vim 6.0+ required, 7.0+ recommended.
4
5 " 1 important
6
7 " Remove ALL autocommands in case the file is sourced for the second time
8 autocmd!
9
10 language messages C " Print messages in English
11
12 if exists("b:wrap") " Only do this on the second and subsequent :source's
13    let fenc = &fileencoding
14    let ftype = &filetype
15    let mod = &modified
16    set all& " Reset all options, except terminal options, to their default value.
17    execute 'set fileencoding=' . fenc
18    execute 'set filetype=' . ftype
19    if mod
20       set modified
21    else
22       set nomodified
23    endif
24    unlet fenc ftype mod
25
26 elseif filereadable($VIMRUNTIME . "/defaults.vim")
27    unlet! skip_defaults_vim
28    source $VIMRUNTIME/defaults.vim
29 endif
30
31 " No, it is not VI, it is VIM! It is important to set this first, because this
32 " command resets many other options.
33 set nocompatible
34
35 " Set behavior to xterm, not mswin
36 behave xterm
37
38 " 2 moving around, searching and patterns
39
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
43
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
46
47 " 4 displaying text
48
49 set display=lastline,uhex " Show the last line instead of '@'; show non-printable chars as <hex>
50
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
54
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
61
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
65
66 set sidescroll=1  " The minimal number of columns to scroll horizontally
67
68 " 5 highlighting
69
70 colorscheme phd
71 set nohlsearch    " Stop the search highlighting
72
73 " 6 multiple windows
74
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
78
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
81
82 " 8 terminal
83
84 set ttyfast       " terminal connection is fast
85
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()}]
95
96 " 9 using the mouse
97
98 if has('mouse')
99    set mouse=ar      " Use mouse in all modes, plus hit-return
100 endif
101
102 " 12 messages and info
103
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
107 if v:version >= 800
108    set belloff=error,insertmode " Do not ring the bell for these reasons
109 endif
110
111 " Short message for [Modified];
112 " overwrite message for writing a file with subsequent message;
113 " truncate long file messages
114 set shortmess=mot
115
116 " 14 editing text
117
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
123
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
129
130 " 15 tabs and indenting
131
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>
136
137 set noautoindent  " Do not automatically set the indent of a new line
138
139 " 18 mapping
140
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
142
143 " 19 reading and writing files
144 if v:version >= 703
145    set cryptmethod=blowfish " encryption method for file writing: zip or blowfish
146 endif
147
148 " 20 the swap file
149
150 let myUndoDir = expand('~/tmp/vim/undo')
151 if !isdirectory(myUndoDir)
152     " Create dirs
153     call mkdir(myUndoDir, 'p')
154 endif
155
156 " list of directories for the swap file; remove . (the current directory)
157 if has("win32")
158    set directory=~/tmp/vim//,$TEMP//,c:/tmp//,c:/temp//
159 else
160    set directory=~/tmp/vim//,~/tmp//,/var/tmp//,/tmp//
161 endif
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.
166
167 " 21 command line editing
168
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
174
175 " Keep undo history across sessions by storing it in a file
176 if has('persistent_undo')
177     let &undodir = myUndoDir
178     set undofile
179 endif
180
181 " 22 executing external commands
182
183 if has("filterpipe")
184    set noshelltemp " Use pipes on Unix
185 endif
186
187 " 25 multi-byte characters
188
189 " Automatically detected character encodings
190 set fileencodings=ucs-bom,us-ascii,utf-8,koi8-r,cp1251,cp866,latin1
191
192 " 26 various
193
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.
200 set viminfo=!,h,'50
201 if version < 603
202    set viminfo+=\"1000
203 else
204    set viminfo+=<1000,s10
205 endif
206
207 " c - convert viminfo to the current encoding;
208 if has("iconv")
209    set viminfo+=c
210 endif
211
212 " Removable media paths
213 if has("win32")
214    set viminfo+=ra:,rb:
215 endif
216
217 " ----------
218
219 if has("gui_running")
220    set background=light
221
222    if has("win32")
223       "set guifont=Courier_New:h18:cRUSSIAN
224       set guifont=Lucida_Console:h18:cRUSSIAN
225    elseif has("x11")
226       set guifont=Monospace\ 18
227       set toolbar=icons,text " how to show the toolbar
228    endif
229
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
233
234    " Make shift-insert work like in Xterm
235    " map <S-Insert> <MiddleMouse>
236    " map! <S-Insert> <MiddleMouse>
237
238    " ----------
239    " From http://slobin.pp.ru/vim/_vimrc.html
240
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"
244
245    " The <CR> key should select from completion menu without adding a newline
246    imap <expr> <CR> pumvisible() ? "<C-Y>" : "<CR>"
247    " ----------
248
249 else
250    if (&term =~ "linux") || (&term =~ "cygwin") || (&term =~ "putty")
251          \ || ($BACKGROUND == 'DARK') || ($BACKGROUND == 'dark')
252          \ || has("win32")
253       " Background of the terminal is black or dark grey
254       set background=dark
255    else
256       set background=light
257    endif
258
259    if (&term =~ "linux")
260       execute 'set t_kb=' . nr2char(127)
261    endif
262
263    if (&term =~ "rxvt") || (&term =~ "screen") || (&term =~ "term") || (&term =~ "vt100")
264       execute 'set t_kb=' . nr2char(127)
265
266       if has ("terminfo")
267          " set t_Co=256
268          set t_Co=16
269       else
270          set t_Co=8
271          set t_Sf="\e[3%dm"
272          set t_Sb="\e[4%dm"
273       endif
274
275       " KP_Up -> Up
276       map <Esc>Ox <Esc>OA
277       map! <Esc>Ox <Esc>OA
278       " KP_Down -> Down
279       map <Esc>Or <Esc>OB
280       map! <Esc>Or <Esc>OB
281       " KP_Right -> Right
282       map <Esc>Ov <Esc>OC
283       map! <Esc>Ov <Esc>OC
284       " KP_Left -> Left
285       map <Esc>Ot <Esc>OD
286       map! <Esc>Ot <Esc>OD
287       " KP_Home -> Home
288       map <Esc>Ow <Esc>[7~
289       map! <Esc>Ow <Esc>[7~
290       " KP_End -> End
291       map <Esc>Oq <Esc>[8~
292       map! <Esc>Oq <Esc>[8~
293       " KP_Prev (PgDn) and KP_Next (PgUp) work fine, no mapping is required
294
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
301
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
306    endif
307
308    if (&term =~ "screen")
309       set ttymouse=xterm2 " Enable mouse codes under screen/tmux
310       if empty(&t_ts)
311          " Enable window title under screen/tmux
312          let &t_ts = "\e]2;"
313          let &t_fs = "\007"
314       endif
315    endif
316
317    " Bracketed paste mode
318    " https://github.com/ConradIrwin/vim-bracketed-paste/blob/master/plugin/bracketed-paste.vim
319    let &t_ti .= "\<Esc>[?2004h"
320    let &t_te = "\e[?2004l" . &t_te
321
322    function! XTermPasteBegin(ret)
323      set pastetoggle=<f29>
324      set paste
325      return a:ret
326    endfunction
327
328    execute "set <f28>=\<Esc>[200~"
329    execute "set <f29>=\<Esc>[201~"
330    map <expr> <f28> XTermPasteBegin("i")
331    imap <expr> <f28> XTermPasteBegin("")
332    vmap <expr> <f28> XTermPasteBegin("c")
333    cmap <f28> <nop>
334    cmap <f29> <nop>
335
336    "https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
337    " https://ttssh2.osdn.jp/manual/en/usage/tips/vim.html
338    function! WrapForScreenTmux(s)
339       if (&term =~ "screen")
340          let scr_start = "\<Esc>P"
341          let scr_end = "\<Esc>\\"
342
343          return scr_start . a:s . scr_end
344       endif
345
346       if exists('$TMUX')
347          let tmux_start = "\<Esc>Ptmux;"
348          let tmux_end = "\<Esc>\\"
349
350          return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
351       endif
352
353       return a:s
354    endfunction
355
356    " https://vim.fandom.com/wiki/Change_cursor_shape_in_different_modes
357    let &t_EI.=WrapForScreenTmux("\e[2 q") "EI = NORMAL mode (ELSE)
358    let &t_SI.=WrapForScreenTmux("\e[6 q") "SI = INSERT mode
359    if v:version >= 800
360       let &t_SR.=WrapForScreenTmux("\e[4 q") "SR = REPLACE mode
361    endif
362
363    "Cursor settings:
364    "  1 -> blinking block
365    "  2 -> solid block 
366    "  3 -> blinking underscore
367    "  4 -> solid underscore
368    "  5 -> blinking vertical bar
369    "  6 -> solid vertical bar
370 endif
371
372 " Multiline comments often confuse vim syntax highlighting - these maps
373 " allow to resynchronize; the first is faster, the second is more thorough
374 nmap \sc :syntax sync clear<Enter>
375 nmap \ss :syntax sync fromstart<Enter>
376
377
378 " AUTOCOMMANDS
379
380 " Enable filetype detection
381 filetype plugin indent on
382
383 runtime macros/matchit.vim
384
385 " Reread me after editing
386 autocmd BufWritePost ~/.vimrc source ~/.vimrc | syntax on
387
388 if version >= 700
389 " Save all files before running any quickfix command (grep, makeprg, etc.)
390 autocmd QuickFixCmdPre * wall
391 " automatically close quickfix if it's the only window left
392 autocmd WinEnter * if winnr('$') == 1 && 
393    \ index(["nofile", "quickfix"], &buftype) >= 0 | quit | endif
394 endif
395
396 " Syntax highlighting
397 autocmd BufReadPost * syntax on
398
399
400 " Restore last known cursor position
401 function! RestorePosition()
402    if exists('b:position_restored')
403       return
404    endif
405
406    if line("'\"") > 0
407       call cursor(line("'\""), col("'\""))
408    endif
409    let b:position_restored = 1
410 endfunction
411
412 " When editing a file, always jump to the last cursor position (if saved)
413 autocmd BufReadPost * call RestorePosition()
414
415
416 function! SetupEncoding(encoding)
417    if !has("iconv") || exists('b:encoding_set') || empty(a:encoding)
418       return
419    endif
420
421    call RestorePosition()
422    let b:encoding_set = 1
423    if !empty(expand('%'))
424       execute "edit ++enc=" . a:encoding
425    endif
426 endfunction
427
428
429 " From http://lwn.net/Articles/226514/
430
431 augroup gpg
432 " Remove ALL autocommands for the current group.
433 autocmd!
434 autocmd BufReadPre,FileReadPre *.gpg set viminfo=
435 autocmd BufReadPre,FileReadPre *.gpg setlocal noswapfile
436 autocmd BufReadPost *.gpg :%!gpg -q -d
437 autocmd BufReadPost *.gpg | redraw
438 autocmd BufWritePre *.gpg :%!gpg --default-recipient-self -q -e -a
439 autocmd BufWritePost *.gpg u
440 autocmd VimLeave *.gpg :!clear
441 " For OpenSSL:
442 " BufReadPost: use "openssl bf -d -a"
443 " BufWritePre: use "openssl bf -salt -a"
444 augroup END
445
446
447 function! SetWrap()
448    setlocal wrap
449    map <Up> gk
450    imap <Up> <C-O>gk
451    map <Down> gj
452    imap <Down> <C-O>gj
453    let b:wrap = 1
454 endfunction
455
456 function! SetNoWrap()
457    setlocal nowrap
458    map <Up> k
459    map <Down> j
460    let b:wrap = 0
461 endfunction
462
463 command! SetWrap call SetWrap()
464 command! SetNoWrap call SetNoWrap()
465
466 " b:wrap can be set by an ftplugin
467 autocmd BufReadPost * if !exists("b:wrap") | call SetWrap() | endif
468
469
470 " MAPPINGS
471
472 " Do not unindent #-comment
473 inoremap # X<C-H>#
474
475 " map <C-A> <Home>
476 " map <C-E> <End>
477 " map <C-Z> :shell<CR>
478
479
480 if version >= 700
481 " WEB BROWSERS
482
483 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"
484
485 function! ExtractURL()
486    let line = getline('.')
487    let parts = split(line, s:URL_re . '\zs')
488
489    if empty(parts)
490       throw 'ExtractURLCannotFindURL' " No URL found
491    endif
492
493    let length = 0
494    let column = col('.')
495
496    for p in parts
497       let save_length = length
498       let length += len(p)
499       if length >= column
500          break
501       endif
502    endfor
503
504    let pos = match(p, s:URL_re)
505    if pos == -1
506       throw 'ExtractURLCannotFindURL' " No URL found
507    endif
508
509    if save_length + pos >= column " cursor left of the URL
510       throw 'ExtractURLCannotFindURL'
511    endif
512
513    return strpart(p, pos)
514 endfunction
515
516 function! EscapeURL(url)
517    let url = substitute(a:url, ' ', '%20', 'g')
518    return escape(url, '!#$%')
519 endfunction
520
521 function! OpenURL(url, newwin)
522    execute "!webbrowser " . a:newwin . " '" . EscapeURL(a:url) . "'"
523 endfunction
524
525 function! ExtractOpenURL(newwin)
526    try
527       let url = ExtractURL()
528    catch /^ExtractURLCannotFindURL$/
529       echoerr 'No URL found under cursor'
530       return
531    endtry
532
533    call OpenURL(url, a:newwin)
534 endfunction
535
536 function! EncodeOpenURL(url, newwin)
537    execute "!webbrowser-encode-url " . a:newwin . " '" . EscapeURL(a:url) . "'"
538 endfunction
539
540
541 " Send current link to a browser
542 nmap \b :call ExtractOpenURL('')<CR>
543 nmap \w :call ExtractOpenURL('-n')<CR>
544 nmap \t :call ExtractOpenURL('-t')<CR>
545 " Send visual block to a browser
546 vmap \b ""y:call OpenURL('<C-R>"', '')<CR>
547 vmap \w ""y:call OpenURL('<C-R>"', '-n')<CR>
548 vmap \t ""y:call OpenURL('<C-R>"', '-t')<CR>
549 " Encode and send visual block to a browser
550 vmap \B ""y:call EncodeOpenURL('<C-R>"', '')<CR>
551 vmap \W ""y:call EncodeOpenURL('<C-R>"', '-n')<CR>
552 vmap \T ""y:call EncodeOpenURL('<C-R>"', '-t')<CR>
553 " Send current file's name to a browser
554 nmap \B :call EncodeOpenURL('file:' . expand("%:p"), '')<CR>
555 nmap \W :call EncodeOpenURL('file:' . expand("%:p"), '-n')<CR>
556 nmap \T :call EncodeOpenURL('file:' . expand("%:p"), '-t')<CR>
557
558 endif " version >= 700
559
560
561 " SPELLING
562
563 if has("spell") " Works in 7.0+
564    " Use builtin spellchecker
565    nmap \sv :syntax off <BAR> setlocal spell<CR>
566    " Clear
567    nmap \sn :syntax on <BAR> setlocal nospell<CR>
568 endif
569
570
571 " Russian letters mapped in normal mode
572 "if has("keymap")
573 "   set keymap=russian-jcuken
574 "endif
575
576 if has("langmap")
577    if v:version >= 702
578       " langmap in utf-8 mode requires at least Vim 7.2.109
579       scriptencoding utf-8
580       set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
581                  \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
582                  \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
583
584    elseif &encoding != 'utf-8'
585       scriptencoding koi8-r
586       set langmap=ё`Ё~йqцwуeкrеtнyгuшiщoзpх[ъ]фaыsвdаfпgрhоjлkдlж\\;э'
587                  \яzчxсcмvиbтnьmб\\,ю.ЙQЦWУEКRЕTНYГUШIЩOЗPХ{Ъ}
588                  \ФAЫSВDАFПGРHОJЛKДLЖ:Э\\"ЯZЧXСCМVИBТNЬMБ<Ю>
589    endif
590
591    scriptencoding us-ascii
592 endif
593
594
595 if version >= 700
596 function! W()
597    " let encodings=filter(split(&fileencodings, ','), 'v:val != "ucs-bom"')
598    let encodings = ['us-ascii']
599    if $LC_CTYPE =~ 'UTF-8' " UTF-8 or en_US.UTF-8 or ru_RU.UTF-8 or such
600       let encodings += ['utf-8']
601    elseif $LC_CTYPE == 'ru_RU.KOI8-R'
602       let encodings += ['koi8-r', 'utf-8']
603    elseif v:lc_time == 'Russian_Russia.1251'
604       let encodings += ['cp1251', 'utf-8']
605    endif
606
607    for e in encodings
608       try
609          execute 'set fileencoding=' . e
610          w
611          break
612       catch /E513: write error, conversion failed/
613          continue
614       endtry
615    endfor
616
617    if &modified
618       throw '"' . expand('%') . '" E513: write error, conversion failed; tried ' . join(encodings, ',')
619    elseif has("spell")
620       call SetupSpell()
621    endif
622 endfunction
623
624 command! W call W()
625 endif
626
627
628 function! SlowTerm()
629    set laststatus=1
630    set noruler
631    set shortmess=aoOtT
632    set noshowcmd
633    set scrolljump=5 " The minimal number of lines to scroll vertically when the cursor gets of the screen
634    set sidescroll=5
635    set nottyfast
636    set notitle
637    set timeoutlen=5000
638    set nowildmenu
639    set wildmode=list:longest
640    set viminfo=!,h,'10,<100,s5
641    if has("iconv")
642       set viminfo+=c
643    endif
644    syntax off
645    highlight NonText cterm=NONE ctermfg=NONE
646 endfunction
647
648 if exists("$SLOWTERM")
649    call SlowTerm()
650 endif
651
652
653 if has("python")
654 pyfile ~/.vim/python/virtualenv.py
655 endif
656
657 if has("python3")
658 py3file ~/.vim/python/virtualenv.py
659 endif
660
661
662 " From Tip 212:
663 " http://vim.fandom.com/wiki/Setting_file_attributes_without_reloading_a_buffer
664
665 if executable('chmod')
666    function! SetExecutableBit(x)
667       checktime
668       " Avoid 'Reload Y/N?' question
669       autocmd FileChangedShell <buffer> call _BufChangedCB()
670       let fx = executable(expand("%:p"))
671       if a:x && !fx
672          silent !chmod a+x %
673       elseif !a:x && fx
674          silent !chmod a-x %
675       endif
676       if v:shell_error
677          echoerr 'Error running chmod: ' . v:shell_error
678       endif
679       checktime
680       autocmd! FileChangedShell <buffer>
681    endfunction
682    function! _BufChangedCB()
683       autocmd! FileChangedShell <buffer>
684    endfunction
685    command! ToggleXbit if executable(expand("%:p")) | call SetExecutableBit(0) | else | call SetExecutableBit(1) | endif
686 endif
687
688 function! Code()
689     setlocal expandtab tabstop=8 softtabstop=4 shiftwidth=4
690 endfunction
691 command! Code call Code()
692
693 function! Text()
694     setlocal expandtab tabstop=8 softtabstop=3 shiftwidth=3
695 endfunction
696 command! Text call Text()
697
698 " ----------
699 " From http://slobin.pp.ru/vim/_vimrc.html
700
701 " These options will be kept between editing sessions
702 " let options = []
703
704 " Called automagically after .viminfo and plugins are loaded, sets
705 " miscellaneous options from persistent global variables
706 " function! VimEnter()
707   " for optname in g:options
708   "   let varname = "g:OPT_" . toupper(optname)
709   "   if exists(varname)
710   "     execute "let &" . optname . " = " . varname
711   "   endif
712   " endfor
713
714   " if has("gui_running") && exists("g:WINPOSX") && exists("g:WINPOSY")
715   "   execute "winpos" g:WINPOSX g:WINPOSY
716   " endif
717 " endfunction
718
719 " Called automagically before .viminfo is saved, saves miscellaneous
720 " options into persistent global variables
721 " function! VimLeavePre()
722   " call filter(g:, 'v:key !~# "^OPT_"')
723   " for optname in g:options
724   "   let varname = "g:OPT_" . toupper(optname)
725   "   execute "let " . varname . " = &g:" . optname
726   " endfor
727
728   " if has("gui_running")
729   "   let g:WINPOSX = getwinposx()
730   "   let g:WINPOSY = getwinposy()
731   " endif
732 " endfunction
733
734 " autocmd VimEnter * call VimEnter()
735 " autocmd VimLeavePre * call VimLeavePre()
736
737
738 " Called automagically after every buffer read, enables fileencoding
739 " setting from modeline (see Tip #911:
740 " http://vim.fandom.com/wiki/How_to_make_fileencoding_work_in_the_modeline)
741 function! AutoEncoding()
742   if &modified && &fileencoding != ""
743     call SetupEncoding(&fileencoding)
744   endif
745   autocmd! auto-encoding
746   augroup! auto-encoding
747 endfunction
748
749 augroup auto-encoding
750 autocmd!
751 autocmd BufWinEnter * call AutoEncoding()
752 augroup END
753
754
755 let CONVERT=1
756
757 " Value of a character under cursor; better than standard '0x%02B (%b)'
758 function! HexDec()
759   let char = matchstr(getline("."), ".", col(".") - 1)
760   if g:CONVERT
761     let char = iconv(char, &encoding, &fileencoding)
762     let format = "0x%02X <%d>"
763   else
764     let format = "0x%02X (%d)"
765   endif
766   let char = char2nr(char)
767   return printf(format, char, char)
768 endfunction
769
770
771 if has("iconv")
772    " Helper function for :DecodeQP and :DecodeURL commands
773    function! DecodeHex(arg)
774      return iconv(printf("%c", str2nr(submatch(1), 16)), a:arg, &encoding)
775    endfunction
776
777    " Custom completion for encoding names
778    function! EncList(ArgLead, CmdLine, CursorPos)
779      return filter(split(&fileencodings, ','),
780                  \ "strpart(v:val, 0, strlen(a:ArgLead)) == a:ArgLead")
781    endfunction
782
783    if version >= 700
784    " Command for decoding qp-encoded text
785    command! -bar -nargs=? -range -complete=customlist,EncList DecodeQP
786           \ <line1>,<line2>s/=\(\x\x\|\n\)/\=DecodeHex(<q-args>)/eg
787
788    " Command for decoding url-encoded text
789    command! -bar -nargs=? -range -complete=customlist,EncList DecodeURL
790           \ <line1>,<line2>s/%\(\x\x\)/\=DecodeHex(<q-args>)/eg
791    endif
792 endif
793
794
795 if has("spell")
796    function! SetupSpell()
797       if &fileencoding =~ 'ascii'
798          setlocal spelllang=en spellfile=~/.vim/spell/en.ascii.add
799       elseif &fileencoding == 'koi8-r'
800          setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.koi8-r.add
801       elseif &fileencoding == 'utf-8'
802          setlocal spelllang=en,ru spellfile=~/.vim/spell/en.ascii.add,~/.vim/spell/ru.utf-8.add
803       else
804          setlocal spelllang= spellfile=
805       endif
806    endfunction
807    autocmd BufReadPost * call SetupSpell()
808
809    function! SaveSpell()
810       if expand('%:p') == expand('~/.vim/spell/en.ascii.add')
811          mkspell! -ascii %
812       else
813          mkspell! %
814       endif
815    endfunction
816    autocmd BufWritePost ~/.vim/spell/*.add call SaveSpell()
817 endif
818
819
820 function! SyntaxName()
821   echomsg synIDattr(synID(line("."), col("."), 1), "name")
822 endfunction
823
824
825 if has("python")
826 pyfile ~/.vim/python/completion.py
827
828 " Custom completion for python expressions
829 function! CompList(ArgLead, CmdLine, CursorPos)
830   python vim_comp_list()
831 endfunction
832
833 " Python command line calculator
834 command! -nargs=+ -range -complete=customlist,CompList Calc
835        \ <line1>,<line2> python vim_calc(<q-args>)
836
837 " Python text range filter
838 command! -nargs=+ -range -complete=customlist,CompList Pydo
839        \ <line1>,<line2> python vim_pydo(<q-args>)
840
841 " Display unicode name for the character under cursor
842 command! Uname python vim_unicode_name()
843 endif
844
845 if has("python3")
846 py3file ~/.vim/python/completion.py
847
848 " Custom completion for python expressions
849 function! CompList(ArgLead, CmdLine, CursorPos)
850   python3 vim_comp_list()
851 endfunction
852
853 " Python command line calculator
854 command! -nargs=+ -range -complete=customlist,CompList Calc
855        \ <line1>,<line2> python3 vim_calc(<q-args>)
856
857 " Python text range filter
858 command! -nargs=+ -range -complete=customlist,CompList Pydo
859        \ <line1>,<line2> python3 vim_pydo(<q-args>)
860
861 " Display unicode name for the character under cursor
862 command! Uname python3 vim_unicode_name()
863 endif
864
865 if has("python") || has("python3")
866 command! UName Uname
867 endif
868 " ----------
869
870 if v:version >= 800
871    function! SetLazyRedraw(timer_id)
872       call timer_stop(a:timer_id) " One-time event
873       set lazyredraw
874    endfunction
875    call timer_start(500, 'SetLazyRedraw')
876 endif
877
878 " This has to go to the very end of ~/.vimrc to allow reading the .vimrc
879 set secure        " safer working with script files in the current directory