]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - vimrc
49ccdfe41a784401b41b709f8a116455cecf710e
[config/dotfiles.git] / vimrc
1 " Vim main configuration file.
2
3 " Copyright (C) 2008-2013  Simon Ruderich
4 "
5 " This file is free software: you can redistribute it and/or modify
6 " it under the terms of the GNU General Public License as published by
7 " the Free Software Foundation, either version 3 of the License, or
8 " (at your option) any later version.
9 "
10 " This file is distributed in the hope that it will be useful,
11 " but WITHOUT ANY WARRANTY; without even the implied warranty of
12 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 " GNU General Public License for more details.
14 "
15 " You should have received a copy of the GNU General Public License
16 " along with this file.  If not, see <http://www.gnu.org/licenses/>.
17
18
19 " EDITOR SETTINGS
20
21 " Save 'runtimepath' in case it was changed by the system's configuration
22 " files. Also save 'diff' as set all& resets it; but somehow later (after
23 " sourcing the vimrc - for example in a VimEnter autocmd) it gets
24 " automagically restored to the correct value. Not sure what exactly Vim is
25 " doing there.
26 if has('eval')
27     let s:save_runtimepath = &runtimepath
28     let s:save_diff = &diff
29 endif
30 " Reset all options (except 'term', 'lines' and 'columns'). This makes sure a
31 " system wide configuration file doesn't change default values.
32 set all&
33 " And restore it after all other options were reset.
34 if has('eval')
35     let &runtimepath = s:save_runtimepath
36     let &diff = s:save_diff
37     unlet s:save_runtimepath
38     unlet s:save_diff
39 endif
40
41 " Make sure Vim (and not Vi) settings are used.
42 set nocompatible
43
44 " Disallow :autocmd, shell and write commands in .vimrc and .exrc files in the
45 " current directory. Only used if 'exrc' is enabled (off by default),
46 " precaution just in case somebody enables 'exrc'.
47 set secure
48
49 " Use UTF-8 for all internal data (buffers, registers, etc.). This doesn't
50 " affect reading files in different encodings, see 'fileencodings' for that.
51 set encoding=utf-8
52
53 " Load my scripts from ~/.vim (my scripts) and ~/.vim/runtime (checkout of Vim
54 " runtime files) if available.
55 set runtimepath-=~/.vim
56 set runtimepath^=~/.vim,~/.vim/runtime
57
58 " Don't store swap files in the same directory as the edited file, but only if
59 " we have a "safe" writable directory available.
60 if filewritable('~/.tmp') == 2 || filewritable('~/tmp') == 2
61     set directory-=.
62 endif
63 " But store them in ~/.tmp or ~/tmp (already set by default) if available.
64 set directory^=~/.tmp
65 " Never use /tmp which gets cleaned on reboot.
66 set directory-=/tmp
67
68 " Disable modelines as they may cause security problems. Instead use
69 " securemodelines (Vim script #1876).
70 set nomodeline
71
72 " Complete to longest common string (list:longest) and then complete all full
73 " matches after another (full). Thanks to pbrisbin
74 " (http://pbrisbin.com:8080/dotfiles/vimrc).
75 set wildmode=list:longest,full
76 " Ignore case when completing files/directories.
77 if exists('+wildignorecase')
78     set wildignorecase
79 endif
80
81 " Ignore files with the following extensions because I almost never want to
82 " edit them in Vim (specifying them manually still works of course).
83 set wildignore=
84 " C
85 set wildignore+=*.o,*.d,*.so
86 " Java
87 set wildignore+=*.class
88 " LaTeX
89 set wildignore+=*.aux,*.log,*.out,*.toc,*.pdf
90 " Python
91 set wildignore+=*.pyc
92
93 " Show completion menu even if only one entry matches.
94 if exists('+completeopt')
95     set completeopt+=menuone
96 endif
97
98 " Increase history of executed commands (:) and search patterns (/).
99 set history=1000
100
101 " Increase number of possible undos.
102 set undolevels=1000
103
104 " Remember marks (including the last cursor position) for more files. ^= is
105 " necessary because 'viminfo' is parsed from the beginning and the first match
106 " is used.
107 if has('viminfo')
108     set viminfo^='1000
109 endif
110
111 " Use strong encryption if possible, also used for swap/undo files.
112 if exists('+cryptmethod')
113     set cryptmethod=blowfish
114 endif
115
116 " Clear all vimrc-related autocmds. Has to be done here as the vimrc augroup
117 " is used multiple times. Necessary to support reloading the vimrc.
118 if has('autocmd')
119     augroup vimrc
120         autocmd!
121     augroup END
122 endif
123
124
125 " HELPER FUNCTIONS
126
127 if has('eval')
128 " Check if the given syntax group is available. Thanks to bairui in #vim on
129 " Freenode (2012-02-19 01:15 CET) for the try/catch silent highlight idea.
130     function! s:HasSyntaxGroup(group)
131         try
132             execute 'silent highlight ' . a:group
133         " \a = [A-Za-z]
134         catch /^Vim\%((\a\+)\)\=:E411/ " 'highlight group not found'
135             return 0
136         endtry
137         return 1
138     endfunction
139
140 " Check if the given Vim version and patch is available.
141     function! s:HasVersionAndPatch(version, patch)
142         return v:version > a:version
143             \ || (v:version == a:version && has('patch' . a:patch))
144     endfunction
145 endif
146
147
148 " TERMINAL SETTINGS
149
150 " Also enable fast terminal mode in GNU screen and tmux, but not for SSH
151 " connections.
152 if &term =~# '^screen' && !exists('$SSH_CONNECTION')
153     set ttyfast
154 endif
155
156
157 " EDIT SETTINGS
158
159 " Enable automatic file detection, plugin and indention support.
160 if has('autocmd')
161     filetype off " necessary for pathogen to force a reload of ftplugins
162     filetype plugin indent on
163 endif
164
165 " Use UTF-8 file encoding for all files. Automatically recognize latin1 in
166 " existing files.
167 set fileencodings=utf-8,latin1
168
169 " Always use unix line-endings for new files. DOS line endings in existing
170 " files are recognized.
171 set fileformats=unix,dos
172
173 " Wrap text after 78 characters.
174 set textwidth=78
175
176 " Set tabs to 4 spaces, use softtabs.
177 set shiftwidth=4
178 set softtabstop=4
179 set expandtab
180 " When < and > is used indent/deindent to the next 'shiftwidth' boundary.
181 set shiftround
182 " Use the default value for real tabs.
183 set tabstop=8
184
185 " Enable auto indention.
186 set autoindent
187
188 " When joining lines only add one space after a sentence.
189 set nojoinspaces
190
191 " Allow backspacing over autoindent and line breaks.
192 set backspace=indent,eol
193
194 " Start a comment when hitting enter after a commented line (r) and when using
195 " o or O around a commented line (o).
196 set formatoptions+=ro
197 " Don't break a line if was already longer then 'textwidth' when insert mode
198 " started.
199 set formatoptions+=l
200 " Remove comment leader when joining lines where it makes sense.
201 if s:HasVersionAndPatch(703, 541)
202     set formatoptions+=j
203 endif
204
205 " Allow virtual editing (cursor can be positioned anywhere, even when there is
206 " no character) in visual block mode.
207 set virtualedit=block
208
209 " Already display matches while typing the search command. This makes spotting
210 " typos easy and searching faster.
211 set incsearch
212
213 " Activate syntax folding.
214 if has('folding')
215     set foldmethod=syntax
216     " Only use fold column if we have enough space (for example not in a
217     " (virtual) terminal which has only 80 columns).
218     if &columns > 80
219         set foldcolumn=2
220     endif
221     set foldlevel=99 " no closed folds at default, 'foldenable' would disable
222                      " folding which is not what I want
223     " Don't open folds for block movements like '(', '{', '[[', '[{', etc.
224     set foldopen-=block
225 endif
226
227 " Only check case if the searched word contains a capital character.
228 set ignorecase
229 set smartcase
230
231 " Activate spell checking, use English as default.
232 if exists('+spell') && has('syntax')
233     " But not when diffing because spell checking is distracting in this case.
234     if !&diff
235         set spell
236     endif
237     set spelllang=en_us
238 endif
239
240 " Allow buffers with changes to be hidden. Very important for efficient
241 " editing with multiple buffers. Prevents the "E37: No write since last change
242 " (add ! to override)" warning when switching modified buffers.
243 set hidden
244
245 " When splitting vertically put the new window right of the current one.
246 if has('vertsplit')
247     set splitright
248 endif
249
250
251 " DISPLAY SETTINGS
252
253 " Use a dark background. Doesn't change the background color, only sets text
254 " colors for a dark terminal.
255 set background=dark
256
257 " Use my color scheme if 256 colors are available.
258 if &t_Co == 256 || has('gui_running')
259     colorscheme simon
260 endif
261
262 " Display line numbers.
263 set number
264 " But use as little space as possible for the numbers column. Thanks to James
265 " Vega (http://git.jamessan.com/?p=etc/vim.git;a=summary).
266 if exists('+numberwidth')
267     set numberwidth=1
268 endif
269 " Display the ruler with current line/file position. If 'statusline' is used,
270 " then this only affects <C-G>.
271 set ruler
272 " Display partial commands in the status line.
273 set showcmd
274
275 " Don't redraw screen when executing macros; increases speed. Thanks to James
276 " Vega (http://git.jamessan.com/?p=etc/vim.git;a=summary).
277 set lazyredraw
278
279 " Visualize the line the cursor is currently in.
280 if exists('+cursorline')
281     set cursorline
282 endif
283
284 " Highlight all matches on the screen when searching. Use <C-L> (see below) to
285 " remove the highlighting until the next search.
286 set hlsearch
287
288 " Display some special characters.
289 set list
290 set listchars=
291 " Display tabs as ">--------".
292 set listchars+=tab:>-
293 " Display trailing whitespace as "-".
294 set listchars+=trail:-
295 " Display markers for long lines when wrapping is disabled.
296 set listchars+=extends:>,precedes:<
297 " Display non-breakable space as "!".
298 if v:version >= 700
299     set listchars+=nbsp:!
300 endif
301
302 " Don't draw the vertical split separator by using space as character. Thanks
303 " to scp1 in #vim on Freenode (2012-06-16 16:12 CEST) for the idea to use a
304 " non-breakable space. But a simple space works as well, as long as the
305 " current color scheme is not reset.
306 if has('windows') && has('folding')
307     set fillchars+=vert:\  " comment to prevent trailing whitespace
308 endif
309
310 if has('statusline')
311     " Always display the status line even if there is only one window.
312     set laststatus=2
313
314     " If there's more than one buffer return "/<nr>" (e.g. "/05") where <nr>
315     " is the highest buffer number, otherwise return nothing. Used in
316     " 'statusline' to get an overview of available buffer numbers.
317     function! s:StatuslineBufferCount()
318         let l:bufnr = bufnr('$')
319         if l:bufnr > 1
320             let l:result = '/'
321             if exists('*printf')
322                 let l:result .= printf('%02d', l:bufnr)
323             else
324                 " Older Vims don't have printf() (and no .= either). Emulate
325                 " "%02d".
326                 if l:bufnr < 10
327                     let l:result = l:result . '0'
328                 endif
329                 let l:result = l:result . l:bufnr
330             endif
331             return l:result
332         else
333             return ''
334         endif
335     endfunction
336
337     " Like %f but use relative filename if it's shorter than the absolute path
338     " (e.g. '../../file' vs. '~/long/path/to/file'). fnamemodify()'s ':.' is
339     " not enough because it doesn't create '../'s.
340     function! s:StatuslineRelativeFilename()
341         " Display only filename for help files.
342         if &buftype == 'help'
343             return expand('%:t')
344         endif
345         " Special case for scratch files.
346         if &buftype == 'nofile'
347             return '[Scratch]'
348         endif
349
350         let l:path = expand('%')
351         " No file.
352         if l:path == ''
353             return '[No Name]'
354         endif
355         " Path is already relative, nothing to do.
356         if stridx(l:path, '/') != 0
357             return l:path
358         endif
359
360         " Absolute path to this file.
361         let l:path = expand('%:p')
362         " Shortened path to this file, thanks to bairui in #vim on Freenode
363         " (2012-06-23 00:54) for the tip to use fnamemodify(). This is what
364         " Vim normally uses as %f (minus some exceptions).
365         let l:original_path = fnamemodify(l:path, ':~')
366         " Absolute path to the current working directory.
367         let l:cwd = getcwd()
368
369         " Working directory completely contained in path, replace it with a
370         " relative path. Happens for example when opening a file with netrw.
371         " %f displays this as absolute path, but we want a relative path of
372         " course.
373         if stridx(l:path, l:cwd) == 0
374             return strpart(l:path, strlen(l:cwd) + 1)
375         endif
376
377         let l:path_list = split(l:path, '/')
378         let l:cwd_list  = split(l:cwd,  '/')
379
380         " Remove the common path.
381         while l:path_list[0] == l:cwd_list[0]
382             call remove(l:path_list, 0)
383             call remove(l:cwd_list,  0)
384         endwhile
385
386         " Add as many '..' as necessary for the relative path and join the
387         " path. Thanks to Raimondi in #vim on Freenode (2012-06-23 01:13) for
388         " the hint to use repeat() instead of a loop.
389         let l:path = repeat('../', len(l:cwd_list)) . join(l:path_list, '/')
390
391         " Use the shorter path, either relative or absolute.
392         if strlen(l:path) < strlen(l:original_path)
393             return l:path
394         else
395             return l:original_path
396         endif
397     endfunction
398
399     " Display unexpected 'fileformat', 'fileencoding' and 'bomb' settings.
400     function! s:StatuslineFileFormat()
401         if &fileformat != 'unix'
402             return '[' . &fileformat . ']'
403         else
404             return ''
405         endif
406     endfunction
407     function! s:StatuslineFileEncoding()
408         if &fileencoding != '' && &fileencoding != 'utf-8'
409                 \ && &filetype != 'help'
410             return '[' . &fileencoding . ']'
411         else
412             return ''
413         endif
414     endfunction
415     function! s:StatuslineFileBOMB()
416         if exists('+bomb') && &bomb
417             return '[BOM]'
418         else
419             return ''
420         endif
421     endfunction
422
423     " Return current syntax group in brackets or nothing if there's none.
424     function! s:StatuslineSyntaxGroup()
425         let l:group = synIDattr(synID(line('.'), col('.'), 1), 'name')
426         if l:group != ''
427             return '[' . l:group . '] '
428         else
429             return ''
430         endif
431     endfunction
432
433     " Short function names to make 'statusline' more readable.
434     function! SBC()
435         return s:StatuslineBufferCount()
436     endfunction
437     function! SRF()
438         return s:StatuslineRelativeFilename()
439     endfunction
440     function! SFF()
441         return s:StatuslineFileFormat()
442     endfunction
443     function! SFE()
444         return s:StatuslineFileEncoding()
445     endfunction
446     function! SFB()
447         return s:StatuslineFileBOMB()
448     endfunction
449     function! SSG()
450         return s:StatuslineSyntaxGroup()
451     endfunction
452
453     set statusline=
454     " on the left
455     set statusline+=%02n              " buffer number
456     set statusline+=%{SBC()}          " highest buffer number
457     set statusline+=:
458     if has('modify_fname') && v:version >= 700 " some functions need 7.0
459         set statusline+=%{SRF()}      " path to current file
460     else
461         set statusline+=%f            " path to current file in buffer
462     endif
463     set statusline+=\                 " space after path
464     set statusline+=%h                " [help] if buffer is help file
465     set statusline+=%w                " [Preview] if buffer is preview buffer
466     set statusline+=%m                " [+] if buffer was modified,
467                                       " [-] if 'modifiable' is off
468     set statusline+=%r                " [RO] if buffer is read only
469     if v:version >= 700               " %#..# needs 7.0
470         set statusline+=%#Error#      " display warnings
471         set statusline+=%{SFF()}      "   - unexpected file format
472         set statusline+=%{SFE()}      "   - unexpected file encoding
473         set statusline+=%{SFB()}      "   - unexpected file byte order mask
474         set statusline+=%##           " continue with normal colors
475     endif
476
477     " on the right
478     set statusline+=%=                " right align
479     set statusline+=0x%-8B\           " current character under cursor as hex
480     set statusline+=%-12.(%l,%c%V%)\  " line number (%l),
481                                       " column number (%c),
482                                       " virtual column number if different
483                                       "                       than %c (%V)
484     set statusline+=%P                " position in file in percent
485 endif
486
487
488 " MAPPINGS (except for plugins, see PLUGIN SETTINGS below)
489
490 " noremap is used to make sure the right side is executed as is and can't be
491 " modified by a plugin or other settings. Except for <Nop> which isn't
492 " affected by mappings.
493
494 " Easy way to exit insert mode (jj is too slow).
495 inoremap jk <Esc>
496 " Also for command mode, thanks to http://github.com/mitechie/pyvim
497 " (2010-10-15).
498 cnoremap jk <C-C>
499 " And fix my typos ...
500 inoremap JK <Esc>
501 inoremap Jk <Esc>
502 inoremap jK <Esc>
503 cnoremap JK <C-C>
504 cnoremap Jk <C-C>
505 cnoremap jK <C-C>
506
507 " Disable arrow keys for all modes except command modes. Thanks to James Vega
508 " (http://git.jamessan.com/?p=etc/vim.git;a=summary).
509 map <Right>  <Nop>
510 map <Left>   <Nop>
511 map <Up>     <Nop>
512 map <Down>   <Nop>
513 imap <Right> <Nop>
514 imap <Left>  <Nop>
515 imap <Up>    <Nop>
516 imap <Down>  <Nop>
517 " Also disable arrow keys in command mode, use <C-P>/<C-N> as replacement (see
518 " below).
519 cmap <Up>    <Nop>
520 cmap <Down>  <Nop>
521 cmap <Right> <Nop>
522 cmap <Left>  <Nop>
523
524 " Use <C-P>/<C-N> as replacement for <Up>/<Down> in command mode. Thanks to
525 " abstrakt and grayw in #vim on Freenode (2010-04-12 21:20 CEST).
526 cnoremap <C-P> <Up>
527 cnoremap <C-N> <Down>
528
529 if has('eval')
530 " Don't move the cursor to the first column for certain scroll commands (<C-F,
531 " <C-B>, <C-D>, <C-U>). Thanks to jamessan in #vim on Freenode (2011-08-31
532 " 02:27 CEST) for the 'nostartofline' tip. But I can't use 'nostartofline'
533 " directly because it also enables that feature for other commands which I
534 " don't want.
535
536     " Set 'nostartofline' for a single movement.
537     function! s:TemporaryNostartofline(movement)
538         let l:startofline = &startofline
539         set nostartofline
540         execute 'normal! ' . a:movement
541         let &startofline = l:startofline
542     endfunction
543
544     " Thanks to fow in #vim on Freenode (2012-02-16 15:38 CET) for the idea to
545     " use "<Bslash><Lt>"; Vim documentation reference: :help <>.
546     nnoremap <silent> <C-F>
547         \ :call <SID>TemporaryNostartofline("<Bslash><Lt>C-F>")<CR>
548     nnoremap <silent> <C-B>
549         \ :call <SID>TemporaryNostartofline("<Bslash><Lt>C-B>")<CR>
550     nnoremap <silent> <C-D>
551         \ :call <SID>TemporaryNostartofline("<Bslash><Lt>C-D>")<CR>
552     nnoremap <silent> <C-U>
553         \ :call <SID>TemporaryNostartofline("<Bslash><Lt>C-U>")<CR>
554 endif
555
556 " Let Y yank to the end of the line, similar to D and C. Use yy if you want to
557 " yank a line. This fixes a weird inconsistency in Vi(m).
558 nnoremap Y y$
559
560 " Write before suspending, thanks to deryni in #vim on Freenode (2011-05-09
561 " 20:02 CEST). To suspend without saving either unmap this or use :stop<CR>.
562 " Only the current buffer is written, thus switching to another buffer works
563 " too.
564 nnoremap <silent> <C-Z> :update<CR>:stop<CR>
565
566 " 2<C-G> gives more verbose information, use it by default. Thanks to NCS_One
567 " in #vim on Freenode (2011-08-15 00:17 CEST).
568 nnoremap <C-G> 2<C-G>
569
570 " Use <Space> to move down a page and - to move up one like in mutt. Don't use
571 " nnoremap so the <C-F>/<C-B> 'nostartofline' fix (see above) works.
572 nmap <Space> <C-F>
573 nmap - <C-B>
574
575 " Go to next and previous buffer. Thanks to elik in #vim on Freenode
576 " (2010-05-16 18:38 CEST) for this idea.
577 nnoremap <silent> gb :bnext<CR>
578 nnoremap <silent> gB :bprevious<CR>
579 if has('eval')
580     " But when starting again at the first buffer, print a warning which
581     " reminds me that I've already seen that buffer.
582     function! s:NextBuffer()
583         " Are we currently on the last buffer and moving to the first?
584         let l:last_buffer = 0
585         if bufnr('%') == bufnr('$') && bufnr('$') > 1
586             let l:last_buffer = 1
587         endif
588
589         " Go to the next buffer.
590         if !l:last_buffer
591             bnext
592
593         " Go to the first buffer, silent is necessary or the following message
594         " won't be displayed because it's overwritten by the status message
595         " displayed when entering a buffer.
596         else
597             silent bnext
598
599             echohl WarningMsg
600             echo 'Starting again at first buffer.'
601             echohl None
602         endif
603     endfunction
604     nnoremap <silent> gb :call <SID>NextBuffer()<CR>
605 endif
606
607 " Fast access to buffers.
608 nnoremap <silent> <Leader>1 :1buffer<CR>
609 nnoremap <silent> <Leader>2 :2buffer<CR>
610 nnoremap <silent> <Leader>3 :3buffer<CR>
611 nnoremap <silent> <Leader>4 :4buffer<CR>
612 nnoremap <silent> <Leader>5 :5buffer<CR>
613 nnoremap <silent> <Leader>6 :6buffer<CR>
614 nnoremap <silent> <Leader>7 :7buffer<CR>
615 nnoremap <silent> <Leader>8 :8buffer<CR>
616 nnoremap <silent> <Leader>9 :9buffer<CR>
617 nnoremap <silent> <Leader>0 :10buffer<CR>
618
619 " Use real tabs instead of soft tabs.
620 if has('eval')
621 " Switch from soft tabs to real tabs.
622     function! s:UseTabs()
623         setlocal noexpandtab shiftwidth=8 softtabstop=8
624     endfunction
625     nnoremap <silent> <Leader>t :call <SID>UseTabs()<CR>
626 endif
627 " Enable "verbatim" mode. Used to view files with long lines or without syntax
628 " coloring. 'list' is not changed, see next mapping.
629 nnoremap <silent> <Leader>v :setlocal nowrap nospell synmaxcol=0<CR>
630                           \ :2match<CR>
631 " Toggle 'list'.
632 nnoremap <silent> <Leader>l :set invlist<CR>
633
634 " Make last active window the only window. Similar to <C-W> o.
635 nnoremap <C-W>O <C-W>p<C-W>o
636
637 " Maps to change spell language between English and German and disable spell
638 " checking.
639 if exists('+spell')
640     nnoremap <silent> <Leader>sn :set nospell<CR>
641     nnoremap <silent> <Leader>se :set spell spelllang=en_us<CR>
642     nnoremap <silent> <Leader>sd :set spell spelllang=de_de<CR>
643 " If no spell support is available, these mappings do nothing.
644 else
645     nmap <Leader>sn <Nop>
646     nmap <Leader>se <Nop>
647     nmap <Leader>sd <Nop>
648 endif
649
650 if has('eval')
651 " * and # for selections in visual mode. Thanks to
652 " http://got-ravings.blogspot.com/2008/07/vim-pr0n-visual-search-mappings.html
653 " and all nerds involved (godlygeek, strull in #vim on Freenode).
654     function! s:VSetSearch()
655         let l:temp = @@ " unnamed register
656         normal! gvy
657         " Added \C to force 'noignorecase' while searching the current visual
658         " selection. I want to search for the exact string in this case.
659         let @/ = '\C' . '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')
660         let @@ = l:temp
661     endfunction
662     vnoremap * :<C-U>call <SID>VSetSearch()<CR>//<CR>
663     vnoremap # :<C-U>call <SID>VSetSearch()<CR>??<CR>
664
665 " Use 'noignorecase' for * and #. See comment in s:VSetSearch() for details.
666 " Thanks to the writers of s:VSetSearch(), see above.
667     function! s:NSetSearch()
668         let l:cword = expand('<cword>')
669         let l:regex = substitute(escape(l:cword, '\'), '\n', '\\n', 'g')
670         let @/ = '\C\V'. '\<' . l:regex . '\>'
671     endfunction
672     nnoremap * :call <SID>NSetSearch()<CR>//<CR>
673     nnoremap # :call <SID>NSetSearch()<CR>??<CR>
674 endif
675
676 " I often type "W" instead of "w" when trying to save a file. Fix my mistake.
677 " Thanks to Tony Mechelynck <antoine.mechelynck@gmail.com> from the Vim
678 " mailing list for the commands.
679 if v:version < 700
680     cnoreabbrev W w
681     cnoreabbrev Wa wa
682     cnoreabbrev Wq wq
683     cnoreabbrev Wqa wqa
684 else
685     cnoreabbrev <expr> W
686         \ ((getcmdtype() == ':' && getcmdpos() <= 2) ? 'w' : 'W')
687     cnoreabbrev <expr> Wa
688         \ ((getcmdtype() == ':' && getcmdpos() <= 3) ? 'wa' : 'Wa')
689     cnoreabbrev <expr> Wq
690         \ ((getcmdtype() == ':' && getcmdpos() <= 3) ? 'wq' : 'Wq')
691     cnoreabbrev <expr> Wqa
692         \ ((getcmdtype() == ':' && getcmdpos() <= 4) ? 'wqa' : 'Wqa')
693 endif
694 " Also fix my typo with "Q".
695 if v:version < 700
696     cnoreabbrev Q q
697     cnoreabbrev Qa qa
698 else
699     cnoreabbrev <expr> Q
700         \ ((getcmdtype() == ':' && getcmdpos() <= 2) ? 'q' : 'Q')
701     cnoreabbrev <expr> Qa
702         \ ((getcmdtype() == ':' && getcmdpos() <= 3) ? 'qa' : 'Qa')
703 endif
704
705 " In case 'hlsearch' is used disable it with <C-L>. Thanks to frogonwheels and
706 " vimgor (bot) in #vim on Freenode (2010-03-30 05:58 CEST).
707 nnoremap <silent> <C-L> :nohlsearch<CR><C-L>
708
709 " <C-U> in insert mode deletes a lot, break undo sequence before deleting the
710 " line so the change can be undone. Thanks to the vimrc_example.vim file in
711 " Vim's source.
712 inoremap <C-U> <C-G>u<C-U>
713 " Same for <C-@> (insert previously inserted text and leave insert mode).
714 inoremap <C-@> <C-G>u<C-@>
715 " And for <C-A> (insert previously inserted text).
716 inoremap <C-A> <C-G>u<C-A>
717 " And for <C-W> (delete word before cursor).
718 inoremap <C-W> <C-G>u<C-W>
719
720 if has('eval')
721 " New text-objects ii and ai to work on text with the same indentation. Thanks
722 " to http://vim.wikia.com/index.php?title=Indent_text_object&oldid=27126
723 " (visited on 2011-11-19).
724     onoremap <silent> ai :<C-U>call <SID>IndTxtObj(0)<CR>
725     onoremap <silent> ii :<C-U>call <SID>IndTxtObj(1)<CR>
726     vnoremap <silent> ai :<C-U>call <SID>IndTxtObj(0)<CR><Esc>gv
727     vnoremap <silent> ii :<C-U>call <SID>IndTxtObj(1)<CR><Esc>gv
728
729     function! s:IndTxtObj(inner)
730         let curline = line(".")
731         let lastline = line("$")
732         let i = indent(line(".")) - &shiftwidth * (v:count1 - 1)
733         let i = i < 0 ? 0 : i
734         if getline(".") !~ "^\\s*$"
735             let p = line(".") - 1
736             let nextblank = getline(p) =~ "^\\s*$"
737             while p > 0
738                     \ && ((i == 0 && !nextblank)
739                         \ || (i > 0 && ((indent(p) >= i
740                             \ && !(nextblank && a:inner))
741                             \ || (nextblank && !a:inner))))
742                 -
743                 let p = line(".") - 1
744                 let nextblank = getline(p) =~ "^\\s*$"
745             endwhile
746             normal! 0V
747             call cursor(curline, 0)
748             let p = line(".") + 1
749             let nextblank = getline(p) =~ "^\\s*$"
750             while p <= lastline
751                     \ && ((i == 0 && !nextblank)
752                         \ || (i > 0 && ((indent(p) >= i
753                             \ && !(nextblank && a:inner))
754                             \ || (nextblank && !a:inner))))
755                 +
756                 let p = line(".") + 1
757                 let nextblank = getline(p) =~ "^\\s*$"
758             endwhile
759             normal! $
760         endif
761     endfunction
762 endif
763
764
765 " ABBREVIATIONS
766
767 " Fix some of my spelling mistakes (German).
768 inoreabbrev relle reelle
769 inoreabbrev reele reelle
770 " Fix some of my spelling mistakes (English).
771 inoreabbrev completly completely
772
773
774 " SYNTAX SETTINGS
775
776 " Activate syntax coloring.
777 if has('syntax')
778     " But only if it wasn't already active. Prevents breaking the syntax
779     " coloring when reloading the vimrc. Thanks to johnLate for the idea.
780     if !exists('g:syntax_on')
781         syntax enable
782     endif
783
784 " Don't highlight more than 500 columns as I normally don't have that long
785 " lines and they slow down syntax coloring. Thanks to Derek Wyatt
786 " (http://www.derekwyatt.org/vim/the-vimrc-file/).
787     if exists('+synmaxcol')
788         set synmaxcol=500
789     endif
790
791 " Use (limited) syntax based omni completion if no other omni completion is
792 " available. Taken from :help ft-syntax-omni.
793     if has('autocmd') && exists('+omnifunc')
794         augroup vimrc
795             autocmd FileType *
796                 \ if &omnifunc == '' |
797                 \     setlocal omnifunc=syntaxcomplete#Complete |
798                 \ endif
799         augroup END
800     endif
801
802 " Function to enable all custom highlights. Necessary as highlights are
803 " window-local and thus must be set for each new window.
804     function! s:CustomSyntaxHighlights()
805         " Not the first time called, nothing to do.
806         if exists('w:vimrc_syntax_run')
807             return
808         endif
809         let w:vimrc_syntax_run = 1
810
811 " Highlight lines longer than 78 characters. Thanks to Tony Mechelynck
812 " <antoine.mechelynck@gmail.com> from the Vim mailing list. It can easily be
813 " disabled when necessary with :2match (in Vim >= 700).
814         if !&diff && exists(':2match')
815             " Use ColorColumn for overlong lines if available and my color
816             " scheme is used.
817             if &t_Co == 256 && s:HasSyntaxGroup('ColorColumn')
818                 2match ColorColumn /\%>78v./
819             else
820                 2match Todo /\%>78v./
821             endif
822         elseif !&diff
823             match Todo /\%>78v./
824         endif
825
826         if exists('*matchadd')
827 " Highlight some important keywords in all documents.
828             let l:todos = ['TODO', 'XXX', 'FIXME', 'NOTE',
829                          \ 'CHANGED', 'REMOVED', 'DELETED']
830             " Compatibility fix for Vim 6.4 which can't parse for in functions
831             " (without function it's ignored).
832             execute '  for l:x in l:todos'
833                   \ '|     call matchadd("Todo", l:x)'
834                   \ '| endfor'
835
836 " Highlight Unicode whitespace which is no normal whitespace (0x20).
837             let l:spaces = ['00a0', '1680', '180e', '2000', '2001', '2002',
838                           \ '2003', '2004', '2005', '2006', '2007', '2008',
839                           \ '2009', '200a', '200b', '200c', '200d', '202f',
840                           \ '205f', '2060', '3000', 'feff']
841             " Compatibility fix for Vim 6.4. Escape \ inside the " string or
842             " it won't work!
843             execute '  for l:x in l:spaces'
844                   \ '|     call matchadd("Error", "\\%u" . l:x)'
845                   \ '| endfor'
846
847 " Special highlight for tabs to reduce their visibility in contrast to other
848 " SpecialKey characters (e.g. ^L).
849             if &t_Co == 256 && s:HasSyntaxGroup('specialKeyTab')
850                 call matchadd('specialKeyTab', '\t')
851             endif
852         endif
853     endfunction
854 " Enable highlights for the current and all new windows. Thanks to bairui in
855 " #vim on Freenode (2012-04-01 00:22 CEST) for the WinEnter suggestion.
856     call s:CustomSyntaxHighlights()
857     if has('autocmd')
858         augroup vimrc
859             autocmd WinEnter * call s:CustomSyntaxHighlights()
860         augroup END
861     endif
862
863 " Settings for specific filetypes.
864
865     " C
866     let g:c_no_if0_fold = 1 " fix weird double fold in #if0 in recent versions
867     " Haskell
868     let g:hs_highlight_delimiters = 1
869     let g:hs_highlight_boolean = 1
870     let g:hs_highlight_types = 1
871     let g:hs_highlight_more_types = 1
872     " Java
873     let g:java_highlight_java_lang_ids = 1 " color java.lang.* identifiers
874     " Perl
875     let g:perl_fold = 1
876     let g:perl_fold_blocks = 1
877     let g:perl_nofold_packages = 1
878     let g:perl_include_pod = 1 " syntax coloring for PODs
879     " PHP
880     let g:php_folding = 3    " fold functions
881     let g:php_short_tags = 0 " no short tags (<? .. ?>), not always usable
882     let g:php_sql_query = 1  " highlight SQL queries in strings
883     " Python
884     let g:python_highlight_all = 1
885     " Shell
886     let g:sh_noisk = 1        " don't add . to 'iskeyword'
887     let g:sh_is_posix = 1     " POSIX shell (e.g. dash) is compatible enough
888     let g:sh_fold_enabled = 7 " functions (1), heredoc (2) and if/do/for (4)
889     " Vim
890     let g:vimsyn_embed = 0      " don't highlight embedded languages
891     let g:vimsyn_folding = 'af' " folding for autogroups (a) and functions (f)
892     " XML
893     let g:xml_syntax_folding = 1
894 endif
895
896
897 " PLUGIN SETTINGS
898
899 if has('eval')
900 " Use pathogen which allows one 'runtimepath' entry per plugin. This makes
901 " installing/removing/updating plugins simple. (Used for plugins with more
902 " than one file.) Ignore errors in case pathogen is not installed.
903     if v:version >= 700
904         silent! execute 'call pathogen#infect()'
905     endif
906
907 " Settings for securemodelines.
908     " Only allow items I need (also includes spl which is not enabled by
909     " default).
910     if v:version >= 700 " need lists
911         let g:secure_modelines_allowed_items = ['ft', 'spl', 'fdm',
912                                               \ 'sw', 'sts', 'noet']
913     endif
914
915 " Settings for the NERD commenter.
916     " Don't create any mappings I don't want to use.
917     let g:NERDCreateDefaultMappings = 0
918     " Map toggle comment.
919     nmap <Leader><Leader> <Plug>NERDCommenterToggle
920
921 " XPTemplate settings.
922     " Try to maintain snippet rendering even after editing outside of a
923     " snippet.
924     let g:xptemplate_strict = 0
925     " Don't complete any braces automatically.
926     let g:xptemplate_brace_complete = 0
927     " Only highlight the current placeholder.
928     let g:xptemplate_highlight = 'current'
929
930 " CtrlP settings.
931     " Don't manage the working directory (the default setting is too slow for
932     " me).
933     let g:ctrlp_working_path_mode = 0
934
935     " Path to cache directory. I prefer to keep generated files as local as
936     " possible.
937     let g:ctrlp_cache_dir = $HOME . '/.vim/cache/ctrlp'
938     " Permanent cache, cleared by a crontab entry. Use <F5> to update the
939     " cache manually.
940     let g:ctrlp_clear_cache_on_exit = 0
941
942     " Don't switch the window if the selected buffer is already open. I want
943     " to open another view on this buffer in most cases.
944     let g:ctrlp_switch_buffer = 0
945
946 " FSWitch settings.
947     " Defaults don't work well for my projects.
948     augroup vimrc
949         autocmd BufEnter *.cc let b:fswitchdst  = 'h'
950                           \ | let b:fswitchlocs = './'
951         autocmd BufEnter *.h  let b:fswitchdst  = 'cc,c'
952                           \ | let b:fswitchlocs = './'
953     augroup END
954
955     " Switch to corresponding header/source file.
956     nnoremap <silent> <Leader>h :FSHere<CR>
957
958 " netrw settings.
959     " Don't create ~/.vim/.netrwhist history file.
960     let g:netrw_dirhistmax = 0
961 endif
962
963
964 " AUTO COMMANDS
965
966 " Use a custom auto group to prevent problems when the vimrc files is sourced
967 " multiple times.
968 if has('autocmd')
969     augroup vimrc
970
971 " Go to last position of opened files. Taken from :help last-position-jump.
972         autocmd BufReadPost *
973             \ if line("'\"") > 1 && line("'\"") <= line('$') |
974             \     execute "normal! g'\"" |
975             \ endif
976 " But not for Git commits, go to beginning of the file.
977         autocmd BufReadPost COMMIT_EDITMSG normal! gg
978
979 " Make sure 'list' and 'number' is disabled in help files. This is necessary
980 " when switching to a help buffer which is in the background with :buffer as
981 " these options are local to windows (and not only to buffers). This happens
982 " because I often want to use only one window and thus the help buffer is in
983 " the background.
984         autocmd BufWinEnter *.txt
985             \ if &filetype == 'help' |
986             \     setlocal nolist |
987             \     setlocal nonumber |
988             \ endif
989
990 " Automatically disable 'paste' mode when leaving insert mode. Thanks to
991 " Raimondi in #vim on Freenode (2010-08-14 23:01 CEST). Very useful as I only
992 " want to paste once and then 'paste' gets automatically unset. InsertLeave
993 " doesn't exist in older Vims. Use "*p to paste X11's selection, no need for
994 " 'paste' in this case.
995         if exists('##InsertLeave')
996             autocmd InsertLeave * set nopaste
997         endif
998
999 " Write all files when running :mak[e] before 'makeprg' is called.
1000 " QuickFixCmdPre doesn't exist in older Vims.
1001         if exists('##QuickFixCmdPre')
1002             autocmd QuickFixCmdPre * wall
1003         endif
1004
1005 " Don't ignore case while in insert mode, but ignore case in all other modes.
1006 " This causes <C-N>/<C-P> to honor the case and thus only complete matching
1007 " capitalization. But while searching (/) 'ignorecase' is used.
1008 " InsertEnter/InsertLeave doesn't exist in older Vims.
1009         if exists('##InsertEnter') && exists('##InsertLeave')
1010             autocmd InsertEnter * set noignorecase
1011             autocmd InsertLeave * set   ignorecase
1012         endif
1013
1014 " Display a warning when editing a file which contains "do not edit" (ignoring
1015 " the case) and similar messages in the first lines of the file, for example
1016 " template files which were preprocessed or auto-generated files. Especially
1017 " useful when the header is not displayed on the first screen, e.g. when the
1018 " old position is restored.
1019         function! s:SearchForDoNotEditHeader()
1020             " Only search the first 20 lines to prevent false positives, e.g.
1021             " in scripts which write files containing this warning and ignore
1022             " the case (\c). (Can't use search()'s {stopline} as we might not
1023             " start searching from the top.)
1024             let l:search = '\c\(do not \(edit\|modify\)\|autogenerated by\)'
1025             let l:match = search(l:search, 'n')
1026             if l:match == 0 || l:match > 20
1027                 return
1028             endif
1029
1030             echoerr 'Do not edit this file! (Maybe a template file.)'
1031         endfunction
1032         autocmd BufRead * call s:SearchForDoNotEditHeader()
1033
1034 " AFTER/FTPLUGIN AUTO COMMANDS
1035
1036 " Disable spell checking for files which don't need it.
1037         autocmd FileType deb  setlocal nospell
1038         autocmd FileType diff setlocal nospell
1039         autocmd FileType tar  setlocal nospell
1040 " Fix to allow Vim edit crontab files as crontab doesn't work with
1041 " backupcopy=auto.
1042         autocmd FileType crontab setlocal backupcopy=yes
1043 " Don't use the modeline in git commits as the diff created by `git commit -v`
1044 " may contain one which could change the filetype or other settings of the
1045 " commit buffer. Also make sure we use only 72 characters per line which is
1046 " the recommendation for git commit messages (http://tpope.net/node/106).
1047         autocmd FileType gitcommit let g:secure_modelines_allowed_items = [] |
1048                                  \ setlocal textwidth=72
1049 " Fix 'include' setting for shell files to recognize '.' and 'source'
1050 " commands.
1051         autocmd FileType sh let &l:include = '^\s*\(\.\|source\)\s\+'
1052 " Use the same comment string as for Vim files in Vimperator files.
1053         autocmd FileType vimperator setlocal commentstring=\"%s
1054 " Use TeX compiler for (La)TeX files.
1055         autocmd FileType tex compiler tex
1056
1057 " FTDETECT AUTO COMMANDS
1058
1059 " Recognize .md as markdown files (Vim default is .mkd).
1060         autocmd BufRead,BufNewFile *.md set filetype=mkd
1061 " Recognize .test as Tcl files.
1062         autocmd BufRead,BufNewFile *.test set filetype=tcl
1063
1064 " OTHER AUTO COMMANDS
1065
1066 " Disable spell checking, displaying of list characters and long lines when
1067 " viewing documentation.
1068         autocmd BufReadPost /usr/share/doc/* setlocal nospell nolist | 2match
1069
1070 " Use diff filetype for mercurial patches in patch queue.
1071         autocmd BufReadPost */.hg/patches/* set filetype=diff
1072
1073     augroup END
1074 endif
1075
1076
1077 " CUSTOM FUNCTIONS AND COMMANDS
1078
1079 if has('eval')
1080 " Convenient command to see the difference between the current buffer and the
1081 " file it was loaded from, thus the changes you made. Thanks to the
1082 " vimrc_example.vim file in Vim's source. Modified to use the same filetype
1083 " for the diffed file as the filetype for the original file.
1084     if !exists(':DiffOrig')
1085         command DiffOrig
1086             \ let s:diff_orig_filetype = &filetype
1087             \ | vertical new
1088             \ | let &filetype = s:diff_orig_filetype
1089             \ | unlet s:diff_orig_filetype
1090             \ | set buftype=nofile
1091             \ | read ++edit #
1092             \ | 0d_
1093             \ | diffthis
1094             \ | wincmd p
1095             \ | diffthis
1096     endif
1097 endif