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