" Config {{{
if platform#is_windows()
  set rtp+=~/.vim
endif

" Plugins {{{
call plug#begin('~/.vim/plugs')

" vim-airline improved status bar
Plug 'vim-airline/vim-airline'
let g:airline_left_sep=''
let g:airline_right_sep=''
" tabline.vim sanely numbered tabs
Plug 'mkitt/tabline.vim'

" TODO Find YouCompleteMe Windows setup that works
if !platform#is_windows()
  " YouCompleteMe with parameter completion
  Plug 'oblitum/YouCompleteMe', {'do': './install.py --clang-completer'}
endif
let g:ycm_min_num_of_chars_for_completion=1
let g:ycm_complete_in_comments=1
let g:ycm_complete_in_strings=1
let g:ycm_collect_identifiers_from_comments_and_strings=1
let g:ycm_autoclose_preview_window_after_insertion = 1
let g:ycm_seed_identifiers_with_syntax=1
let g:ycm_always_populate_location_list=1
let g:ycm_error_symbol="-▸"
let g:ycm_warning_symbol="-▸"
set completeopt-=preview
nnoremap <leader>fx :YcmCompleter FixIt<CR>
nnoremap <leader>jd :YcmCompleter GoTo<CR>
nnoremap <leader>gt :YcmCompleter GetType<CR>
nnoremap <leader>gp :YcmCompleter GetParent<CR>
nnoremap <leader>gd :YcmCompleter GetDoc<CR>
nnoremap <leader>sd :YcmShowDetailedDiagnostic<CR>
" Quick toggle quickfix & location list
Plug 'Valloric/ListToggle'

" UltiSnips snippet engine
Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'

" CMake completions & syntax
Plug 'richq/vim-cmake-completion' | Plug 'rperier/vim-cmake-syntax'

" Completion for vimscript
Plug 'vim-scripts/vimomni', {'for': ['vim']}

" format.vim format with text objects
if platform#is_linux()
  Plug 'git@bitbucket.org:infektor/format.vim.git'
else
  Plug '~/Sandbox/format'
endif

" delimitMate paired delimiters
Plug 'jiangmiao/auto-pairs'
" Improved % matching
Plug 'opennota/vim-matchit'
" Tabulaize text with regex
Plug 'godlygeek/tabular'
" Display xterm color table
Plug 'guns/xterm-color-table.vim'
" Sane insert mode pasting from system clipboard
Plug 'ConradIrwin/vim-bracketed-paste'
" Open file:line at line from terminal
Plug 'bogado/file-line'
" Open file:line at line from command
Plug 'kopischke/vim-fetch'

" fzf CLI FuZzy Finder wrapper
Plug 'junegunn/fzf', {'dir': '~/.fzf', 'do': './install --all --no-update-rc'}
Plug 'junegunn/fzf.vim'
exec 'nmap <C-f>f :Files '
nmap <C-f>g :GitFiles<CR>
exec 'nmap <C-f>a :Ag '
nmap <C-f>b :Buffers<CR>
nmap <C-f>l :BLines<CR>
nmap <C-f>c :Commits<CR>
nmap <C-f>h :Helptags<CR>
nmap <C-f>s :Snippets<CR>

" Library for creating text objects
Plug 'kana/vim-textobj-user'
" Entire file text object.
let g:textobj_entire_no_default_key_mappings = 1
Plug 'kana/vim-textobj-entire'
xmap a% <Plug>(textobj-entire-a)
omap a% <Plug>(textobj-entire-a)
xmap i% <Plug>(textobj-entire-i)
omap i% <Plug>(textobj-entire-i)
" Parameter text object
Plug 'sgur/vim-textobj-parameter'
" Underscope text object
Plug 'lucapette/vim-textobj-underscore'
" Comment block text object
Plug 'glts/vim-textobj-comment'
" Conflict marker text object
Plug 'rhysd/vim-textobj-conflict'

" vim-commentary toggle comments
Plug 'tpope/vim-commentary'
" vim-surround edit delimiters
Plug 'tpope/vim-surround'
" vim-repeat better dot command
Plug 'tpope/vim-repeat'
" vim-fugitive git wrapper
Plug 'tpope/vim-fugitive'
" vim-eunuch unix warppers
Plug 'tpope/vim-eunuch'
" vim-vinegar improved directory browser
Plug 'tpope/vim-vinegar'
" vim-abolish camelCase to under_score & stuff
Plug 'tpope/vim-abolish'
" vim-unimpaired for pairs of tasks
Plug 'tpope/vim-unimpaired'
" vim-sensible sane default settings
Plug 'tpope/vim-sensible'
" vim-speeddating
Plug 'tpope/vim-speeddating'

" DoxygenToolkit documentation stubs
Plug 'vim-scripts/DoxygenToolkit.vim'
let g:DoxygenToolkit_commentType="C++"
map <leader>d :Dox<CR>

" vim-notes easy note taking
Plug 'xolox/vim-notes' | Plug 'xolox/vim-misc'
let g:notes_directories = ['~/Sync/Notes']
let g:notes_title_sync = 'rename_file'
let g:notes_word_boundries = 1
hi link notesTodo Todo
hi link notesDoneMarker Note
hi link notesXXX Important

if !platform#is_windows()
  " Seemless vim/tmux pane navigation
  Plug 'christoomey/vim-tmux-navigator'
  " Enable focus events when in tmux session
  Plug 'tmux-plugins/vim-tmux-focus-events'
endif

" Markdown live browser preview
Plug 'suan/vim-instant-markdown'
" Markdown folding
Plug 'nelstrom/vim-markdown-folding'
let g:markdown_fenced_languages=['cpp', 'c', 'cmake', 'sh', 'vim', 'python']

" Foling form python
Plug 'tmhedberg/SimpylFold'
" Syntax checking for python
Plug 'nvie/vim-flake8', {'for': ['python']}

" Folding for json
Plug 'elzr/vim-json'

" Improved syntax for C/C++
Plug 'kbenzie/vim-native-syntax'
let g:native_syntax#highlight_operators=1

" GLSL syntax
Plug 'tikhomirov/vim-glsl'

" HLSL syntax
Plug 'beyondmarc/hlsl.vim'

" OpenCL C syntax
Plug 'frasercrmck/opencl.vim'

" spir-vim in development
Plug '~/spir-vim'
" jira.vim in development
Plug '~/jira.vim'

call plug#end()
" }}}

" Mappings {{{
" Enable all mouse features
set mouse=a

" Treat long lines as line containing breaks
map j gj
map k gk
" Quick write
map <leader>w :w!<CR>

" Switch panes
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l

" Quick tabs
exec "nmap <leader>tn :tabnew "
nmap <leader>tc :tabclose<CR>
nmap <leader>to :tabonly<CR>
exec "nmap <leader>tm :tabmove "

" Clear search highlights
map <leader><Space> :noh<CR>

" Quick clipboard yank/put
map <leader>y "+y
map <leader>Y "+Y
map <leader>p "+p
map <leader>P "+P

" Jump to current location list item
nmap <leader>ll :ll<CR>
" Jump to next location list item
nmap <leader>ln :lnext<CR>
" Jump to previous location list item
nmap <leader>lp :lprevious<CR>

" Quickly access spelling menu
imap <C-s> <C-g>u<C-X>s
nmap <C-s> i<C-g>u<C-X>s

" Disable 'Q' from opening Ex mode
nmap Q <nop>
" Disable 'K' from loading man pages in normal mode
nmap K <nop>
" Disable 'K' from loading man pages in visual mode
vmap K <nop>

" Split line at the cursor
nnoremap [j i<CR><Esc>
nnoremap ]j a<CR><Esc>
" Mappings }}}

" Behaviour {{{
" Set window title to titlestring
set title
" Show relative line numbers & current line number
set number
" Keep cursor from buffer edges
set scrolloff=8
" Turn backup off
set nobackup nowritebackup noswapfile

" Wrap to whole words
set wrap linebreak nolist
" Don't add 2 spaces after end of sentence
set nojoinspaces

" Use Unix as standard file type
set fileformats=unix,dos,mac
" Allow : in filenames to allow gf to specify line numbers
set isfname-=:

" Highlight search matches & show search matches while typing
set hlsearch
" Set ignore search case unless mixed
set ignorecase smartcase

" Allow buffers with changes to be hidden
set hidden
" Open new splits on the other side of the axis
set splitbelow splitright
" Indicates a fast terminal connection
set ttyfast
" Set syntax as default fold method
set foldmethod=syntax
set foldlevel=20

" Automatically write changes to files
set autowrite

" Format text
"   r - insert comment leader on 'o' and 'O'
"   q - allow formatting with 'gq'
set formatoptions+=rq

" Enable modeline
set modeline

" Don't redraw during execution macros, registers, commands, etc.
set lazyredraw
" Behaviour }}}

" Autocommands {{{
augroup reopen_at_last_cursor
  autocmd!
  " Reopening a file at last curson position
  au FocusGained * set relativenumber
  au FocusLost * set norelativenumber
  au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$")
          \ | exe "normal! g'\"" | endif
augroup END
" Autocommands }}}

" Functions {{{
" Strip trailing whitespace
function! <SID>StripWhitespace()
  let l = line(".")
  let c = col(".")
  %s/\s\+$//e
  call cursor(l, c)
endfunction
command! StripWhitespace :call <SID>StripWhitespace()
augroup strip_white_space
  " Strip whitespace on buffer write
  autocmd!
  autocmd BufWritePre * :call <SID>StripWhitespace()
augroup END

" Show highlight group under cursor
map \hi :echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") .
  \ '> trans<' . synIDattr(synID(line("."),col("."),0),"name") . "> lo<"
  \ . synIDattr(synIDtrans(synID(line("."),col("."),1)),"name") . ">"<CR>

" Stringify
" Make a code block in to a C string literal
function! <SID>Stringify()
  " Escape existing escape characters
  execute 's/\\/\\\\/ge'
  " Escape quotes
  execute 's/"/\\"/ge'
  " Prepend quote
  execute 's/^/"/g'
  " Append carriage return, quote
  execute 's/$/\\n"/g'
  noh
endfunction
map <silent> <leader>s :call <SID>Stringify()<CR>
" Make a C string literal in to a code block
function! <SID>Destringify()
  " Remove final quote and carriage return
  execute 's/\\n"\s*$//ge'
  " Remove first quote
  execute 's:^\(\s*\)":\1:ge'
  " Remove quote escapes
  execute 's/\\"/"/ge'
  " Remove escapes of escapes characters
  execute 's/\\\\/\\/ge'
  noh
endfunction
map <silent> <leader>S :call <SID>Destringify()<CR>

" Invoke terminal command without prompt and then redraw.
command! -nargs=+ Silent execute 'silent <args>' | redraw!

" Set the tab width for the current filetype
function! <SID>TabWidth(width)
  execute "set tabstop=".a:width
  execute "set shiftwidth=".a:width
  execute "set softtabstop=".a:width
  echo "Tab width is now ".a:width
endfunction
command! -nargs=1 TabWidth :call <SID>TabWidth(<f-args>)

" Toggle task list bullet
function! <SID>TaskToggle()
  " Get current line
  let l:line = getline('.')

  " Get the ' ' or 'x' character from within the task bullet
  let l:pattern = '[-\*+] \[\zs[ x]\ze]'
  let l:char = matchstr(l:line, l:pattern)

  " Toggle the ' ' or 'x' character
  if l:char == 'x'
    let l:char = ' '
  else
    let l:char = 'x'
  endif

  " Replace the current line with a new one
  call setline(line('.'), substitute(l:line, l:pattern, l:char, ''))
endfunction
command! TaskToggle :call <SID>TaskToggle()
nnoremap <leader>x :TaskToggle<CR>
" Functions }}}