" .vimrc
" cayla fauver <[email protected]>
" Created: Sat Sep 17, 2005  08:02PM

syntax on

set background=dark
set backspace=indent,eol,start
set directory=~/tmp         " temp file directory for vim
set encoding=utf-8
set expandtab               " expands tabs to space, ctrl-v <tab> to get a real tab
set formatoptions+=roc      " r = comment leader after enter, o = comment leader after o, c = auto wrap comments
set formatoptions-=t        " t = disable line wrapping on normal text.
set gdefault                " set all substitutes to g by default
set history=50              " none mapped commands to remember.  default is 20
set hlsearch                " highlight search terms.  temp disable with :nohlsearch
set ignorecase              " ignore case in patterns
set incsearch               " match as search pattern is typed
set laststatus=2            " status bar always shows last two lines
set nowrap                  " don't wrap text
set number
set relativenumber          " line counts above and below from current position
set shiftwidth=4            " how much to indent on >>, cindent, etc
set showcmd                 " show command feedback in last line
set showmatch               " show matching brackets on cursor over
set showmode                " show mode in last line, eg. insert, visual, etc
set smartcase               " case insensitive if all lower case, sensitive if mixed; this works with ignorecase
set tabstop=4               " tab = n spaces
set textwidth=72            " needed for wrapping comments
set title
set titlestring=%F%(\ %M%)
set undolevels=5000         " max # of undos
set visualbell

" misc
" clear search
map <silent> <Leader>cs :let @/ = ""<CR>
" edit
map <silent> <Leader>e :call ToggleVExplorer()<CR>
" find color scheme element under cusor
" https://jordanelver.co.uk/blog/2015/05/27/working-with-vim-colorschemes/
nmap <leader>ce :call <SID>SynStack()<CR>

" leader g - git fugitive
noremap <Leader>gb :Gblame<CR> :ccl<CR>:cw<CR><CR>
noremap <Leader>gl :Glog<CR><CR>
noremap <Leader>gs :Gstatus<CR>

" leader t - toggles
noremap <Leader>tc :set cursorcolumn!<CR>
" don't bork idents on paste
noremap <Leader>tp :set invpaste paste?<CR>
" toggle line numbers
noremap <Leader>tn :set invnumber<CR>:set invrelativenumber<CR>

" leader f = fix format
" spelling
map <Leader>fs :setlocal spell! spelllang=en_us<CR>
" trailing whitespace
nnoremap <silent> <Leader>ft :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar>:nohl<CR>
" format json
noremap <Leader>fj :%!python -m json.tool<CR>
" xml clean
noremap <Leader>fx :set syntax=xml<CR>:%!xmllint --format --recover - 2>/dev/null<CR>

" leader m - make run create
" Quick run
nnoremap <Leader>mx :call <SID>compile_and_run()<CR>
" make html
noremap <Leader>mh :TOhtml<CR>:wq<CR>

" buffer nav
" noremap <Leader>[ :bp<CR>
" noremap <Leader>] :bn<CR>
" lint navigation
nmap <silent> <C-k> <Plug>(ale_previous_wrap)
nmap <silent> <C-j> <Plug>(ale_next_wrap)

" sudo :w :)
cmap w!! w !sudo tee > /dev/null %

let g:netrw_altv = 1
let g:netrw_banner = 0
let g:netrw_browse_split = 4
let g:netrw_liststyle = 3
let g:netrw_winsize = 25
" xml folding
let g:xml_syntax_folding=9
au FileType xml setlocal foldmethod=syntax
set foldlevelstart=99       " default all unfolded

" ansible plugin
let g:ansible_options = {'ignore_blank_lines': 0}
let g:ansible_unindent_after_newline = 1

" ctrlp
let g:ctrlp_match_window = 'bottom,order:ttb,min:1,max:10,results:10'
let g:ctrlp_by_filename = 1

" vim-template:
let g:templates_no_builtin_templates = 1
let g:templates_directory = "~/.vim/templates/"

" vim-airline
"let g:airline#extensions#tabline#enabled = 1
let g:airline_theme='distinguished'

" ale (lint)
let g:ale_echo_msg_error_str = 'E'
let g:ale_echo_msg_warning_str = 'W'
let g:ale_echo_msg_format = '[%linter%] %s [%severity%]'

" colorscheme (after all 'let' so things like solarized can be supported
let g:solarized_termcolors=256
colorscheme lanox-cef          " needs xterm 256 to look decent

" https://www.reddit.com/r/vim/comments/62s3fl/tmux_breaks_vim_colors/dfou3u7/
if &term =~ '256color'
  " Disable Background Color Erase (BCE) so that color schemes work
  " properly within 256-color terminals
  set t_ut=

" try to exlude pattens that might not be real words.  i.e. programming
syn match myExCapitalWords +\<[A-Z]\w*\>+ contains=@NoSpell
syn match myExNonWords +\<\p*[^A-Za-z \t]\p*\>+ contains=@NoSpell

filetype plugin indent on
filetype off
" linter
let &runtimepath.=',~/.vim/bundle/ale'
filetype plugin on
augroup filetype
  au BufNewFile,BufRead *.txt,README*,mutt*[0-9] set filetype=human
augroup END

au FileType human               set noautoindent nosmartindent formatoptions-=r textwidth=72
au FileType c,cpp,java          let b:comment_leader = '// '
au FileType sh,make,perl,python let b:comment_leader = '# '
au FileType vim                 let b:comment_leader = '" '
au FileType gitcommit           set wrap textwidth=72 fo+=t
au FileType gitcommit           setlocal spell spelllang=en_us spellcapcheck=
au FileType gitcommit           call setpos('.', [0, 1, 1, 0])

" try to clear search on load and exit.  on exit is pre writing viminfo
au VimEnter,GUIEnter,BufNewFile,BufRead,VimLeavePre * let @/ = ""
au BufRead,BufNewFile *.py,*.pyw,*.c,*.h,*.yml,*.tf match ExtraWhitespace /\s\+$/

autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\   exe "normal! g`\"" |
\ endif

autocmd BufEnter * let &titlestring = hostname() . "-vim %F%(\ %M%) "
" http://vim.wikia.com/wiki/Automatically_quit_Vim_if_quickfix_window_is_the_last
au BufEnter * call MyLastWindow()

    " Automatically open the quickfix window
    autocmd User AsyncRunStart call asyncrun#quickfix_toggle(15, 1)
augroup END

" autocommands
autocmd BufRead,BufNewFile hosts set syntax=ansible_hosts
autocmd BufRead,BufNewFile manage*.yml set filetype=ansible
autocmd QuickFixCmdPost *grep* cwindow

" lets do it
inoremap  <Up>     <NOP>
inoremap  <Down>   <NOP>
inoremap  <Left>   <NOP>
inoremap  <Right>  <NOP>
noremap   <Up>     <NOP>
noremap   <Down>   <NOP>
noremap   <Left>   <NOP>
noremap   <Right>  <NOP>


function! MyLastWindow()
  " if the window is quickfix go on
  if &buftype=="quickfix"
    " if this window is last on screen quit without warning
    if winbufnr(2) == -1

function! ToggleVExplorer()
  if exists("t:expl_buf_num")
      let expl_win_num = bufwinnr(t:expl_buf_num)
      if expl_win_num != -1
          let cur_win_nr = winnr()
          exec expl_win_num . 'wincmd w'
          exec cur_win_nr . 'wincmd w'
          unlet t:expl_buf_num
          unlet t:expl_buf_num
      exec '1wincmd w'
      let t:expl_buf_num = bufnr("%")

function! <SID>SynStack()
  if !exists("*synstack")
  echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')

function! Customize()
    if filereadable(expand("~/.vim/vimrc.personal"))
        source ~/.vim/vimrc.personal
call Customize()

function! s:compile_and_run()
    exec 'w'
    if &filetype == 'c'
        exec "AsyncRun! gcc % -o %<; time ./%<"
    elseif &filetype == 'cpp'
       exec "AsyncRun! g++ -std=c++11 % -o %<; time ./%<"
    elseif &filetype == 'java'
       exec "AsyncRun! javac %; time java %<"
    elseif &filetype == 'sh'
       exec "AsyncRun! time bash %"
    elseif &filetype == 'python'
       exec "AsyncRun! time python %"