Wikia

Vim Tips Wiki

Tonymec/vimrc

Talk0
1,610pages on
this wiki

< User:Tonymec

Revision as of 20:59, August 8, 2009 by Tonymec (Talk | contribs)

I'm quoting my own vimrc below. It includes some stuff that, IMHO, every sane Vim setup should have, and other stuff which I like but maybe you won't. If you have comments, add them at the bottom of this page, in line with what is done on other pages of this wiki; don't use the talk page to discuss this vimrc.

The code

" use 'nocompatible' mode even if sourced with -u
set nocompatible

" this script is in Latin1 even when 'encoding' is UTF-8
scriptencoding latin1

" remember where I keep my sources:
" this means the parent of src/ runtime/ etc.
let $VIMSRC = '/root/.build/vim/vim72'

" I think the following two were fixed by patches 6.0.064 and 7.1b.002 (or some such)
" I leave them in in case I happened to run an unfixed Vim
" I don't think they can hurt
if &mm < 256
	set mm=20000000
endif
if &mmt < 256
	set mmt=20000000
endif

" set menus & messages to English even on a multilingual Vim run on a non-English locale
if has("multi_lang")
	if has("unix")
		language messages C
	else
		language messages en
	endif
	language time en_GB
endif

if 1	" expression evaluation compiled-in
	runtime! menu.vim
endif

" use 256 colors in Console mode if we think the terminal supports it
if &term =~? 'mlterm\|xterm'
	let &t_Co = 256
endif

" the example vimrc sets a lot of useful settings
runtime vimrc_example.vim
" ... and a few that we don't want
unmap! <C-U>
" the example vimrc doesn't set syntax highlighting on mono terminals --
" let's correct that
if has('syntax') && !(exists('syntax_on') && syntax_on)
	syntax on
endif

" set my own color scheme
if has('autocmd') && has('syntax')
	color almost-default
	let my_colors_name = "almost-default"
endif

" (try to) detect whether we have clipboard and X
if has('gui_running')
	function TestForX()
		return 1
	endfunction
elseif has('clipboard')
	function TestForX()
		let @+ = " "
		let x = @+
		let @+ = '--' . x
		redir @"
		silent reg
		redir END
		let @+ = x
	"	unlet x
		return (@" =~ '\n"+ ')
	endfunction
else
	function TestForX()
		return 0
	endfunction
endif


if has("autocmd")
	" remove the 'textwidth' setting set by vimrc_example.vim on text files
	au! vimrcEx FileType text

	" define a few additional autocommands
	augroup vimrclocal

	" complete the try-to-detect-Xwindows started earlier
	au VimEnter *
		\   let clipboard_present = TestForX()
		\ | let X_available = has('x11') && clipboard_present

	" this one is unnecessary on recent Vim versions
	au FileType *.* exe substitute(expand('<amatch>'), '^\(.*\)\.\(.*\)$', 'doau Filetype \1 | doau Filetype \2', '')

	" remove filetype-indenting autocommands set by the vimrc_example.vim
	filetype indent off

	" set verbosity to at least 1, except during startup and closedown
	if ! &verbose
		au vimEnter * set verbose=1
		au vimLeave * set verbose=0
	endif

	" close all cscope connections (if any) at closedown
	if has('cscope')
		au vimLeave * cs kill -1
	endif

	" use matchit correctly on C (etc.) sources
	au Filetype c,cpp,css,javascript
	\ let b:match_words = &matchpairs

	" this was fixed by patch 7.1.261 but doesn't hurt,
	" and will make Vim open UTF-16 files with BOM correctly even without that patch
	if has('multi_byte')
		au BufReadPost * if (&fenc == 'ucs-2le') && &bomb | e ++enc=utf-16le | endif
		au BufReadPost * if (&fenc == 'ucs-2')   && &bomb | e ++enc=utf-16   | endif
	endif
endif

if has("gui_running")
	" set the GUI font, using the correct format for the build we're on
	if has("gui_gtk2")
		set gfn=Bitstream\ Vera\ Sans\ Mono\ 8
		let s:pfn = 'Bitstream\ Vera Sans Mono'
	"	set gfn=Monaco\ 7
	"	let s:pfn='Monaco'
	elseif has("gui_photon")
		set gfn=Bitstream\ Vera\ Sans\ Mono:s8
		let s:pfn = 'Bitstream\ Vera Sans Mono'
	"	set gfn=Monaco=s7
	"	let s:pfn='Monaco'
	elseif has("gui_kde")
		set gfn=Bitstream\ Vera\ Sans\ Mono/8/-1/5/50/0/0/0/1/0
		let s:pfn = 'Bitstream\ Vera Sans Mono'
	"	set gfn=Monaco/7/-1/5/50/0/0/0/1/0
	"	let s:pfn='Monaco'
	elseif has("x11")
		set gfn=-*-lucidatypewriter-medium-r-normal-*-*-90-*-*-m-*-*
		let s:pfn = 'Lucida'
	else
		set gfn=Lucida_Console:h9:cDEFAULT
		let s:pfn = 'Lucida Console'
	endif

	" set GUI cursor shape
	set guicursor=n-v-c:block-Cursor/lCursor,ve:ver35-Cursor,o:hor50-Cursor
	set guicursor+=i-ci:ver25-Cursor/lCursor,r-cr:hor20-Cursor/lCursor
	set guicursor+=sm:block-Cursor,a:blinkwait750-blinkoff750-blinkon750

	" maximize the Vim GUI
	set lines=99999 columns=99999

	set keywordprg=MANPAGER=more\ man\ -a\  " command to be used for the K command
else
	" print font for Console mode
	let s:pfn = 'Courier'

	if (&term == "pcterm") || (&term == "win32")
		" if exists("+guicursor")
		" Console cursor shape (Windows only)
		set guicursor=n-v-c:block,o:hor50,i-ci:hor15,r-cr:hor30
		set guicursor+=sm:block,a:blinkwait750-blinkoff750-blinkon750

	elseif &term == "linux"
		" don't try running CSApprox on Linux text-only console
		let g:CSApprox_loaded = 1

		" avoid some line-depth screwups
		if &lines > 47
			set lines=47
		endif

	elseif &term == "mlterm"	" the true-bidi terminal
		let &t_kb = "\x7F"	" termcap patch for mlterm backspace key
	endif

	" some more Console-mode-only settings
	set keywordprg=man
	set title titleold= titlestring=%t\ -\ VIM
	" change cursor color for Insert (commented out, doesn't work for me)
	if &term == 'xterm' && 0
		let &t_SI = "\e]12;CursorShape=1\x07"
		let &t_EI = "\e]50;CursorShape=0\x07"
	endif
endif	" has("gui_running") ... else ...

" override previous 'keywordprg' settings if not on Unix
if !has('unix')
	set keywordprg=:help
endif

" printer settings
if has("printer")
	set popt=duplex:off,formfeed:y
	let &pfn = s:pfn
endif

" switch to UTF-8 if possible (and not already done by the OS)
if has("multi_byte")
	let g:locale_encoding = &encoding
	if &encoding !~? '^u'		" ... if not already Unicode ...
		if &termencoding == ""
			let &termencoding = &encoding
		endif
		set encoding=utf-8
	endif
	set fileencodings=ucs-bom,utf-8,latin1
	setg bomb fileencoding=utf-8
"	if has("printer")
"		set penc=utf-8
"	endif
endif

" additional options
set autowriteall			" save (if possible) when |abandon|ing a file
set backup				" back up old versions
if has('writebackup')			" but only if not equipped with the more advanced 'writebackup'
	set nobackup writebackup
endif

" indent settings (we do NOT want filetype-related indent)
set autoindent
if has('smartindent')
	set smartindent
endif

set errorbells visualbell			" use both audio and visual bell
if 1			" has arithmetic evaluation
	let &t_vb = "\x07" . &t_vb		" 07 is the BEL character, rings the terminal bell
endif
if has('autocmd') && has('gui')
	" must set it again for the GUI
	au GUIEnter * let &t_vb = "\<C-G>\e|50f"
	" where 50 is the flash time in milliseconds
endif

if exists("+modelines")
	" the following is required because of SuSE's paranoid /etc/vimrc
	" and to force 'modeline' on even for root in Vim 7.0.237 and later
	set modeline modelines=5
	" the following disables a dangerous modeline in one helpfile
	if has ('autocmd')
		au BufReadPost ada.txt setl nomodeline ft=help
	endif
endif

set report=0		" report # of :substitute changes even if only one
set nojoinspaces	" don't use double spaces (e.g. after periods) when joining
set selection=inclusive keymodel=startsel selectmode=key	" :behave tonymec	;-)
set laststatus=2	" always display bottom status line
set display=lastline	" if the last line (with 'wrap') overshoots the window bottom,
			" display as much of it as possible
set timeout timeoutlen=5000 ttimeoutlen=100	" timeouts: 0.1s on keycodes, 5s on mappings
set scrolloff=3		" display at least 3 lines of context above & below cursor if possible
set nrformats=		" have ^A and ^X increment/decrement only in decimal
set formatoptions-=c	" autowrap comments using textwidth
set tags=tags,./tags	" ignore emacs-style tagfiles by default

" set 'list' and 'listchars' options
set list listchars=eol:$		" $ should work on all 8-byte encodings
if has('multi_byte')
	set listchars=eol:¶		" on multibyte Vim (where 'encoding' is UTF-8)
					" we can use the prettier Pilcrow mark
endif
set listchars+=tab:\|_			" show tabs as |_______|_______
silent! set listchars+=nbsp:~		" show no-break space as tilde if supported
" silent! set listchars+=precedes:<,extends:>

set ignorecase smartcase	" ignore case when search text is all-lowercase

" case adjust in Insert completion
if exists("+infercase")
	set infercase
endif

" add atsign to 'isfname' characters
set isfname+=@-@

" path search settings
if has('file_in_path')
	set path=.,,
	if has('path_extra')
		set path^=$HOME/**
	else
		set path^=$HOME
	endif
endif

set whichwrap=<,>,[,],~,s	" allow line-wrapping on <Left> <Right> <Space> and tilde

if has("mouse")
	set mouse=a mousemodel=popup selectmode+=mouse
endif

if exists("+cursorcolumn")
	set cuc cul
endif

if has("diff")
	set diffopt+=context:0
endif

if exists("+imsearch")
	setg ims=-1	" set 'imsearch' to mimic 'iminsert' by default
endif

" set up Rolodex Vim
if has("windows")
    if has("autocmd")
      augroup rolodex
	au VimEnter * set noea wmh=0 wh=99999 hh=99999 cwh=99999
      augroup vimrclocal
    else
	set noea wmh=0 wh=99999 hh=99999 cwh=99999
    endif
endif

" display up to 4 combining chars merged with a given spacing char
if exists("+maxcombine")
	set mco=4
endif

" allow removing combining chars one-by-one
if exists("+delcombine")
	set deco
endif

" set 'wildmenu' option, to get completion-by-menu (on the status line when hitting Tab)
if has("wildmenu")
	set wildmenu wildmode=longest:full,full
else
	set wildmode=longest,list:longest,full
endif

if has("wildignore")
	set wildoptions=tagfile		" display tag kind if possible
endif

if exists("+clipboard")
	set clipboard=exclude:cons\\\|linux
	if has('multi_byte') && has('gui_gtk2') && (((version == 702) && has('patch201')) || (version > 702))
		set clipboard^=html
	endif
endif

if has('cscope')
	set cst csverb 
	if has('quickfix')
		set csqf=s-,c-,d-,i-,t-,e-
	endif
	if version < 700
		cnoreabbrev csf cs find
		cnoreabbrev csk cs kill
		cnoreabbrev css cs show
		cnoreabbrev csh cs help
	else
		cnoreabbrev <expr> csa ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs add'  : 'csa')
		cnoreabbrev <expr> csf ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs find' : 'csf')
		cnoreabbrev <expr> csk ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs kill' : 'csk')
		cnoreabbrev <expr> css ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs show' : 'css')
		cnoreabbrev <expr> csh ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs help' : 'csh')
	endif
endif

if exists("+guioptions")
	set go-=a go-=e go+=tc
	" remove a	no autoselect to * register
	" remove e	always use text-style tabs
	" add    t	include tearoff menu items if possible
	" add    c	avoid popup dialogs for small choices
endif

if exists("+guiheadroom")
	set ghr=0
endif

" define out text-style tabline
" this is adapted (with some enhancements) from the example at :help setting-tabline
if exists("+showtabline")
	function MyTabLine()
		let s = ''
		let t = tabpagenr()
		let i = 1
		while i <= tabpagenr('$')
			let buflist = tabpagebuflist(i)
			let winnr = tabpagewinnr(i)
			let s .= '%' . i . 'T'
			let s .= (i == t ? '%1*' : '%2*')
			let s .= ' '
			let s .= i . ':'
			let s .= winnr . '/' . tabpagewinnr(i,'$')
			let s .= ' %*'
			let s .= (i == t ? '%#TabLineSel#' : '%#TabLine#')
			let file = bufname(buflist[winnr - 1])
			let file = fnamemodify(file, ':p:t')
			if file == ''
				let file = '[No Name]'
			endif
			let s .= file
			let i = i + 1
		endwhile
		let s .= '%T%#TabLineFill#%='
		let s .= (tabpagenr('$') > 1 ? '%999XX' : 'X')
		return s
	endfunction
	set stal=2
	set tabline=%!MyTabLine()
"	map	<F10>	:tabnext<CR>
"	map!	<F10>	<C-O>:tabnext<CR>
"	map	<S-F10>	:tabprev<CR>
"	map!	<S-F10>	<C-O>:tabprev<CR>
endif

" when splitting, put new window after current by default
if exists("+splitbelow")
	set splitbelow
endif
if exists("+splitright")
	set splitright
endif

" avoid too-frequent "more?" prompts
if &cmdheight < 2
	set cmdheight=2
endif

" custom status line, see :help 'statusline' for details
if has("statusline")
	set statusline=%<%f\ %h%m%r%=%k[%{(&fenc\ ==\ \"\"?&enc:&fenc).(&bomb?\",BOM\":\"\")}][U+%04B]\ %-12.(%l,%c%V%)\ %P
endif

" session options
if has('mksession')
	set ssop-=curdir ssop+=sesdir,globals,localoptions
endif

" highlight syntax all the way, even on very long lines
if exists("+synmaxcol")
	set synmaxcol=0
endif

if exists("+completeopt")
	set completeopt=menuone,preview
endif

" history and viminfo options
set history=200
if has('viminfo')
	set vi-=h vi+=!,%
	if has("unix")
		set vi+=r/media/dvdrecorder,r/mnt/floppy
	else
		set vi+=ra:,rb:
	endif
endif

if 1			" only if has arithmetic evaluation
	" netrw settings
	let netrw_alto		= 1
	let netrw_altv		= 1
	let netrw_liststyle	= 1
	" let netrw_keepdir	= 0
	let netrw_longlist	= 1
	let netrw_mousemaps	= 0
	let netrw_noretmap	= 1	" disable going back by double clicking
	let netrw_timefmt	= '%a %d %b %Y %T'

	" syntax settings for shell syntax
	let is_bash		= 1 " our 'sh' Bourne shell is alias to bash
	let sh_fold_enabled	= 7 " enable all kinds of syntax folding
endif

" Mappings and abbreviations

" make Ctrl-arrows move by words not WORDS
" (like they already do in Insert mode).
map	<C-Left>	b
map	<C-Right>	w

if exists('+iminsert')
	" map F8 to toggle keymap (Ctrl-^ not present on keyboard)
	noremap  <F8> :let &l:iminsert = ! &l:iminsert<CR>
	lnoremap <F8> <C-O>:let &l:iminsert = ! &l:iminsert<CR>
	noremap! <F8> <C-O>:let &l:iminsert = ! &l:iminsert<CR>
	cnoremap <F8> <C-^>
endif

" unmap ZZ (exit). We have :qa anyway.
map ZZ <Nop>

set wildcharm=<C-T>		" or any key not needed in Command-line mode
if has('menu')
	" override Ctrl-Z (minimize) by a text-mode menu
	map <C-Z> :emenu <C-T>
	imap <C-Z> <C-O>:emenu <C-T>
endif
" F9		follow help link
map	<F9>	<C-]>
" F9		terminate abbreviation
map!	<F9>	<C-]>
" F11		go to next window
" Shift-F11	go to previous window
" (with count) F11 or Shift-F11 both go to nth window
map	<F11>	<C-W>w
map!	<F11>	<C-O><C-W>w
map	<S-F11>	<C-W>W
map!	<S-F11>	<C-O><C-W>W
" move current window up and down
noremap	<C-W>X	<C-W>W<C-W>x
noremap	<C-W>x	<C-W>x<C-W>w
" F2		go to next quickfix line
" Shift-F2	go to previous quickfix line
map	<F2>	:cnext<CR>zv
map	<S-F2>	:cprev<CR>zv
" F4		paste clipboard after last line
" Shift-F4	paste clipboard before 1st line
" omitted if clipboard is inaccessible or not compiled-in
if has('autocmd')
	au VimEnter *
		\ if clipboard_present
			\ | exe 'map	<F4>	:$put +<CR>'
			\ | exe 'map	<S-F4>	:0put +<CR>'
			\ | exe 'imap	<F4>	<C-O>:$put +<CR>'
			\ | exe 'imap	<S-F4>	<C-O>:0put +<CR>'
		\ | endif
endif
" F3		save our work
map	<F3>	:wa<Bar>wv<CR>
imap	<F3>	<C-O>:wa<Bar>wv<CR>
map	<S-F3>	8<Bar>v/\.<CR>hy/\/<C-R>"\.<CR>
imap	<S-F3>	<Esc>8<Bar>v/\.<CR>hy/\/<C-R>"<CR>a
if 1
	function Fortune()
		" In order to remember them in the viminfo,
		" the first two variables defined below
		" must have names starting with an uppercase letter
		" and containing no lowercase letters.
		if !exists("g:FORTUNE")
			let g:FORTUNE = 0
		endif
		if !exists("g:FORTUNECYCLE")
			let g:FORTUNECYCLE = 5
		endif
		if !exists("s:sysFortunes")
			let s:sysFortunes =
			\ (system("which fortune") != "") && (!v:shell_error)
		endif
		if !exists("s:bramFortunes")
			let s:bramFortunes =
			\ filereadable(expand("~/fortunes.txt"))
		endif
		if s:sysFortunes && (g:FORTUNE || (!s:bramFortunes))
			let @+ = "-- \n" . system("fortune -a")
		elseif s:bramFortunes
			new ~/fortunes.txt
			silent 1;/^-- $/-1d +
			$put +
			wq
		else
			let @+ = ""
		endif
		let g:FORTUNE = g:FORTUNE + 1
		if g:FORTUNE >= g:FORTUNECYCLE
			let g:FORTUNE = 0
		endif
		return @+
	endfunction
map <F5> :echo Fortune()<CR>
endif
"
" Up, Down	move up/down by "screen lines"
" j k 		(default) move down/up by "file lines"
map	<Down>	gj
map	<Up>	gk
" if exists("*pumvisible")
"	inoremap <expr>	<Down>	pumvisible() ? "\<lt>Down>" : "\<lt>C-O>gj"
"	inoremap <expr>	<Up>	pumvisible() ? "\<lt>Up>"   : "\<lt>C-O>gk"
" else
"	inoremap	<Down>	<C-O>gj
"	inoremap	<Up>	<C-O>gk
"endif

" scroll mouse by single lines
if has('mouse')
	noremap		<MouseUp>	<C-E>
	inoremap	<MouseUp>	<C-O><C-E>
	noremap		<MouseDown>	<C-Y>
	inoremap	<MouseDown>	<C-O><C-Y>
endif

" make left-arrow work over indent/eol/start
noremap	<Left>	<BS>
" open help window at bottom unless :help typed in full
if version < 700
	cnoreabbrev	h	bot h
else
	cnoreabbrev	<expr>	h	((getcmdtype() == ':' && getcmdpos() <= 2)? 'bot h' : 'h')
endif
map	<F1>	:bot help<CR>
" map Ctrl-L to invoke :diffupdate when in diff mode (disabled)
" if has("diff")
" 	map	<C-L>	:if &diff <Bar> diffu <Bar> else <Bar> redraw <Bar> endif <CR>
" 	imap	<C-L>	<C-O>:if &diff <Bar> diffu <Bar> else <Bar> redraw <Bar> endif <CR>
" endif

" Ctrl-K comma colon (in Insert mode): UTF-8 single-codepoint ellipsis "..."
" disregard error if (for instance) not in UTF-8
if has("digraphs")
	silent!	dig	,:	8230		" HORIZONTAL ELLIPSIS
endif

if has('insert_expand')
	" mappings for «ordinary» Insert-mode completion
	inoremap	<F12>		<C-X><C-N>
	inoremap	<S-F12>		<C-X><C-P>
	" mapping for Omni completion
	inoremap	<F6>		<C-X><C-O>
endif

" repeat latest substitute
map	µ	:&&<CR>
" find non-UTF8 in 8-bit files
map	£	8g8

" the following are to force-break autocomplete on these keys
inoremap	<C-Y>	<Space><BS><C-Y>
inoremap	<C-E>	<Space><BS><C-E>
" Add some undo points in Insert mode
if (version > 602) || ((version == 602) && has("patch148"))	" <C-G>u sets undo point
	inoremap	<CR>	<C-G>u<CR>
else
	inoremap	<CR>	<C-O>o
endif
inoremap	<Space>		<Space><Left><Right>

if has("user_commands")
	command -nargs=0 -bar WhatSyntax echomsg synIDattr(synID(line("."),col("."),0),"name") synIDattr(synIDtrans(synID(line("."),col("."),0)),"name") synIDattr(synID(line("."),col("."),1),"name") synIDattr(synIDtrans(synID(line("."),col("."),1)),"name")
	command -nargs=0 -bar -bang -range -reg Put exe ((<q-bang> == '!') ? <q-line1> : <q-line2>) . 'put' . <q-bang> <q-reg>
	command -nargs=* -bar -bang -range Iline <line1>,<line2>Put<bang> =<q-args>
endif

if has('autocmd')
	augroup END
endif

if 1
  finish
endif
" the following is only for Vim versions without expression evaluation
runtime! plugin/zzsplash.vim

See also

The above references other scripts, some of which I've written myself; I'm linking them here for completeness:

You might also be interested in:

Comments

If you have comments or questions about the above vimrc, please add them below. I'd prefer it if you sign your contributions with ~~~~ and if successive unrelated comments are separated by ----. I'll "give the good example" by signing and separating this header: Tonymec 13:49, 3 August 2009 (UTC)


Around Wikia's network

Random Wiki