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