Difference between revisions of "Vimrc"

From ArchWiki
Jump to navigation Jump to search
(stub category removed)
Line 1: Line 1:
[[Category:Dotfiles (English)]]
[[Category:Dotfiles (English)]]

Revision as of 15:21, 22 February 2012

Merge-arrows-2.pngThis article or section is a candidate for merging with Vim.Merge-arrows-2.png

Notes: please use the second argument of the template to provide more detailed indications. (Discuss in Talk:Vimrc#)

I've only just the past couple years started understanding why it was key to learn vim, in the past I never had the patience for it and preferred nano-like editors. Now vim is all I use when on linux.

Note: Not sure what this would look like in a gui, I never ever use a gui, this is all 100% for console/terminal/pty/tty/ssh/putty/telnet users. I install this as /etc/vimrc if I can, then for each user they have ~/.vimrc containing 1 line source /etc/vimrc which works great. Also, because I am always on so many different systems, I do not use any plugins other than those built into the installation, which I compile myself. I'm still very new for the most part to vim, but I've had success with this vimrc logic. It works on all types of consoles, and depending on the TERM environment variable (and whether it has the right term capabilities) it will load 256 color support or not. Usually on a new system I just scp this right over and it works without any modifications. But an ongoing Work in progress.

"# Updated: Fri Oct  8 09:27:13 2010
" vim: set ft=vim foldlevel=2 commentstring"%s

" help holy-grail, all, termcap
" :verbose opt? - show where opt was set
" opt!		- invert
" invopt		- invert
" opt&		- reset to default
" all&		- set all to def
" '.	- last modification in file!

" tc	- create a new tab
" td	- close a tab
" tn	- next tab
" tp	- previous tab

" gf  - open file under cursor
" guu - lowercase line
" gUU - uppercase line

" =   - reindent text

" F 	- create a fold from matching parenthesis
" fm	- (zm)  more folds
" fl  - (zr) less/reduce folds
" fo	- open all folds (zR)
" fc	- close all folds (zM)
" ff  -  (zf)	- create a fold
" fd	- (zd)	- delete fold at cursor
" zF	- create a fold N lines
" zi	- invert foldenable

" CTRL-I - forward trace of changes
" CTRL-O - backward trace of changes!

" !!date - insert date
" :%!sort -u  - only show uniq (and sort)

" C-W W	 - Switch to other split window
" CTRL-N		  - Find keyword for word in front of cursor
" CTRL-P		  - Find PREV diddo

" ---------------------------------
" %s/\s\+$//    - delete trailing whitespace
" :s/a\|b/xxx\0xxx/g             modifies a b      to xxxaxxxbxxx
" :s/\([abc]\)\([efg]\)/\2\1/g   modifies af fa bg to fa fa gb
" :s/abcde/abc^Mde/              modifies abcde    to abc, de (two lines)
" :s/$/\^M/                      modifies abcde    to abcde^M
" :s/\w\+/\u\0/g                 modifies bla bla  to Bla Bla

"  COMMANDS "{{{4
" ---------------------------------
" :v/./.,/./-1join  - join empty lines
" :e! return to unmodified file
" :tabm n  - move tab to pos n
" :jumps
" :history
" :reg   -  list registers
" :so $VIMRUNTIME/syntax/hitest.vim	  " view highlight options
" delete empty lines
" global /^ *$/ delete

" HELP HELP "{{{4
" ---------------------------------"
"  :help user-toc.txt          Table of contents of the User Manual. >
"  :help :subject              Ex-command "subject", for instance the following: >
"  :help :help                 Help on getting help. >
"  :help CTRL-B                Control key <C-B> in Normal mode. >
"  :help 'subject'             Option 'subject'. >
"  :help EventName             Autocommand event "EventName"
"  :help pattern<Tab>          Find a help tag starting with "pattern".  Repeat <Tab> for others. >
"  :help pattern<Ctrl-D>       See all possible help tag matches "pattern" at once. >
"  :helpgrep pattern           Search the whole text of all help files for pattern "pattern". Jumps to the first match.  Jump to other matches with: >
"		:cn                         next match >
"		:cprev, :cN                 previous match >
"		:cfirst, :clast             first or last match >
"		:copen,  :cclose            open/close the quickfix window; press <Enter> to jump to the item under the cursor

" :runtime! plugin/**/*.vim  - load plugins
" :so $VIMRUNTIME/syntax/hitest.vim
" :so $VIMRUNTIME/syntax/colortest.vim
"f &term =~ "xterm"| f has("terminfo")set t_Co=8 t_Sf=<Esc>[3%p1%dm t_Sb=<Esc>[4%p1%dm  els  set t_Co=8 t_Sf=<Esc>[3%dm t_Sb=<Esc>[4%dm
"set t_AB=<Esc>[%?%p1%{8}%<%t25;%p1%{40}%+%e5;%p1%{32}%+%;%dm t_AF=<Esc>[%?%p1%{8}%<%t22;%p1%{30}%+%e1;%p1%{22}%+%;%dm

" ===========================================================================================================================================================================
if !exists("MyLoaded")
   let MyLoaded=1

   " function ToggleMaxWins "{{{2
   function! ToggleMaxWins()
	  if exists('g:windowMax')
		 au! maxCurrWin
		 exe "normal \<c-w>="
		 unlet g:windowMax
		 augroup maxCurrWin
			" au BufEnter * exe "normal \<c-w>_\<c-w>\<Bar>"
		" only max it vertically
			au! WinEnter * exe "normal \<c-w>_"
		 augroup END
		 do maxCurrWin WinEnter
		 let g:windowMax=1

   " function StripTrailingWhitespace "{{{2
   " automatically remove trailing whitespace before write
   function! StripTrailingWhitespace()
	  normal mZ
	  if line("'Z") != line(".")
		 echo "Stripped whitespace\n"
	  normal `Z

   " function ShowWhitespace() "{{{2
   " Highlight whitespace problems. "{{{4
   " flags is '' to clear highlighting, or is a string to
   " specify what to highlight (one or more characters):
   "   e  whitespace at end of line
   "   i  spaces used for indenting
   "   s  spaces before a tab
   "   t  tabs not at start of line "}}}4
   function! ShowWhitespace(flags)
	  let bad = ''
	  let pat = []
	  for c in split(a:flags, '\zs')
		 if c == 'e'
			call add(pat, '\s\+$')
		 elseif c == 'i'
			call add(pat, '^\t*\zs \+')
		 elseif c == 's'
			call add(pat, ' \+\ze\t')
		 elseif c == 't'
			call add(pat, '[^\t]\zs\t\+')
			let bad .= c
	  if len(pat) > 0
		 let s = join(pat, '\|')
		 exec 'syntax match ExtraWhitespace "'.s.'" containedin=ALL'
		 syntax clear ExtraWhitespace
	  if len(bad) > 0
		 echo 'ShowWhitespace ignored: '.bad

   " function ToggleShowWhitespace {{{2
   function! ToggleShowWhitespace()
	  if !exists('b:ws_show')
		 let b:ws_show = 0
	  if !exists('b:ws_flags')
		 let b:ws_flags = 'est'  " default (which whitespace to show)
	  let b:ws_show = !b:ws_show
	  if b:ws_show
		 call ShowWhitespace(b:ws_flags)
		 call ShowWhitespace('')

   " function MyTabL "{{{2
   function! MyTabL()

	  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*')
		 ". winnr . '/' . tabpagewinnr(i,'$')
		 let s .= '%*'
		 let s .= (i == t ? ' %#TabLineSel# ' : '%#TabLine#')

		 let file = bufname(buflist[winnr - 1])
		 "let file = fnamemodify(file, ':p:t')
		 let file = (i == t ? file : fnamemodify(file, ':p:t') )
		 if file == ''|let file = '[No Name]'|endif
		 let s .= i.' '.file
		 let s .= (i == t ? ' ' : '')

		 let i = i + 1

	  let s .= '%T%#TabLineFill#%='
	  let s .= (tabpagenr('$') > 1 ? '%999XX' : 'X')
	  return s

   " function DiffWithSaved "{{{2
   " Diff with saved version of the file
   function! s:DiffWithSaved()
	  let filetype=&ft
	  vnew | r # | normal! 1Gdd
	  exe "setlocal bt=nofile bh=wipe nobl noswf ro ft=" . filetype
   com! DiffSaved call s:DiffWithSaved()

   " function SetStatusLineStyle "{{{2
   function! SetStatusLineStyle()
	  let &stl="%F%m%r%h%w\ [%{&ff}]\ [%Y]\ %P\ %=[a=\%03.3b]\ [h=\%02.2B]\ [%l,%v]"


" OPTIONS "{{{1
" ===========================================================================================================================================================================

" Basic Settings "{{{2
" first the disabled features due to security concerns. security fix for modelines
set modeline
set nocompatible		" vim, not vi.. must be first, because it changes other options as a side effect
set tags=tags;/			" search recursively up for tags
set ttyfast				" we have a fast terminal
set tw=500				" default textwidth is a max of 5
set undolevels=10000	" 1000 undos
set updatecount=50		" switch every 50 chars
set whichwrap+=b,s,<,>,h,l,[,]			" backspaces and cursor keys wrap to
set wildignore+=*.o,*~,.lo,*.exe,*.bak	" ignore object files
set wildmenu							" menu has tab completion
set wildmode=longest:full				" *wild* mode
set title titlelen=150 titlestring=%(\ %M%)%(\ (%{expand(\"%:p:h\")})%)%(\ %a%)\ -\ %{v:servername}
set nowrap
set autoindent smartindent		" auto/smart indent
set autoread					" watch for file changes
set backspace=indent,eol,start	" backspace over all kinds of things
set backup						"keep a backup file
set cmdheight=1					" command line two lines high
set complete=.,w,b,u,U,t,i,d	" do lots of scanning on tab completion
set cursorline					" show the cursor line
set enc=utf-8 fenc=utf-8		" utf-8
set history=30000				" keep 3000 lines of command line history
set keywordprg=TERM=mostlike\ man\ -s\ -Pless
set laststatus=2
set lazyredraw					" do not redraw when do not have to
set linebreak					" wrap at 'breakat' instead of last char
set magic						" Enable the "magic"
set noautowrite					" do not automagically write on :next
set noerrorbells				" no error bells please
set noexpandtab					" no expand tabs to spaces"
set nohidden					" close the buffer when I close a tab (I use tabs more than buffers)
set nospell
set noerrorbells visualbell t_vb= " Disable ALL bells
set number					" line numbers
set pastetoggle=<F11>
set noruler					" show the line number on the bar
set scrolloff=3				" keep at least 3 lines above/below
set shiftwidth=3			" shift width
set showcmd					" Show us the command we're typing
set showfulltag				" show full completion tags
set showmode				" show the mode all the time
set sidescroll=2			" if wrap is off, this is fasster for horizontal scrolling
set sidescrolloff=2			"keep at least 5 lines left/right
set swapfile
set swapsync=fsync
set noguipty
set splitright
set splitbelow
set winheight=25
set winminheight=5	" minimal value for window height
"set winheight=30	" set the minimal window height
set equalalways		" all the windows are automatically sized same
set eadirection=both	" only equalalways for horizontally split windows
set laststatus=2
set tabstop=4
set softtabstop=4
set shiftwidth=3
set switchbuf=usetab
set commentstring=\ #\ %s
set tabpagemax=35
set showtabline=2		" 2 always, 1 only if multiple tabs
set smarttab			" tab and backspace are smart
set foldmethod=marker
set foldenable
set foldcolumn=2 " the blank left-most bar left of the numbered lines
set incsearch                 " incremental search
set ignorecase              " search ignoring case
set sc								" override 'ignorecase' when pattern has upper case characters
set smartcase                 " Ignore case when searching lowercase
set showmatch                 " show matching bracket
set diffopt=filler,iwhite     " ignore all whitespace and sync"
set stal=2
set tabline=%!MyTabL()
" MAIN LETS "{{{2
let $BKDIR=expand("$HOME") . "/.bk"
let &viewdir=expand("$BKDIR") . "/.vim/v"
let &dir=expand("$BKDIR") . "/.vim"
let &backupdir=expand("$BKDIR") . "/.vim"
let maplocalleader=','
let g:vimsyn_folding='af'
"let &verbosefile=expand("$BKDIR") . "/.vim/vim-messages.

"Disable filetype-specific maps
let no_plugin_maps=1

" viminfo "{{{4
"  "       Maximum number of lines saved for each register
"  %       When included, save and restore the buffer lis
"  '       Maximum number of previously edited files for which the marks are remembere
"  /       Maximum number of items in the search pattern history to be saved
"  :        Maximum number of items in the command-line history
"  <       Maximum number of lines saved for each register.
"   @       Maximum number of items in the input-line history
"  h       Disable the effect of 'hlsearch' when loading the viminfo
"  n       Name of the viminfo file.  The name must immediately follow the 'n'.  Must be the last oneEnvironment variables are expanded when opening the file, not when setting the option
"  r       Removable media.  The argument is a string
"  s       Maximum size of an item in Kbyte"}}}4
let &viminfo="%200,'200,/800,h,<5000,:900,s150,r/tmp,r" . expand("$BKDIR") . ",n" . expand("$BKDIR") ."/.vim/.viminfo"


" ---------------------------------
" Switch syntax highlighting on, when the terminal has colors, Also switch on highlighting the last used search pattern.
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')|set mouse=|endif
if has('title')|set titlestring=%t%(\ [%R%M]%)| endif
if has('statusline')|call SetStatusLineStyle()|endif

set bg=dark term=$TERM
if &t_Co > 2  
   if &term == "putty-256color"
	  colorscheme askapachecode
	  set hlsearch t_Co=256 t_AB=�[48;5;%dm t_AF=�[38;5;%dm

   if &term == "xterm-256color"

	  " flash screen for visual bell
	  set vb
	  let &t_vb="\<Esc>[?5h\<Esc>[?5l"

	  colorscheme askapachecode
	  set hlsearch t_Co=256

   syntax on
   filetype indent plugin on
   " for crontab editing, visudo stuff
   set term=dumb nohlsearch
   syntax off
   filetype indent plugin off

" cool way to change cursor color depending on insert/non-insert mode
"if &term =~ "xterm-256color"
"let &t_SI = "\<Esc>]12;purple\x7"
"let &t_EI = "\<Esc>]12;blue\x7"


" Commented Out sets "{{{4
" set term=putty-256color		" The environment variable TERM, if it exists, is used to set the 'term'"
" set shell=/bin/bash		" The environment variable SHELL, if it exists, is used
"set tabstop=3
"set softtabstop=2
" Use the same symbols as TextMate for tabstops and EOLs
"set listchars=tab:▸\ ,eol:¬,trail:-
"set foldlevel=3
"set foldclose=all
"set foldopen=hor
" set t_Co=8
" set notimeout		" do not timeout on mappings
" set ttimeout		" do timeout on terminal key codes
" set timeoutlen=100	" timeout after 100 msec - requires the key-codes to be sent within 100 msec in
" set more			" use more prompt
" set mousehide			" hide the mouse when typing
" set paste			" paste mode is great for pasting text with mouse
" set matchpairs+=<:>		" add < and > to match pairs

" ----------------------------------------------------------------
" ===========================================================================================================================================================================

" auto load extensions for different file types
if has('autocmd')
   if !exists("autocommands_loaded")
	  let autocommands_loaded = 1
	  runtime ftplugin/man.vim

	  " Buffer Autocommands "{{{2	 
	  autocmd BufWritePre *.cpp,*.hpp,*.i :call StripTrailingWhitespace()

	  augroup vimrc
		 au BufReadPre * setlocal foldmethod=indent
		 au BufWinEnter * if &fdm == 'indent' | setlocal foldmethod=manual | endif
	  augroup END

	 augroup vimrc
		au BufReadPre * setlocal foldmethod=indent
		au BufWinEnter * if &fdm == 'indent' | setlocal foldmethod=manual | endif
	 augroup END
	  " improve legibility
	  au BufRead quickfix setlocal nobuflisted wrap number

	  " Save backupfile as backupdir/filename-06-13-1331
	  au BufWritePre * let &bex = strftime("-%m-%d-%H%M")

	  au BufRead /usr/local/apache/conf/* setlocal filetype=apache2
	  au BufRead *.sh,*.cron,*.bash setlocal filetype=sh
	  au BufRead *.vim,vimrc setlocal filetype=vim
	  au BufRead *.c setlocal filetype=c
	  au BufRead syslog-ng.conf setlocal filetype=syslog-ng  

	  au BufRead quickfix setlocal nobuflisted wrap number

	  au BufWinLeave *.sh,*.conf,*.vim,*.c,*.txt mkview
	  au BufWinEnter *.sh,*.conf,*.vim,*.c,*.txt silent loadview

	  " When editing a file, always jump to the last known cursor position. Don't do it when the position is invalid or when inside an event handler
	  au BufWinLeave *.sh,*.conf,*.vim,*.c,*.txt mkview
	  au BufWinEnter *.sh,*.conf,*.vim,*.c,*.txt silent loadview

	  " When editing a file, always jump to the last known cursor position. Don't do it when the position is invalid or when inside an event handler
	  " (happens when dropping a file on gvim). Also do not do it when the mark is in the first line, that is the default position when opening a file.
	  autocmd BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif

	  " if !exists(":DiffOrig") | command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis | wincmd p | diffthis | endif

	  autocmd BufWinLeave * call clearmatches()

	  "au VimEnter * set winheight=999
	  " FileType Autocommands "{{{2
	  "au FileType vim setlocal commentstring"%s

	  au FileType text setlocal textwidth=78	" For all text files set 'textwidth' to 78 characters.

	  " Turn on omni-completion for the appropriate file types.
	  autocmd FileType python set omnifunc=pythoncomplete#Complete
	  autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
	  autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
	  autocmd FileType css set omnifunc=csscomplete#CompleteCSS
	  autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
	  autocmd FileType php set omnifunc=phpcomplete#CompletePHP
	  autocmd FileType c set omnifunc=ccomplete#Complete
	  autocmd FileType ruby,eruby set omnifunc=rubycomplete#Complete
	  autocmd FileType ruby,eruby let g:rubycomplete_rails = 1  " Rails support
	  autocmd FileType java setlocal noexpandtab " do not expand tabs to spaces for Java

	  "Commented Out "{{{4
	  " Whitespace Highlighting
	  "au ColorScheme * highlight ExtraWhitespace ctermbg=red guibg=red
	  "au InsertLeave * redraw!
	  "highlight ExtraWhitespace ctermbg=red guibg=red
	  "match ExtraWhitespace /\s\+$/
	  "autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
	  "autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
	  "autocmd InsertLeave * match ExtraWhitespace /\s\+$/
	  "autocmd BufWinLeave * call clearmatches()

	  " Show leading whitespace that includes spaces, and trailing whitespace.
	  "au BufWinEnter * match ExtraWhitespace /^\s* \s*\|\s\+$/
	  "au BufWinEnter * match ExtraWhitespace /\s\+\%#\@<!$/
	  "au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
	  "au InsertLeave * match ExtraWhitespace /\s\+$/

	  " Convenient command to see the difference between the current buffer and the
	  " file it was loaded from, thus the changes you made.  Only define it when not defined already.
	  "if !exists(":DiffOrig") | command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis | wincmd p | diffthis | endif
	  "au BufRead httpd.conf set filetype=apache		" for htaccess files set filetype to apache


" MAPS "{{{1
" ===========================================================================================================================================================================
" ----------------------------------------------------------------

" Basic Maps  "{{{2

" Reindent File
map <silent> <LocalLeader>ri G=gg<CR>

" clear spaces at end of line
map <silent> <LocalLeader>cs :%s/\s\+$//e<CR>

" ---------------------------------
" Don't use Ex mode, use Q for formatting
map Q gq
map! ^H ^?

" Jump out of insert mode fast
"imap ii <Esc>

" next search result
map <silent> <LocalLeader>cn :cn<CR>

map <silent> <LocalLeader>ww :ww
" insert date
map <silent> <F12> dd\|a<C-R>=strftime("# Updated: %c\n")\|D<CR><ESC>

" show files in current directory
map <silent> <LocalLeader>ll :!tput clear;pwd;echo;ll;read -n1<CR><Esc>

" resource MYVIMRC
map <silent> <LocalLeader>. :unlet MyLoaded\|source $MYVIMRC<CR>

" tabedit from pwd
nmap <LocalLeader>te :tabedit

" tabedit from vimruntime
nmap <LocalLeader>tv :tabedit $VIMRUNTIME/

" toggle paste mode
nmap <LocalLeader>pm :set nonumber! foldcolumn=0!<CR>

" change directory to that of current file
nmap <LocalLeader>cd :cd%:p:h<CR>

" change local directory to that of current file
nmap <LocalLeader>lcd :lcd%:p:h<CR>

" toggle wrapping
nmap <LocalLeader>ww :set wrap!<CR>
nmap <LocalLeader>wo :set wrap<CR>

"toggles whether or not the current window is automatically zoomed
map <LocalLeader>mm :call ToggleMaxWins()<CR>

" TABS "{{{2
" ---------------------------------
" create a new tab
map <LocalLeader>tc :tabnew %<CR>

" close a tab
map <LocalLeader>tk :tabclose<CR>

" next tab
map <LocalLeader>tn :tabnext<CR>

" previous tab
map <LocalLeader>tp :tabprev<CR>

" FOLDS	 "{{{2
" ---------------------------------
" Fold with paren begin/end matching
nmap F zf%

" When I use ,sf - return to syntax folding with a big foldcolumn
nmap <LocalLeader>sf :set foldcolumn=6 foldmethod=syntax<cr>

map <LocalLeader>y a<C-R>="[[ $# -eq 0 ]] && echo -e >&2 \"$0: missing operand\\nTry \\`$0 --help' for more information.\" && return 2"<CR><ESC>

" COMMANDS   "{{{2
" ---------------------------------
" If I forgot to sudo vim a file, do that with :w!!
cmap w!! %!sudo tee > /dev/null %

nnoremap <LocalLeader>ts :call ToggleShowWhitespace()<CR>

" Bindings for Narrow/Widen
map <LocalLeader>N :Narrow<cr>
map <LocalLeader>W :Widen<cr>

" Bindings for ctk
nnoremap <LocalLeader>C :CC<cr>


" Speed hack
hi NonText cterm=NONE ctermfg=NONE