vim / .vimrc

set expandtab shiftwidth=4 tabstop=4 list hidden nowritebackup nobackup
set spelllang=en_us spellsuggest=5 ruler textwidth=0 hlsearch wrap cursorline
set incsearch smartindent paste ignorecase
set wildcharm=<Tab> wildmenu wildmode=full
" set cursorline cursorcolumn

" Vim 7.3-specific config
if version >= 703
    set relativenumber

    " Pull up NERD Tree and the Tag List plugins
    nnoremap <silent> <F6> :NERDTreeToggle<CR>:set norelativenumber nolist<CR>
    set number
    nnoremap <silent> <F6> :NERDTreeToggle<CR>:set nonumber nolist<CR>

" Replace stuff with line number :%s/\v^\[ ?\d+]/\=line(".")/

" Trim all trailing whitespace before saving
autocmd BufWritePre * :%s/[ \t\r]\+$//e

" Automatically format certain files using tidy
" autocmd FileType xml exe ":silent 1,$!tidy --input-xml true --indent yes -q"
" autocmd FileType html,htm exe ":silent 1,$!tidy --indent yes -q"

" autocmd FocusLost *.inc,*.php,*.html,*.js,*.css :w
au BufEnter,BufRead,BufNewFile *.inc,*.phtml,*.php setlocal shiftwidth=2 tabstop=2 syntax=php nolist
au BufEnter,BufRead,BufNewFile *.htm,*.html setlocal shiftwidth=2 tabstop=2 syntax=html nolist
au BufEnter,BufRead,BufNewFile *.xml,*.rml setlocal shiftwidth=2 tabstop=2 syntax=xml nolist
au BufEnter,BufRead,BufNewFile *.css setlocal shiftwidth=2 tabstop=2 syntax=css nolist
au BufEnter,BufRead,BufNewFile *.js setlocal shiftwidth=2 tabstop=2 syntax=javascript nolist
au BufEnter,BufRead,BufNewFile *.pde,*.ino setlocal shiftwidth=2 tabstop=2 syntax=c nolist ft=arduino
au BufEnter,BufRead,BufNewFile *.coffee setlocal shiftwidth=2 tabstop=2 syntax=coffee nolist
au BufEnter,BufRead,BufNewFile *.rb setlocal shiftwidth=2 tabstop=2 syntax=ruby nolist
au BufEnter,BufRead,BufNewFile *.hs setlocal shiftwidth=2 tabstop=2 syntax=haskell nolist
"au BufWritePost *.coffee silent CoffeeMake! | cwindow

" Highlight trailing spaces
autocmd ColorScheme * highlight ExtraWhitespace ctermbg=darkgreen guibg=darkgreen
highlight ExtraWhitespace ctermbg=darkgreen guibg=darkgreen
match ExtraWhitespace /\s\+\%#\@<!$/

" Highlight diffs
highlight DiffAdded guibg=darkgreen guifg=black
highlight DiffRemoved guibg=darkred guifg=white

syntax on

" Bindings for FindFile plugin
nnoremap <Leader><Leader>f :FC .<CR>
nnoremap <C-f> :FF<CR>

" Toggles list and line numbers to make it easier to copy buffer contents
nnoremap <Tab> :set nolist!<CR>:set nonumber!<CR>

" Find all occurrences of the word under the cursor and replace it with the
" specified value
nnoremap <Leader>s :%s/\<<C-r><C-w>\>/
nnoremap Zs /^\(.*\<<C-r><C-w>\>.*\)$<CR>

" Execute the selected expression in Python
vmap <Leader>I "xdmpiprint <Esc>pme`pv`e:!python -<CR>
vmap <Leader>i :!python -<CR>
nnoremap gp `[v`]

" Format IPMI trap varbinds
nnoremap <Leader>ipmi IGUID: <Esc>16f s<CR>Sequence #: <Esc>2f s<CR>Timestamp: <Esc>4f s<CR>UTC Offset: <Esc>2f s<CR>Trap Source Type: <Esc>f s<CR>Event Source Type: <Esc>;s<CR>Event Severity: <Esc>;s<CR>Sensor Device: <Esc>;s<CR>Sensor #: <Esc>;s<CR>Entity: <Esc>;s<CR>Entity Instance: <Esc>;s<CR>Event Data: <Esc>8f s<CR>Language Code: <Esc>f s<CR>Manufacturer ID: <Esc>4f s<CR>System ID: <Esc>2f s<CR>OEM Custom Fields: <Esc>

" Toggle things that make it more difficult to copy/paste code samples
map <F10> :set invnumber<CR>:set invlist<CR>

" For easier Django blocks
nnoremap <Leader>b i{% block  %}{% endblock %}<Esc>3F i
nnoremap <Leader>B i{% block  %}<CR>{% endblock %}<Esc><Up>$2hi
ab bl <Esc>bi{% block <Esc>ea %}{% endblock %}<Esc>h%i

" Replace pretty quotes with standard ASCII quotes
nnoremap <Leader>" :%s/\v(“\|”)/"/g<CR>
nnoremap <Leader>' :%s/’/'/g<CR>

filetype plugin on
set omnifunc=syntaxcomplete#Complete

" For code folding
nnoremap <Leader>x :set fdm=indent foldminlines=10<CR>
nnoremap <Leader>z zA

" For RST
map <C-h>1 yyPVr=jpVr=o<CR>
map <C-h>2 yypVr=o<CR>
map <C-h>3 yypVr-o<CR>
map <C-h>4 yypVr+o<CR>
map <C-h>5 yypVr^o<CR>
map <C-h>6 yypVr*o<CR>
map <C-b> bi**<Esc>ea**
map <C-e> bi*<Esc>ea*
map <C-l> i`<Esc>ea <>`_<Esc>hhi

" For the mini buffer window
let g:miniBufExplMapWindowNavVim = 1
let g:miniBufExplMapWindowNavArrows = 1
let g:miniBufExplMapCTabSwitchBufs = 1
let g:miniBufExplModSelTarget = 1

" For Tag List plugin
let Tlist_Ctags_Cmd = '/usr/local/bin/ctags'
let Tlist_Use_Right_Window = 1
let Tlist_Inc_Windwidth = 70
let Tlist_Exit_OnlyWindow = 0
nnoremap <Leader>S :TlistSync<CR>

" Center search results vertically on the screen
nnoremap <silent> n nzz
nnoremap <silent> N Nzz

" Find in files
function! s:FindCurrentWord()
    " Find the word under the cursor in all files (recursively) in the cwd
    normal "wyiw
    call s:FindWordInFS('\<'.@w.'\>')

function! s:FindNeedle()
    " Find whatever is in the search buffer in all files (recursively in the
    " current working directory
    call s:FindWordInFS(@/)

function! s:FindWordInFS(word)
    " Searches for all instances of a:word in all text files in the current
    " working directory (recursively).  Matches are shown with some context
    " in a new scratch buffer

    setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap
    setlocal modifiable
    execute 'silent r!egrep -riInC2 "'.a:word.'" *'
    normal ggdd

    nnoremap <buffer> <Esc> <C-w>c
    nnoremap <buffer> <Return> ^<C-w>gF

    let b:qf_list = []
    python << EOF
import vim
import re

magic = re.compile(r'^([^:-]+):(\d+):(.*)$')

for line in vim.current.buffer:
    matches = magic.match(line)
    if matches:
        vim.command('let l:qf_item = {}')
        vim.command('let l:qf_item.filename = "%s"' %
        vim.command('let l:qf_item.lnum = %s' %
        vim.command("let l:qf_item.text = '%s'" %"'", "''"))
        vim.command('call add(b:qf_list, l:qf_item)')
    call setqflist(b:qf_list, 'r')

    highlight Needle ctermbg=red guibg=red
    exec "match Needle /".a:word."/"
    set nomodifiable

command! FindCurrentWord call s:FindCurrentWord()
command! FindNeedle call s:FindNeedle()
nnoremap <Leader>f :FindNeedle<CR>
nnoremap <Leader>g :FindCurrentWord<CR>
nnoremap tc :tabclose!<CR><CR><CR>

" Next/Previous matches in files
nnoremap <silent> <F12> :cn<CR>zz
nnoremap <silent> <F11> :cp<CR>zz
nnoremap <Leader>. :cn<CR>zz
nnoremap <Leader>, :cp<CR>zz

" Handy for adding an IPython interactive shell for debugging
nnoremap <Leader>d iimport IPython; IPython.embed()<Esc>

" Space before and after (for math like a+b/c)
nnoremap <Leader>ba i <Esc>la <Esc>

function! BufSel(pattern)
    let bufcount = bufnr("$")
    let currbufnr = 1
    let nummatches = 0
    let firstmatchingbufnr = 0
    while currbufnr <= bufcount
            let currbufname = bufname(currbufnr)
            if(match(currbufname, a:pattern) > -1)
                echo currbufnr . ": ". bufname(currbufnr)
                let nummatches += 1
                let firstmatchingbufnr = currbufnr
        let currbufnr = currbufnr + 1
    if(nummatches == 1)
        execute ":buffer ". firstmatchingbufnr
    elseif(nummatches > 1)
        let desiredbufnr = input("Enter buffer number: ")
        if(strlen(desiredbufnr) != 0)
            execute ":buffer ". desiredbufnr
        echo "No matching buffers"

"Bind the BufSel() function to a user-command
command! -nargs=1 Bs :call BufSel("<args>")
nnoremap <F14> :Bs<Space>

" Customize the status line
set statusline=%F%m%r%h%w\ [%{&ff}][%Y][A=\%03.3b][H=\%02.2B][POS=%04l,%04v][%p%%][LEN=%L]
set laststatus=2

" GVIM-specifics
if has("gui_running")
    if has("win32")
        set guifont=Dina:h8
    elseif has("gui_gtk2")
        "set guifont=xos4\ Terminus\ 9
        set guifont=Andale\ Mono\ 9

    set nomousehide
    set spell
    colorscheme desert
    "set background=light
    "colorscheme solarized

    set guioptions=-T
    set guioptions=-t

    " Maximize the window
    nnoremap <silent> <F5> :set lines=999 columns=999<CR>:cd ~/dev/G3/G3code/backend<CR>

    " Automatically save the state of files when closed
    autocmd BufWinLeave *.* silent mkview

    " Automatically restore the state of files when opened
    autocmd BufWinEnter *.* silent loadview

command! -nargs=+ Shell call s:RunShellCommand(<q-args>)
function! s:RunShellCommand(cmdline)
    " Yank the contents of the current buffer into register z
    normal! %y z

    " Create a new window
    botright new
    setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap

    " Paste the contents of the buffer into this new buffer
    normal! ggVG"zP

    " write to a temporary file
    let l:tempfile = tempname()
    execute 'write '.fnameescape(l:tempfile)
    execute 'silent $read !'.a:cmdline.' '.fnameescape(l:tempfile)

    " Hit escape to close this window
    nnoremap <buffer> <Esc> <C-w>c

    setlocal nomodifiable

command! ReStructuredText call s:ReStructuredText()
function! s:ReStructuredText()
    call s:RunShellCommand('')

    " Allow modifications
    setlocal modifiable

    " Go to the top of the file
    normal! ggV

    " Clean up the boilerplate HTML
    if search("<body", 'W') > 0
        normal! dGdkgg

    " Disallow modifications
    setlocal nomodifiable

nnoremap <F2> :ReStructuredText<CR>

command! -range FetchCURL call s:FetchCURL(<line1>,<line2>)
function! s:FetchCURL(start,end)
    normal! "zy"zPgv
    "exec "'<,'>!curl -sk 'http://config:config@' -H 'Content-Type: application/xml; charset=UTF-8' -d @- | tidy -xml -iq -wrap 2048 -config ~/.tidy.conf"
    exec "'<,'>!curl -sk 'https://vimuser:em7admin@' -H 'Content-Type: application/xml; charset=UTF-8' -d @- | tidy -xml -iq -wrap 2048 -config ~/.tidy.conf"
    exec "normal v_v"
vnoremap <F3> :FetchCURL<CR>

command! RefreshFirefox call s:RefreshFirefox()
function! s:RefreshFirefox()
    let mywid = system("xdotool getactivewindow")
    let derp = system("xdotool search --name 'Vimperator' windowactivate key Escape key Escape type R")
    let derp = system("xdotool windowactivate ".mywid)