" Author: Kevin McCarthy
"         http://www.8t8.us/
"

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Enable pathogen:                                      {{{
"   http://www.vim.org/scripts/script.php?script_id=2332
"   https://github.com/tpope/vim-pathogen
" Allows separation of plugins into bundles
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
execute pathogen#infect()

" }}}


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Basic Setup - behaviour, filetypes, syntax            {{{
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
behave xterm               " Sets selectmode, mousemodel, keymodel, selection

filetype plugin indent on  " Turns on filetype detection, plugin, indent

" Used to use this hack to get 256 colors in screen:
" if &term =~ "xterm" || &term =~ "screen"
"   set t_Co=256
" endif

set background=dark
if has("gui_running")
  colorscheme peaksea
else
  " Under urxvt-unicode, vim resets the background to light when the
  " colorscheme performs a
  "   highlight XXXX ctermbg=XXXX
  " regardless whether the ctermbg is set to a dark color or not.
  " See :help :hi-normal-cterm
  " Right now I don't know what to do about this.

  let g:xterm16_colormap="soft"
  let g:xterm16_brightness="default"
  colorscheme xterm16
endif

syntax enable

" Set the value used for <leader> in mappings
let g:mapleader = ","

" Set the value used for <localleader> in mappings
" (this is used less often)
let g:maplocalleader = "\\"

" Technically, this is already off when a .vimrc file is found
set nocompatible        " Use Vim defaults (much better!)

" }}}


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" General settings                                      {{{
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"
" File read/write settings
"
set noautowrite         " Don't automatically write the file
set nobackup            " Don't create backup files
set noexrc              " Disable .vimrc files in current directory
if has("unix")
   set fileformats=unix,dos,mac  " Allow editing of all types of files
else
   set fileformats=dos,unix,mac
endif
set modeline            " Scan for modeline commands
set modelines=5         " Scan 5 lines for modelines
set viminfo='20,\"50    " read/write a .viminfo file, don't store more
                        " than 50 lines of registers
set writebackup         " Make temp backup while overwrite file (for safety)

"
" Editing, formatting, indenting settings
"
set noautoindent        " Turn autoindent off
set backspace=indent,eol,start     " allow backspacing over all in insert mode
set expandtab           " I hate tabs!
set formatoptions+=n    " Add list support
set formatprg=par\ 72q\ g1  " Use par for gq. use gw for internal formatting
                            " g1 preserves double spaces after periods.
set list                " Try showing this all the time with better listchars
set listchars=tab:>-,trail:,extends:,precedes:
set shiftround          " Round indent off to 4 spaces
set shiftwidth=2        " Standard seems to be 2 spaces over nowadays
set smarttab            " Tab in front of line uses shiftwidth - good for coding
set tabstop=8           " set to 8 so other people's stuff looks normal
set textwidth=0         " don't automatically wrap my text

"
" Searching, tag, dictionary settings
"
if has("unix")
   set dictionary=/usr/share/dict/words  " Use with i-ctrl-X ctrl-K
endif
set nohlsearch          " turn off highlight searches, but:
                        " Turn hlsearch off/on with <leader>h
" used to use ctrl-n, but YankRing wants that mapping
" nnoremap <silent> <C-N> :se invhlsearch<CR>
nnoremap <silent> <leader>h :set invhlsearch<CR>
set incsearch           " Incremental search
" set showfulltag       " Show full tag when autocompleting CTRL-N/P
                        " this can show the parameters for functions
set tags=tags;/         " Search for the tags file upward.  Cool!
                        " see :help file-searching

"
" Terminal/display settings
"
" set cursorline        " highlight current line
" set display=lastline  " shows too long line at bottom of screen
set noerrorbells        " Stop the beeps
set scrolljump=-50      " Scroll half the window height when move off screen
set showmatch           " Show matching brace
set notitle             " don't try to set title in xterm
set ttyfast             " assume a fast terminal connection
set winminheight=0      " Allow windows to get fully squashed
set winminwidth=0       " Allow windows to get fully squashed
set visualbell t_vb=    " Turn off flashing

"
" Status bar and command line settings
"
set cmdheight=2         " Less Hit Return messages
set history=100         " Keep 100 lines of command line history
                        " (use arrow keys for history)
set laststatus=2        " Always show status bar
set report=0            " Always report line changes for : commands
set ruler               " Show cursor location
set shortmess=aoOtT     " Abbreviate the status messages
set showmode            " Show mode I'm in
set showcmd             " Show command I'm typing

"
" Command line completion:
"
set wildchar=<TAB>      " Character to start command line completion
set wildmenu            " Enhanced command line completion mode
" First list the possible completions.
" Then complete to longest matching string.
" Finally start cycling between completions (starts wildmenu mode).
set wildmode=list,longest,full

" }}}


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Plugins                                               {{{
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"""
"  BufExplorer
"  http://www.vim.org/scripts/script.php?script_id=42
"
"  One of the oldest and best buffer plugins.
"""
let g:bufExplorerSortBy='fullpath'   " Sort by full file path name.
let g:bufExplorerShowRelativePath=1  " Show relative paths.
let g:bufExplorerSplitOutPathName=0  " Don't split the path and file

"""
"  CtrlP
"  http://www.vim.org/scripts/script.php?script_id=3736
"
"  Fast file finding.
"  Better version of command-t:
"    - no external ruby compilation needed
"    - accomodates different working directory styles
"""
let g:ctrlp_map = '<leader>p'         " command to invoke the plugin
let g:ctrlp_working_path_mode = 0     " don't manage working directory
let g:ctrlp_max_height = 30           " maximum size of match window

" Bind leader-t to ctrlp to reduce transition pain
nnoremap <silent> <leader>t :CtrlP<CR>

"""
"  DirDiff
"  http://www.vim.org/scripts/script.php?script_id=102
"
"  Allows you to compare directories of files.  I use this from hg.
"""

"""
"  MatchIt
"  http://www.vim.org/scripts/script.php?script_id=39
"
"  Enhanced % matching.
"""

"""
"  The NERD tree
"  http://www.vim.org/scripts/script.php?script_id=1658
"
"  Trying to use this, but not convinced yet.
"""
let g:NERDTreeHijackNetrw=0 " for now, don't use it for directory browsing
nnoremap <silent> <F7> :NERDTreeToggle<CR>

"""
"  Obsession
"  http://www.vim.org/scripts/script.php?script_id=4472
"  https://github.com/tpope/vim-obsession
"
"  Provides continuously updating session files.  Useful for my main
"  todo editor where I want to pick up where I left off each time.
"""
set sessionoptions+=resize         " Restore the window dimensions

"""
"  patchreview
"  http://www.vim.org/scripts/script.php?script_id=1563
"
"  Allows easier review of a patch file across multiple files.
"  Vim has :diffpatch which is cool, but only works with one file.
"  I was going to write a script using a combination of
"  lsdiff, filterdiff, and :diffpatch but saw this plugin first.
"""

let g:patchreview_split_right = 1

"""
"  pathogen
"  http://www.vim.org/scripts/script.php?script_id=2332
"
"  Allows you to separate various plugins into their own directory inside a
"  bundle directory.
"""


"""
"  Rails
"  http://www.vim.org/scripts/script.php?script_id=1567
"
"  The plugin to have if you are doing rails development.
"""

"""
"  snipMate
"  http://www.vim.org/scripts/script.php?script_id=2540
"
"  Auto-completion templates.
"""

"""
"  Splice
"  http://www.vim.org/scripts/script.php?script_id=4026
"
"  Used for merge conflicts in hg or git.
"""

"""
"  TagList
"  http://www.vim.org/scripts/script.php?script_id=273
"
"  Nice for those big files with lots of methods
"""
nnoremap <silent> <F8> :TlistToggle<CR>
let Tlist_Exit_OnlyWindow = 1     " exit if taglist is last window open
let Tlist_Show_One_File = 1       " Only show tags for current buffer
let Tlist_Use_Right_Window = 1    " Open on right side
let Tlist_Enable_Fold_Column = 0  " no fold column (only showing one file)
let tlist_sql_settings = 'sql;P:package;t:table'
let tlist_ant_settings = 'ant;p:Project;r:Property;t:Target'
if has("gui_win32")
   let Tlist_Ctags_Cmd = 'C:/Users/kjm/ctag58/ctags.exe'
endif
" let Tlist_Ctags_Cmd = '/usr/bin/ctags'
" let Tlist_WinWidth=40
" let Tlist_WinWidth=33
" let Tlist_File_Fold_Auto_Close = 1  " automatically fold hidden buffers
" let Tlist_Sort_Type = "name"        " default is sort by file order
" let Tlist_Auto_Open = 1             " always show the tag file
" let Tlist_Display_Prototype = 1     " displays prototype

"""
"  vinegar
"  https://github.com/tpope/vim-vinegar
"
"  Simplfies the netrw/directory browser and provides a handy
"  "-" mapping to open the browser.
"""

"""
"  xmledit (ftplugin)
"  http://www.vim.org/scripts/script.php?script_id=301
"""
let xml_use_xhtml = 1             " Also use for xhtml

"""
" yankring
" http://www.vim.org/scripts/script.php?script_id=1234
"
" Implements the emacs concept of the kill ring in vim.
" Adds ctrl-n and ctrl-p for rotating through yanks after an initial paste
" :YRShow shows the YankRing buffer.
"
" TODO: not sure I like the history file or not, but I guess .viminfo already
"       leaks a lot of info.
"""
let g:yankring_history_dir = '~/.vim'  " Where to store the history file

let g:yankring_clipboard_monitor = 0   " Don't grab copies outside of vim into
                                       " the yankring.

let g:yankring_window_height = 12      " Increase size of YankRing buffer

nnoremap <silent> <F11> :YRShow<CR>   " Map F11 to show the YankRing buffer

" }}}


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Various maps, settings, and autocmds                  {{{
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"
" Netrw settings
"
let g:netrw_menu=0      " Don't show in menu

"
" Various syntax file config variables
"
let java_highlight_java_lang_ids = 1
let java_highlight_debug = 1
let java_allow_cpp_keywords = 1
let perl_extended_vars = 1
" let perl_fold = 1
let bash_is_sh = 1


" TODO - yes, these mapping are out of control.  I need to think more
" about what mappings I actually use.

" Edit a file in the same directory as the current buffer.
" This leaves the prompt open, allowing Tab expansion or manual completion.
nnoremap <leader>ed :e <C-R>=expand("%:p:h") . "/" <CR>

" Enter directory listing for the directory of the current buffer
nnoremap <leader>en :e %:p:h<CR>
nnoremap <leader>e. :e %:p:h<CR>
nnoremap <leader>. :e %:p:h<CR>

" Create a new window with directory listing of current buffer
nnoremap <leader>wd :new <C-R>=expand("%:p:h") . "/" <CR>
nnoremap <leader>wn :new %:p:h<CR>
nnoremap <leader>w. :new %:p:h<CR>

nnoremap <leader>vd :vnew <C-R>=expand("%:p:h") . "/" <CR>
nnoremap <leader>vn :vnew %:p:h<CR>
nnoremap <leader>v. :vnew %:p:h<CR>

" Change global directory to the current directory of the current buffer
nnoremap <leader>cd :cd %:p:h<CR>

" Regenerate tags.  I usually have a script in my project root called
" gentags.sh to do this.
nnoremap <leader>gt :!./gentags.sh<CR>

" Toggle relative line numbers
nnoremap <leader>rn :set invrelativenumber<CR>

"
" Switch between windows, maximizing the current window
"
nnoremap <C-J> <C-W>j<C-W>_
nnoremap <C-K> <C-W>k<C-W>_

"
" Maps ctrl-S to save.  Note this requires in my .zshrc:
"     setopt no_flow_control
"     stty -ixon -ixoff
"
nnoremap <C-S> :update<CR>
inoremap <C-S> <C-O>:update<CR>

"""
" Mappings from Steve Losh's excellent vimscript book:  {{{
"   http://learnvimscriptthehardway.stevelosh.com/
"""

" Edit your .vimrc in a split window
nnoremap <leader>ev :vsplit $MYVIMRC<cr>
nnoremap <leader>sv :source $MYVIMRC<cr>

" Open the previous buffer in a split window
nnoremap <leader>e# :execute "leftabove split " . bufname("#")<cr>

" operator pending mappings:

augroup kjm_markdown
  autocmd!

  autocmd FileType markdown onoremap ih :<c-u>execute "normal! ?^[-=]\\{2,}$\r:nohlsearch\rkvg_"<cr>
  autocmd FileType markdown onoremap ah :<c-u>execute "normal! ?^[-=]\\{2,}$\r:nohlsearch\rg_vk0"<cr>
augroup END

" Vimscript file settings ---------------------- {{{
augroup kjm_filetype_vim
    autocmd!
    autocmd FileType vim setlocal foldmethod=marker
augroup END
" }}}

" }}}


"
" From http://jetpackweb.com/blog/2010/02/15/vim-tips-for-ruby/
" and http://technicalpickles.com/posts/vimpocalypse/
"
augroup kjm_ruby
  autocmd!

  autocmd FileType ruby inoremap <C-l> <Space>=><Space>
  " convert word into ruby symbol
  autocmd FileType ruby inoremap <C-k> <C-o>b:<Esc>Ea
augroup END

" Trying out this to see if I like it
" set cul
" autocmd WinLeave * set nocul
" autocmd WinEnter * set cul


"
" Try the 'a' autoformat option for emails.  I spend way too much time
" autoformating my emails.  If it causes too much pain I can turn it back off
" see :help fo-table
" Alas, it is causing more problems than it's worth.  Turning off.
"
" autocmd FileType mail setlocal formatoptions+=a

augroup kjm_html_etc
  autocmd!

  "
  " Per http://vim.sourceforge.net/tips/tip.php?tip_id=330
  " this will stop the annoying html indentation.
  " xmledit does some things for us, and combined with autoindent that's probably
  " enough.
  "
  autocmd BufEnter
    \ *.erb,*.haml,*.htm,*.html,*.kid,*.php,*.rhtml,*.xml,*.xsd
    \ setlocal indentexpr= autoindent shiftwidth=2

  "
  " Per Charles E. Campbell's comment on
  " http://www.vim.org/tips/tip.php?tip_id=97
  " Auto timestamping html
  " This pattern assumes 'magic' is set (I changed it so I can understand the
  " pattern better).
  "
  " If you have <!-- DATE --> in the html file (with or without a trailing date)
  " it will substitute the current time in.  Too cool.
  "
  autocmd BufWritePre
    \ *.erb,*.htm,*.html
    \ exe "norm mzHmy"|exe '%s/\(<!-- DATE -->\)\(.*\d\d:\d\d\)\?/\1'.strftime("%b %d, %Y %H:%M")."/e"|norm 'yzt`z

  " This version only uses one mark but the screen jumps around when I save:
    " \ exe "norm mz"|exe '%s/\(<!-- DATE -->\)\(.*\d\d:\d\d\)\?/\1'.strftime("%b %d, %Y %H:%M")."/e"|norm `z
augroup END

" }}}


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Some layouts I used to use for serious editing        {{{
" Lately, there are some nice plugins that make file
" and buffer navigation much easier, so I don't use these
" often anymore.
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"
" Set up F9 to set up a 4 pane window with Tlist
"
function! SetUpFourPane()
  " set columns=202
  set columns=195
  set lines=85
  Tlist
  80 vnew
  " winpos 5 0
  winpos 0 0
endfunction
nnoremap <silent> <F9> :call SetUpFourPane()<CR>

"
" Set up F10 to invoke both NERDTree and TList
"
function! SetUpNERDTlistLayout()
  " nerd uses 31 columns + 1 for bar + 80 columns
  " set columns=112    " nerd + win size
  NERDTree
  " Project plugin behaves badly if we don't reset to the
  " 'main' window before toggling Tlist
  wincmd l
  TlistToggle
  set columns=143  " nerd + win + taglist size
endfunction
nnoremap <silent> <F10> :call SetUpNERDTlistLayout()<CR>

" }}}


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" A few handy tips                                      {{{
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" Regenerate local plugin help tags:
"   :helptags ~/.vim/doc
" Regenerate pathogen bundle tags
"   :Helptags

"
" FILE SEARCHING TIP
"
" See vim tip http://www.vim.org/tips/tip.php?tip_id=1234
"
" Use ctags to include filenames in the tag list.
"   just use the --extra=+f to include the filename and
"  --langdef=file --langmap='file:.ext1.ext2.ext3' to manually include
"  extensions ctags doesn't index by default.
"
"  Then use :tjump to present a list of matching results...
"
"  Even cooler, you can use regular expressions.  see :help tag-regexp
"    just prefix the tag with '/' and define a regexp


"
" JAVA SEARCHING
"
" from: <http://www.ophinity.com/papers/jim/index.html>
"
" set path+=.
" set path+=/home/kjm/google/src/google3/java/**
" autocmd BufRead *.java set include=^#\s*import
" autocmd BufRead *.java set includeexpr=substitute(v:fname,'\\.','/','g')
" map gf <C-W>f
" map gc gdb<C-W>f

" }}}