VIM Tips and Tricks

These are basically my notes on VIM, and some of the things I've found along the way. I expect that this will be something that continues to grow over time.

My Setup

My setup is based on a forked version of spf13 (from spf13/spf13-vim). You can check it out here: jmervine/vim-config.

Amazing Plugins/Addon

VIM plugins/addons I can't live without.

Code Samples

Shell function:

This fucnction adds :Shell, which is much like using a bank (!) to run a bash command, except that it takes the output and dumps it in to a buffer.

" :Shell <cmd>
" put shell command in new buffer.
command! -complete=shellcmd -nargs=+ Shell call s:RunShellCommand(<q-args>)
function! s:RunShellCommand(cmdline)
  echo a:cmdline
  let expanded_cmdline = a:cmdline
  for part in split(a:cmdline, ' ')
     if part[0] =~ '\v[%#<]'
        let expanded_part = fnameescape(expand(part))
        let expanded_cmdline = substitute(expanded_cmdline, part, expanded_part, '')
  botright new
  setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap
  call setline(1, 'You entered:    ' . a:cmdline)
  call setline(2, 'Expanded Form:  ' .expanded_cmdline)
  call setline(3,substitute(getline(2),'.','=','g'))
  execute '$read !'. expanded_cmdline
  setlocal nomodifiable

Disable mouse mode when not in gvim:

" turn off mouse mode
if !has('gui')
    set mouse-=a

Trailing whitespace handling:

" for use before a colorscheme definition
autocmd ColorScheme * highlight ExtraWhitespace ctermbg=red guibg=red

" for use when not using a colorscheme
" highlight ExtraWhitespace ctermbg=red guibg=red

" show unwanted whitespace
match ExtraWhitespace /\s\+\%#\@<!$/

" strip unwanted trailing whitespace on save
autocmd BufWritePre * :%s/\s\+$//e

Toggle spell checking:

" toggle spell checking
imap <Leader>s <C-o>:setlocal spell! spelllang=en_gb<CR>
nmap <Leader>s :setlocal spell! spelllang=en_gb<CR>

Tab handling for various file types:

augroup myfiletypes
  " Clear old autocmds in group

  " autoindent with two spaces, always expand tabs
  autocmd FileType * set ai sw=2 sts=2 et

  " autoindent with four spaces, always expand tabs
  " when working in:
  " - python
  " - html
  " - xml
  " - markdown
  autocmd FileType python,html,xml,markdown set ai sw=4 sts=4 et
augroup END

Published on in vim