" This line should not be removed as it ensures that various options are
" properly set to work with the Vim-related packages.
runtime! archlinux.vim

" If you prefer the old-style vim functionalty, add 'runtime! vimrc_example.vim'
" Or better yet, read /usr/share/vim/vim80/vimrc_example.vim or the vim manual
" and configure vim to your own liking!

" Syntax highlighting
syntax on
set background=dark
let g:solarized_termcolors = 16
let g:solarized_hitrail=1
colorscheme solarized
if !empty($TMUX)
  set termguicolors
endif

" have Vim load indentation rules and plugins
" according to the detected filetype.
if has("autocmd")
  filetype plugin indent on
endif

set shell=fish
set showcmd            " Show (partial) command in status line.
set showmatch           " Show matching brackets.
set hlsearch
set ignorecase         " Do case insensitive matching
set smartcase          " Do smart case matching
set incsearch          " Incremental search
"set autowrite          " Automatically save before commands like :next and :make
set hidden             " Hide buffers when they are abandoned
set mouse=a
set number
set relativenumber
set expandtab       "Use softtabstop spaces instead of tab characters for indentation
set shiftwidth=4    "Indent by 4 spaces when using >>, <<, == etc.
set softtabstop=4   "Indent by 4 spaces when pressing <TAB>
set tabstop=4
set autoindent      "Keep indentation from previous line
set smartindent     "Automatically inserts indentation in some cases
set nowrap
set laststatus=2
let mapleader = ","
set backupdir=~/.vim/backup//
set directory=~/.vim/swap//
set undodir=~/.vim/undo//
set splitright
set cursorline
set concealcursor=nc

" flag lines wider than 80 char
highlight ColorColumn ctermbg=magenta
call matchadd('ColorColumn', '\%81v', 100)


if has("autocmd")

  autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab
  autocmd FileType html setlocal ts=2 sts=2 sw=2 expandtab
  autocmd FileType gohtmltmpl setlocal ts=2 sts=2 sw=2 expandtab
  autocmd FileType css setlocal ts=2 sts=2 sw=2 expandtab
  autocmd FileType javascript setlocal ts=2 sts=2 sw=2 expandtab
  autocmd FileType html.handlebars setlocal ts=2 sts=2 sw=2 expandtab
  autocmd FileType xml setlocal ts=2 sts=2 sw=2 expandtab
  autocmd FileType go setlocal ts=4 sts=4 sw=4 noexpandtab
  autocmd FileType rst setlocal tw=80 ts=3 sts=3 sw=3 expandtab
  autocmd FileType gitcommit setlocal tw=80 ts=2 sts=2 sw=2 expandtab
  autocmd FileType md setlocal tw=80 ts=2 sts=2 sw=2 expandtab
  autocmd FileType vimwiki setlocal tw=80 ts=2 sts=2 sw=2 expandtab
  autocmd FileType sh setlocal tw=80 ts=2 sts=2 sw=2 expandtab
  autocmd FileType java setlocal tw=80 ts=2 sts=2 sw=2 expandtab

  autocmd BufNewFile,BufRead neomutt-* set spell spelllang=fr
endif

if executable('rg')
	set grepprg=rg\ --vimgrep\ --hidden\ --glob\ '!.git'
endif

" Airline options
let g:airline_powerline_fonts = 1
let g:airline_theme='solarized'
let g:airline#extensions#tabline#enabled = 1

" NERDTree options
" Automatically opens NERDTree
" autocmd vimenter * NERDTree

" Close NERDTree if it is the last window
" autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif

" Vim-go options
"let g:go_fmt_command = "goimports"
let g:go_fmt_command = "gopls"
let g:go_imports_mode = 'gopls'
let g:go_fmt_autosave = 1

" gopls settings
let g:go_gopls_gofumpt = 1
let g:go_gopls_staticcheck = 1
let g:go_gopls_analyses = 1
let g:go_gopls_complete_unimported = 1
let g:go_gopls_matcher = 'fuzzy'
let g:go_gopls_use_placeholders = 1

let g:go_metalinter_enabled = ['govet', 'golint', 'errcheck', 'staticcheck', 'gosimple', 'structcheck', 'varcheck', 'ineffassign', 'deadcode', 'gosec', 'unconvert', 'dupl', 'goconst', 'gocyclo', 'misspell', 'unparam', 'lll', 'interfacer', 'nakedret', 'scopelint']
let g:go_metalinter_autosave = 0
"let g:go_metalinter_autosave_enabled = ['govet', 'golint', 'errcheck']
let g:go_metalinter_autosave_enabled = ['govet', 'golint', 'errcheck', 'staticcheck', 'gosimple', 'structcheck', 'varcheck', 'ineffassign', 'deadcode', 'gosec', 'unconvert', 'dupl', 'goconst', 'gocyclo', 'misspell', 'unparam', 'lll', 'interfacer', 'nakedret', 'scopelint']
let g:go_list_type = "quickfix"
let g:go_highlight_functions = 1
let g:go_highlight_function_parameters = 1
let g:go_highlight_function_calls = 1
let g:go_highlight_methods = 1
let g:go_highlight_fields = 1
let g:go_highlight_types = 1
let g:go_highlight_operators = 1
let g:go_highlight_build_constraints = 1
let g:go_highlight_generate_tags = 1
let g:go_highlight_extra_types = 1
let g:go_highlight_array_whitespace_error = 1
let g:go_highlight_chan_whitespace_error = 1
let g:go_highlight_space_tab_error = 1
let g:go_highlight_trailing_whitespace_error = 1
let g:go_highlight_variable_declarations = 1
let g:go_doc_popup_window=1
let g:go_def_mapping_enabled = 0
let g:go_doc_keywordprg_enabled = 0
let g:go_code_completion_enabled = 0
let g:go_gopls_use_placeholders = 1
let g:go_gopls_complete_unimported = 1
let g:go_test_show_name = 1
let g:go_test_timeout= '60s'
let g:go_auto_type_info = 1
let g:go_jump_to_error = 0
let g:go_auto_sameids = 1

" vimwiki options
let g:vimwiki_list = [{'path': '~/Notebook', 
                      \ 'auto_toc': 1, 
                      \ 'index': 'main',
                      \ 'ext': '.md',
                      \ 'syntax': 'markdown'}]
let g:vimwiki_ext2syntax = {'.md': 'markdown'}

" Grammalecte options
let g:grammalecte_cli_py='/usr/bin/grammalecte'

" IndentLine options
let g:indentLine_char = '▏'
"let g:indentLine_setColors = 0

" CoC options

" ALE options
let g:ale_completion_enabled = 0
let g:ale_open_list = 1
let g:ale_linters = {
\ 'go': ['gofmt', 'gopls', 'golangci-lint']
\}
let g:ale_go_golangci_lint_options = ''
let g:ale_go_golangci_lint_executable = 'golangci-lintw'
let g:ale_go_gopls_options = "-remote=auto"
let g:ale_fix_on_save = 0
let g:ale_sign_error = '🔴'
let g:ale_sign_info = '🔵'
let g:ale_sign_warning = '🟡'

" Minisnip options
let g:minisnip_trigger = '<C-w>'

" floatterm options
let g:floaterm_position = 'center'
let g:floaterm_open_in_root = v:true
let g:floaterm_autoinsert = v:false
hi FloatermNF guibg=black
hi FloatermBorderNF guibg=black guifg=green

call plug#begin('~/.vim/plugged')

    Plug 'glacambre/firenvim', { 'do': { _ -> firenvim#install(0) } }
    Plug 'voldikss/vim-floaterm'

    Plug 'scrooloose/nerdtree'
    Plug 'xuyuanp/nerdtree-git-plugin'

    Plug 'vim-airline/vim-airline'
    Plug 'vim-airline/vim-airline-themes'

    Plug 'airblade/vim-gitgutter'
    Plug 'tpope/vim-fugitive'
    Plug 'jreybert/vimagit'

    Plug 'fatih/vim-go'
    Plug 'joukevandermaas/vim-ember-hbs'
    Plug 'dag/vim-fish'
    Plug 'glench/vim-jinja2-syntax'
    Plug 'mattn/emmet-vim'
    Plug 'ollykel/v-vim'

    Plug 'liuchengxu/vim-clap', { 'do': { -> clap#installer#force_download() } }
    Plug 'dense-analysis/ale'
    Plug 'joereynolds/vim-minisnip'

    Plug 'neoclide/coc.nvim', {'branch': 'release'}
    Plug 'nullvoxpopuli/coc-ember', {'do': 'yarn install --frozen-lockfile'}
    Plug 'neoclide/coc-tsserver', {'do': 'yarn install --frozen-lockfile'}
    Plug 'neoclide/coc-html', {'do': 'yarn install --frozen-lockfile'}
    Plug 'neoclide/coc-css', {'do': 'yarn install --frozen-lockfile'}
    Plug 'neoclide/coc-java', {'do': 'yarn install --frozen-lockfile'}
    Plug 'neoclide/coc-snippets', {'do': 'yarn install --frozen-lockfile'}

    Plug 'aklt/plantuml-syntax'
    Plug 'scrooloose/vim-slumlord'

    Plug 'vimwiki/vimwiki'
    Plug 'dpelle/vim-Grammalecte'
    Plug 'Yggdroot/indentLine'
    Plug 'michaeljsmith/vim-indent-object'
    Plug 'altercation/vim-colors-solarized'

call plug#end()

""
"" Notebook
""

nmap <silent> <space>w<space>w :call mkdir(strftime("diary/%Y/%m"), "p", 0755) \| exec "edit " . strftime("diary/%Y/%m/%Y-%m-%d.md")<CR>
nmap <silent> <space>dt :execute ":normal! a" . strftime("%H:%M ")<CR>
nmap <silent> <space>dn :execute ":normal! o* " . strftime("%H:%M ")<CR>

""
"" Keymappings
""

" Removes trailing whitespaces
nnoremap <leader>s :keeppattern %s/\s\+$//<CR>

" move lines around
nnoremap <A-Down> :m .+1<CR>==
nnoremap <A-Up> :m .-2<CR>==
inoremap <A-Down> <Esc>:m .+1<CR>==gi
inoremap <A-Up> <Esc>:m .-2<CR>==gi
vnoremap <A-Down> :m '>+1<CR>gv=gv
vnoremap <A-Up> :m '<-2<CR>gv=gv

" Quickfix and location lists key mappings
nmap <space>cf :cfirst<CR>
nmap <space>cn :cnext<CR>
nmap <space>cp :cprevious<CR>
nmap <space>co :copen<CR>
nmap <space>cc :cexpr [] \| cclose<CR>
nmap <space>lf :lfirst<CR>
nmap <space>ln :lnext<CR>
nmap <space>lp :lprevious<CR>
nmap <space>lo :lopen<CR>
nmap <space>lc :lclose<CR>

autocmd BufNewFile,BufRead *.tmpl set syntax=gohtmltmpl 

" Easier to exit terminal insert mode with Esc
tnoremap <Esc> <C-\><C-n>


" Nerdtree mappings
map <C-n> :NERDTreeToggle<CR>
nmap <leader>N :NERDTreeFocus<CR>

" Coc mappings
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)
nmap <silent> go :CocList outline<CR>

nnoremap <silent> K :call <SID>show_documentation()<CR>
nmap <leader>rn <Plug>(coc-rename)

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

" Use tab for trigger completion with characters ahead and navigate.
inoremap <silent><expr> <TAB>
      \ pumvisible() ? coc#_select_confirm() :
      \ coc#expandableOrJumpable() ? "\<C-r>=coc#rpc#request('doKeymap', ['snippets-expand-jump',''])\<CR>" :
      \ <SID>check_back_space() ? "\<TAB>" :
      \ coc#refresh()

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

let g:coc_snippet_next = '<tab>'

" Use <cr> to confirm completion, `<C-g>u` means break undo chain at current
" position. Coc only does snippet and additional edit on confirm.
if has('patch8.1.1068')
  " Use `complete_info` if your (Neo)Vim version supports it.
  inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm() : 
                                           \"\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
else
  imap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
endif


" Clap mappings
nmap <C-p> :Clap files<CR>
nmap <C-p>b :Clap buffers<CR>
nmap <C-p>r :Clap grep<CR>


" Floaterm mappings
nmap <space>tt :FloatermToggle<CR>
nmap <space>tn :FloatermNext<CR>
nmap <space>tp :FloatermPrev<CR>
nmap <space>tl :FloatermNew lazygit<CR>


nmap <leader>MM :tabnew \| MagitOnly<CR>

if has("autocmd")
    autocmd FileType go nmap <leader>b  <Plug>(go-build)
    autocmd FileType go nmap <leader>r  <Plug>(go-run)
    autocmd FileType go nmap <leader>t  <Plug>(go-test)
    autocmd FileType go nmap <leader>T  <Plug>(go-test-func)
    autocmd FileType go nmap <leader>c  <Plug>(go-coverage)
    autocmd FileType go nmap <leader>cc  <Plug>(go-coverage-clear)
    autocmd FileType go nmap <leader>a  <Plug>(go-alternate-edit)
    autocmd FileType go nmap <leader>f  <Plug>(go-fmt)
    autocmd FileType go nmap <leader>d  <Plug>(go-def)
    autocmd FileType go nmap <leader>m  <Plug>(go-metalinter)
    autocmd FileType go let b:go_fmt_options = {
    \ 'goimports': '-local ' .
      \ trim(system('cd '. shellescape(expand('%:h')) .' && go list -m;')),
    \ }
endif

nmap <space>w :cexpr [] \| cclose \| w<CR>
nmap <C-b> :b#<CR>
nmap <C-w>M <C-w>_<C-w><BAR>
nmap <C-w>m <C-w>=
