" vim:foldmethod=marker:foldlevel=0

set viminfo+=n~/.vim/viminfo

" Basic configuration {{{

if &compatible
	set nocompatible
	set modelines=1
endif

" }}}

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

" Completion engines {{{
"Plug 'Valloric/YouCompleteMe'
"Plug 'zxqfl/tabnine-vim'
"Plug 'lifepillar/vim-mucomplete'
"Plug 'Shougo/neocomplete.vim'
"Plug 'lyuts/vim-rtags'
"Plug 'JBakamovic/cxxd-vim'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'jackguo380/vim-lsp-cxx-highlight'
" }}}

" Mappings {{{
"Plug 'milkypostman/vim-togglelist' " Map of quickfix toggles
" }}}

" Code development helpers {{{
"Plug 'rhysd/vim-clang-format'
Plug 'tpope/vim-commentary' " Toggle C style comments with gc
"Plug 'KabbAmine/zeavim.vim' " gz to open zeal
Plug 'mbbill/undotree'
"Plug 'kkoomen/vim-doge'
Plug 'SirVer/ultisnips'
Plug 'honza/vim-snippets'
Plug 'wellle/context.vim'
Plug 'svermeulen/vim-yoink'
Plug 'will133/vim-dirdiff'
"Plug 'n0v1c3/vira'
" }}}

" Files switch, jump and grep-like tools {{{
"Plug 'ericcurtin/CurtineIncSw.vim' "Toggle .c .h files
Plug 'preservim/nerdtree'
Plug 'Xuyuanp/nerdtree-git-plugin'
"Plug 'mileszs/ack.vim' " Ack integration
Plug 'junegunn/fzf.vim'
"Plug 'fholgado/minibufexpl.vim'
Plug 'ludovicchabant/vim-gutentags' "Auto generate tags
Plug 'liuchengxu/vista.vim'
Plug 'wellle/targets.vim'
Plug 'inside/vim-search-pulse'
" }}}

" Git integration {{{
Plug 'mhinz/vim-signify' " Mark edited lines - faster gitgutter
"Plug 'rhysd/git-messenger.vim' " show git history
"Plug 'tpope/vim-fugitive' " Git integration
" }}}

" Syntax for random filetypes {{{
"Plug 'gabrielelana/vim-markdown'
Plug 'kergoth/vim-bitbake' " Bitbake templates and syntax
"Plug 'vim-scripts/DoxygenToolkit.vim' " Doxygen support
Plug 'pboettch/vim-cmake-syntax'
Plug 'aklt/plantuml-syntax'
Plug 'vim-pandoc/vim-pandoc-syntax'
" }}}

" Colorschemes {{{
"Plug 'flazz/vim-colorschemes' " lots of colorschemes
"Plug 'jeaye/color_coded'
"Plug 'thiagoalessio/rainbow_levels.vim'
"Plug 'fielding/vice'
"Plug 'whatyouhide/vim-gotham'
"Plug 'chuling/ci_dark'
"Plug 'adrian5/oceanic-next-vim'
"Black and white:
"Plug 'ewilazarus/preto'
Plug 'andreasvc/vim-256noir'
" }}}

" Other plugins (external tools, etc) {{{
Plug 'junegunn/goyo.vim'
Plug 'jez/vim-superman' "vman application
Plug 'vimwiki/vimwiki'
"Plug 'metakirby5/codi.vim' " live coding
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'mhinz/vim-startify'
Plug 'vim-pandoc/vim-pandoc'
" }}}

call plug#end()            " required

" Packages {{{
"packadd termdebug
" }}}

" }}}

" TAB settings {{{

set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab

" }}}

" More Common Settings {{{

set encoding=utf-8
set scrolloff=10
set autoindent
set cino=l1,:0
set showmode
set showcmd
" do not force write on buffer switch
set hidden
" set visualbell
set nowrapscan

set cursorline
set ttyfast
set lazyredraw
set ruler
set backspace=eol,indent,start
" statusline {{{
set statusline=%<%f%h%m%r%=%b\ 0x%B\ \ %l,%c%V\ %P
set laststatus=2
" Vista configuration
function! NearestMethodOrFunction() abort
	return get(b:, 'vista_nearest_method_or_function', '')
endfunction

set statusline+=\  "comment to remove trailing space
set statusline+=%{NearestMethodOrFunction()}
" }}}
set number
set relativenumber
" Make Vim to handle long lines nicely.
set wrap
set textwidth=79
set formatoptions=cqrnb1j

syntax on

set showmatch
"set matchtime=3
"Control it with %/s///i - ignore and I - sens
set ignorecase
set smartcase
" %s///g not needed
set gdefault
set hlsearch
set incsearch

set shell=/bin/bash
set path+=**
set updatetime=100
set nospell
set runtimepath+=/usr/share/vim/vimfiles
set spelllang=en
" Dictionary path, from which the words are being looked up.
set dictionary+=/usr/share/dict/words
set clipboard=unnamed

" }}}

" Undofile {{{

if exists("+undofile")
	if isdirectory($HOME . '/.vim/undo') == 0
		:silent !mkdir -p ~/.vim/undo > /dev/null 2>&1
	endif
	set undodir=~/.vim/undo/
	set undofile
endif

" }}}

" Ctags {{{
if isdirectory($HOME . '/.vim/tags') == 0
	:silent !mkdir -p ~/.vim/tags > /dev/null 2>&1
endif
let g:gutentags_cache_dir='~/.vim/tags'
"let g:gutentags_ctags_extra_args=['--fields=+l']
" }}}

" Mappings {{{
" Editing {{{
"Changing Leader Key
let mapleader = "\\"

"nnoremap j gj
"nnoremap k gk

" Get Rid of stupid Goddamned help keys
inoremap <F1> <ESC>
nnoremap <F1> <ESC>
vnoremap <F1> <ESC>
" jj For Quicker Escaping between normal and editing mode
inoremap jj <ESC>
inoremap jk <ESC>
inoremap :w<CR> <Esc>:w<CR>i

" space one line, home,end globally increase/decrease
nnoremap <space><space> za
nnoremap <Home> zm
nnoremap <End> zr

" Map : to ; also in command mode
"nnoremap ; :

" Reselect visual block after incrementing/decrementing
vnoremap <c-a> <c-a>gv
vnoremap <c-x> <c-x>gv

nnoremap <leader>2 <esc>:set tabstop=2 softtabstop=2 shiftwidth=2<cr>
nnoremap <leader>4 <esc>:set tabstop=4 softtabstop=4 shiftwidth=4<cr>
nnoremap <leader>8 <esc>:set tabstop=8 softtabstop=8 shiftwidth=8<cr>

map <F12> :colorscheme random<CR>

nnoremap S :%s//g<LEFT><LEFT>
xnoremap S :s//g<LEFT><LEFT>
xmap <BS> x

" Make pasting done without any indentation break
set pastetoggle=<F3>

" leader Command to remove white space from a file
""nnoremap <leader>W :%s/\s\+$//<cr>:let @/=''<CR>

" This causes issues with FZF
"tnoremap <Esc> <C-W><C-W>

nnoremap S :%s//g<LEFT><LEFT>
xnoremap S :s//g<LEFT><LEFT>
xmap <BS> x

nnoremap <leader><space> :nohlsearch<cr>

" }}}
" Plugins {{{
inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"

nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

nnoremap <silent> <space>k :call <SID>show_documentation()<CR>

"xmap <leader>f  <Plug>(coc-format-selected)
"nmap <leader>f  <Plug>(coc-format-selected)

" Show all diagnostics
nnoremap <silent> <space>a  :<C-u>CocList diagnostics<cr>
" Manage extensions
nnoremap <silent> <space>e  :<C-u>CocList extensions<cr>
" Show commands
nnoremap <silent> <space>c  :<C-u>CocList commands<cr>
" Find symbol of current document
nnoremap <silent> <space>o  :<C-u>CocList outline<cr>
" Search workspace symbols
nnoremap <silent> <space>s  :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent> <space>j  :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent> <space>k  :<C-u>CocPrev<CR>
" Resume latest coc list
nnoremap <silent> <space>p  :<C-u>CocListResume<CR>

let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<CR>"
let g:UltiSnipsJumpBackwardTrigger="<leader>p"

" yoink configuration
nmap <leader>yp <plug>(YoinkPostPasteSwapBack)
nmap <leader>yn <plug>(YoinkPostPasteSwapForward)
nmap p <plug>(YoinkPaste_p)
nmap P <plug>(YoinkPaste_P)

" Mapping to NERDTree
nnoremap <leader>t :NERDTreeToggle<CR>
let NERDTreeIgnore=['\.vim$', '\~$', '\.pyc$']
"nnoremap <C-n> :e .<CR>
"let g:netrw_banner=0
"let g:netrw_wisize=20
"let g:netrw_liststyle=3
"let g:netrw_lolcalrmdir='rm -r'
"nnoremap <leader>n :Lexplore<CR>

" Tagbar key bindings."
"nmap <leader>t :TlistToggle<cr>

nnoremap <leader>ff :FZF!<CR>
nnoremap <leader>fl :Lines!<CR>
nnoremap <leader>fb :Buffers<CR>
inoremap <leader>fs <ESC>:Snippets!<CR>
nnoremap <leader>fa :Ag! <C-R><C-W><CR>

" Disable context.vim on json files
let g:context_filetype_blacklist = ["json"]

" }}}
" }}}

" Wildmenu completion {{{
set wildmenu
set wildmode=list:longest
set wildignore+=.hg,.git,.svn " Version Controls"
set wildignore+=*.aux,*.out,*.toc "Latex Indermediate files"
set wildignore+=*.jpg,*.bmp,*.gif,*.png,*.jpeg "Binary Imgs"
set wildignore+=*.o,*.obj,*.exe,*.dll,*.manifest "Compiled Object files"
set wildignore+=*.spl "Compiled spelling world list"
set wildignore+=*.sw? "Vim swap files"
set wildignore+=*.DS_Store "OSX SHIT"
set wildignore+=*.luac "Lua byte code"
set wildignore+=migrations "Django migrations"
set wildignore+=*.pyc "Python Object codes"
set wildignore+=*.orig "Merge resolution files"
" }}}

match Error /\s\+$\|DU\cPA/

" Removing scrollbars
if !has("gui_running")
	set background=dark
	colorscheme 256_noir
	" To show special characters in Vim
	set listchars=tab:▸\ ,trail:¬
	set list
	hi clear SpellBad
	hi SpellBad cterm=underline
	"hi Normal ctermbg=None
endif

if &term =~ '256color'
	" Disable Background Color Erase (BCE) so that color schemes
	" work properly when Vim is used inside tmux and GNU screen.
	" set t_ut=
endif

" Mini Buffer some settigns."
let g:miniBufExplMapWindowNavVim = 1
let g:miniBufExplMapWindowNavArrows = 1
let g:miniBufExplMapCTabSwitchBufs = 1
let g:miniBufExplModSelTarget = 1
let g:miniBufExplStatusLineText = ''

"Full line:
"set colorcolumn=120
"call matchadd('ColorColumn', '\%80v', 100)

" autocmd {{{
if has("autocmd")
	"restore cursor position
	autocmd BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif
	autocmd FileType helpfile set nonumber

	autocmd WinLeave * set nocursorline
	autocmd WinEnter * set cursorline

	" Set vim to save the file on focus out
	"au FocusLost * :wa

	" Resize Split When the window is resized
	au VimResized * :wincmd =

	" If you want to show the nearest function in your statusline automatically
	autocmd VimEnter * call vista#RunForNearestMethodOrFunction()
endif
"}}}

" Folding {{{
function! FoldFormat()
	let foldsize = (v:foldend - v:foldstart)
	return getline(v:foldstart)."\t\t\t(".foldsize."\tmore lines)"
endfunction
set foldenable
set foldlevelstart=999
set foldnestmax=5
set foldtext=FoldFormat()
set fillchars=fold:\  " comment just to remove trailing
set foldmethod=syntax
if has('folding')
	setglobal foldopen+=jump
endif

" }}}

function! FindAlternate()
	let l:ext = 'h'
	let l:curr_ext = expand('%:e')
	if (l:curr_ext == 'c')
		let l:ext = 'h'
	elseif (l:curr_ext == 'cpp')
		let l:ext = 'h'
	elseif (l:curr_ext == 'h')
		let l:ext = 'c'
	elseif (l:curr_ext == 'hpp')
		let l:ext = 'cpp'
	endif
	let l:file = expand('%:t:r') . '.' . l:ext
	:exec 'find ' . l:file
endfunction

nnoremap <F6> :call FindAlternate()<CR>
"let g:alternateSearchPath="sfr:../source,sfr:../src,sfr:../include,sfr:../inc,sfr:./Source,sfr:.."
"map <F6> :call CurtineIncSw()<CR>

let g:startify_custom_header = ''

setglobal complete-=i
setglobal virtualedit=block
setglobal shiftround

set shortmess+=c
inoremap <silent><expr> <leader><space> coc#refresh()
set signcolumn=yes
set cmdheight=2
"inoremap <silent><expr> <TAB>
"      \ pumvisible() ? "\<C-n>" :
"      \ <SID>check_back_space() ? "\<TAB>" :
"      \ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"

function! s:check_back_space() abort
	let col = col('.') - 1
	return !col || getline('.')[col - 1]  =~# '\s'
endfunction

function! s:show_documentation()
	if (index(['vim','help'], &filetype) >= 0)
		execute 'h '.expand('<cword>')
	else
		call CocAction('doHover')
	endif
endfunction

autocmd CursorHold * silent call CocActionAsync('highlight')

"hi None ctermbg=None ctermfg=None

let g:vim_search_pulse_mode = 'pattern'
let g:vim_search_pulse_duration = 400

"Taken from 256_noir readme:
set cursorline
highlight CursorLine cterm=NONE ctermfg=NONE ctermbg=233 guifg=NONE guibg=#121212
autocmd InsertEnter * highlight CursorLine cterm=NONE ctermfg=NONE ctermbg=234 guifg=NONE guibg=#1c1c1c
autocmd InsertLeave * highlight CursorLine cterm=NONE ctermfg=NONE ctermbg=233 guifg=NONE guibg=#121212

let g:airline_theme = 'minimalist'
let g:airline_powerline_fonts = 1
let g:airline_stl_path_style = 'short'
let g:airline_highlighting_cache = 1
