"*******************************************************
" SETTINGS

" Fix for syntastic
set shell=/bin/bash

" Set mouse mode.
set mouse=a

if has('mouse_sgr')
  set ttymouse=sgr
endif

" Allow backspace to remove lines.
set backspace=indent,eol,start

" Ensure we are out of crappy vi compatible mode.
set nocompatible

" Automatically change working directory to the directory of the open file.
set autochdir

" Enable syntax highlighting.
syntax on

colorscheme seoul256
" Set startup colorscheme.
if has("gui_running")
	colorscheme vizuki
endif
" Don't have vim store backup or swap files.
set nobackup
set noswapfile

" Briefly jump cursor to matching brace when typing completion brace.
set showmatch

" Decrease the time it takes to show the matching brace.
set matchtime=2

" Show line numbers by default.
set number

" Set encoding.
set encoding=utf-8

" Allow vim to recognize file types.
filetype on

" Allow vim to load plugins related to the detected file type.
filetype plugin on

" Allow vim to maintain a file's indent file as you edit it.
filetype indent on

" Highlight all results of a search within the file.
set hlsearch

" Set fold method to manual.
set foldmethod=manual

" Disable code folding.
set nofoldenable

" Set left and right option/alt keys to be meta keys
if has("gui_macvim")
    set macmeta
endif

" Whenever a buffer is written to a file run the syn script to synchronize with VM.

" Set softtabstop to 2 spaces.
set softtabstop=4

" Set shiftwidth to 2 spaces.
set shiftwidth=4

" Set tabstop to 2 spaces.
set tabstop=4

" Set expandtab by default.
"set expandtab
set noexpandtab

" Show statusline always.
set laststatus=2

" No need to add 'g' to the end of substitute patterns to replace all occurances.
set gdefault

"*******************************************************

" COMMANDS

" LN will toggle line numbers on or off.
command! LN set nonumber!

" RC will re-source this .vimrc file.
command! RC :source $MYVIMRC

" WR will force a write to a file you do not have permissions to modify.
command! WW w !sudo tee % > /dev/null

"*******************************************************

" KEY MAPPINGS

" Map ctrl+movement keys to ctrl+w followed by the movement key.
" Makes switching between split windows extremely simple.
map <C-Down> 10j
map <C-Up> 10k
map  10h
map  10l
map  10j
map  10k
"map  10h
"map  10l
" Map alt+movement keys to ctrl+w followed by the movement key.
" Makes moving windows much simpler.
map ∆ <C-W>J
map ˚ <C-W>K
map ˙ <C-W>H
map ¬ <C-W>L

" Map arrow keys to window resize commands.

" When pressing enter it will also run :noh to turn off highlights from previous search.
nnoremap <CR> :noh<CR>

""""" I feel like the following key mappings are a brute force way of navigating the document
""""" without using your eyes so I've temporarily commented them out while I try to learn some
""""" additional buffer movement and cursor movement commands in an attempt to phase the need
""""" for these "macro keys" out.

" Map uppercase movement keys to macro versions of themselves in normal and visual mode.
"nnoremap J 15j
"vnoremap J 15j
"nnoremap K 15k
"vnoremap K 15k
"nnoremap H 10h
"vnoremap H 10h
"nnoremap L 10l
"vnoremap L 10l

" Remap uppercase movement key functions to g+movement key.
"nnoremap gj J
"nnoremap gk K
"nnoremap gh H
"nnoremap gl L

" Force sync current file to vm
noremap <F4> :!~/bin/syn %<CR>

" F2 will use the current tab settings to retab the whole file.
noremap <F2> :retab!<CR>

noremap gw :Autoformat<CR><CR>

imap <C-c> <CR><Esc>O

"*******************************************************

" PLUGIN SETTINGS

" Invoke pathogen to load plugins.
execute pathogen#infect()

"-=-=-= localvimrc =-=-=-

" Don't ask when sourcing .lvimrc files.
let g:localvimrc_ask = 0

"-=-=-= AIRLINE/LIGHTLINE/PROMPTLINE =-=-=-

" Populate powerline symbols.
let g:airline_powerline_fonts = 1

let g:promptline_preset = {
    \'a' : [ promptline#slices#user() ],
    \'c' : [ promptline#slices#cwd() ],
    \'y' : [ promptline#slices#vcs_branch(), promptline#slices#git_status() ]}
    "\'b' : [ promptline#slices#host() ],
let lightline_theme = 'jellybeans'
if has("gui_running")
	let lightline_theme = 'solarized_light'
endif
let g:lightline = {
      \ 'colorscheme': lightline_theme,
      \ 'component': {
      \   'readonly': '%{&readonly?"":""}',
      \ },
      \ 'separator': { 'left': '', 'right': '' },
      \ 'subseparator': { 'left': '', 'right': '' },
      \ 'active': {
      \   'left': [ [ 'mode', 'paste' ], [ 'fugitive', 'filename' ]],
      \   'right': [ [ 'syntastic', 'lineinfo' ], ['percent'], [ 'fileformat', 'fileencoding', 'filetype' ] ]
      \ },
      \ 'component_function': {
      \   'fugitive': 'MyFugitive',
      \   'filename': 'MyFilename',
      \   'fileformat': 'MyFileformat',
      \   'filetype': 'MyFiletype',
      \   'fileencoding': 'MyFileencoding',
      \   'mode': 'MyMode',
      \ },
      \ 'component_expand': {
      \   'syntastic': 'SyntasticStatuslineFlag',
      \ },
      \ 'component_type': {
      \   'syntastic': 'error',
      \ },
      \ }

function! MyModified()
  return &ft =~ 'help' ? '' : &modified ? '+' : &modifiable ? '' : '-'
endfunction

function! MyReadonly()
  return &ft !~? 'help' && &readonly ? '' : ''
endfunction

function! MyFilename()
  let fname = expand('%:t')
  return fname == 'ControlP' ? g:lightline.ctrlp_item :
        \ fname == '__Tagbar__' ? g:lightline.fname :
        \ fname =~ '__Gundo\|NERD_tree' ? '' :
        \ &ft == 'vimfiler' ? vimfiler#get_status_string() :
        \ &ft == 'unite' ? unite#get_status_string() :
        \ &ft == 'vimshell' ? vimshell#get_status_string() :
        \ ('' != MyReadonly() ? MyReadonly() . ' ' : '') .
        \ ('' != fname ? fname : '[No Name]') .
        \ ('' != MyModified() ? ' ' . MyModified() : '')
endfunction

function! MyFugitive()
  try
    if expand('%:t') !~? 'Tagbar\|Gundo\|NERD' && &ft !~? 'vimfiler' && exists('*fugitive#head')
      let mark = ''  " edit here for cool mark
      let _ = fugitive#head()
      return strlen(_) ? mark._ : ''
    endif
  catch
  endtry
  return ''
endfunction

function! MyFileformat()
  return winwidth(0) > 70 ? &fileformat : ''
endfunction

function! MyFiletype()
  return winwidth(0) > 70 ? (strlen(&filetype) ? &filetype : 'no ft') : ''
endfunction

function! MyFileencoding()
  return winwidth(0) > 70 ? (strlen(&fenc) ? &fenc : &enc) : ''
endfunction

function! MyMode()
  let fname = expand('%:t')
  return fname == '__Tagbar__' ? 'Tagbar' :
        \ fname == 'ControlP' ? 'CtrlP' :
        \ fname == '__Gundo__' ? 'Gundo' :
        \ fname == '__Gundo_Preview__' ? 'Gundo Preview' :
        \ fname =~ 'NERD_tree' ? 'NERDTree' :
        \ &ft == 'unite' ? 'Unite' :
        \ &ft == 'vimfiler' ? 'VimFiler' :
        \ &ft == 'vimshell' ? 'VimShell' :
        \ winwidth(0) > 60 ? lightline#mode() : ''
endfunction

function! CtrlPStatusFunc_2(str)
  return lightline#statusline(0)
endfunction

let g:tagbar_status_func = 'TagbarStatusFunc'

function! TagbarStatusFunc(current, sort, fname, ...) abort
    let g:lightline.fname = a:fname
  return lightline#statusline(0)
endfunction

augroup AutoSyntastic
  autocmd!
  autocmd BufWritePost *.c,*.cpp call s:syntastic()
augroup END
function! s:syntastic()
  SyntasticCheck
  call lightline#update()
endfunction

let g:unite_force_overwrite_statusline = 0
let g:vimfiler_force_overwrite_statusline = 0
let g:vimshell_force_overwrite_statusline = 0

"-=-=-= INDENT GUIDES =-=-=-

" Tell indent-guides plugin to start showing guides at 2 levels of indentation.
let g:indent_guides_start_level = 1

" Tell indent-guides plugin to draw guides one character in width.
let g:indent_guides_guide_size = 4

" Tell indent-guides to startup with VIM.
let g:indent_guides_enable_on_vim_startup = 1

" Set background colors manually since I rarely change my color scheme.
let g:indent_guides_auto_colors = 0
autocmd VimEnter,Colorscheme * :hi IndentGuidesOdd ctermbg=237
autocmd VimEnter,Colorscheme * :hi IndentGuidesEven ctermbg=236

"-=-=-= NERDTree =-=-=-

" Ctrl+n will toggle NERDTree window.
noremap <C-n> :NERDTreeToggle<CR>

" Open NERDTree window at startup if no file is open.
"autocmd vimenter * if !argc() | NERDTree | endif

" Close VIM if NERDTree is the only window left open.
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif

"*******************************************************




set guifont=Droid\ Sans\ Mono\ for\ Powerline\ 10

" map control-backspace to delete the previous word
imap <C-BS> <C-W>



set smartindent


let CoVim_default_name = "Niles"
let CoVim_default_port = "8802"  

" Map backslash + backslash to last file
nnoremap <leader><leader> <c-^>


" Stolen from Gary Bernheart, destroyallsoftware.com - educational talks and
" videos
""""""""""""""""""""""""""""""""""""""""""""""""""""
" MULTIPURPOSE TAB KEY
" Indent if we're at the beginning of a line. Else, do completion.
""""""""""""""""""""""""""""""""""""""""""""""""""""
function! InsertTabWrapper()
    let col = col('.') - 1
    if !col || getline('.')[col - 1] !~ '\k'
            return "\<tab>"
    else
        return "\<C-P>"
	endif
endfunction
inoremap <expr> <tab> InsertTabWrapper()
inoremap <s-tab> <c-n>

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" RemoveFancyCharacters COMMAND
" Remove smart quotes, etc.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! RemoveFancyCharacters()
    let typo = {}
    let typo["“"] = '"'
    let typo["”"] = '"'
    let typo["‘"] = "'"
    let typo["’"] = "'"
    let typo["–"] = '--'
    let typo["—"] = '---'
    let typo["…"] = '...'
    :exe ":%s/".join(keys(typo), '\|').'/\=typo[submatch(0)]/ge'
endfunction
command! RemoveFancyCharacters :call RemoveFancyCharacters()


filetype plugin on
au FileType html,xhtml setl ofu=htmlcomplete#CompleteTags
au FileType css setl ofu=csscomplete#CompleteCSS

" Set pastetoggle to F5
" So you can paste things without it going berserk
set pastetoggle=<F5>

" Fixes tmux
set t_ut=
" Map control + T to new tab
map <C-t> :tabnew<CR>
" Map (not in insert mode) Control+W to close a tab
noremap <C-w> :tabclose<CR>
" These two work for gvim, not so much for in the terminal
" Map control + Tab to next tab
map <C-Tab> gt
" Map control + shift + tab to last tab
map <C-S-Tab> gT

nnoremap  :tabprevious<CR>
nnoremap  :tabnext<CR>
nnoremap <C-Left> :tabprevious<CR>
nnoremap <C-Right> :tabnext<CR>

" The theme shows the current mode, no need to display it twice
set noshowmode

" Yanking and pasting will always use the X11 clipboard
set clipboard=unnamedplus

nmap <Tab> :tabnext<CR>
nmap  :tabprev<CR>