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