" plugins (vim-plug)
call plug#begin('~/.config/nvim/plugged')
Plug 'sheerun/vim-polyglot'                                                 " Many languages syntax support. Should be on top to be overwritten by pandoc
Plug 'tpope/vim-sensible'                                                   " Default sensible settings
Plug 'vim-pandoc/vim-pandoc'                                                " Pandoc support 
Plug 'vim-pandoc/vim-pandoc-syntax'                                         " Markdown syntax support 
Plug 'iamcco/markdown-preview.nvim', { 'do': 'cd app & yarn install'  }     " Markdown preview
Plug 'jakewvincent/mkdnflow.nvim'                                           " Create, follow, display links in a directory of md files
Plug 'dhruvasagar/vim-table-mode', { 'on': 'TableModeEnable' }              " Helper for table in markdown
Plug 'junegunn/goyo.vim', { 'on': 'Goyo' }                                  " Distraction free mode for writing
Plug 'junegunn/limelight.vim', { 'on': 'Goyo' }                             " Dime the color of the text that is not being updated
Plug 'lervag/vimtex'                                                        " Filetype and syntax plugin for LaTeX files
Plug 'dpelle/vim-Grammalecte'                                               " French ortho/grammar spelling
Plug 'arcticicestudio/nord-vim'                                             " Nord color scheme
Plug 'sonph/onehalf', { 'rtp': 'vim' }                                      " OneHalf color scheme
Plug 'sainnhe/edge'                                                         " Edge color schemes
Plug 'vim-airline/vim-airline'                                              " Fancy bottom line in vim/neovim
Plug 'vim-airline/vim-airline-themes'                                       " Themes for vim-airlines
Plug 'jiangmiao/auto-pairs'                                                 " Pairs autocomplete
Plug 'tpope/vim-surround'                                                   " To manipulate surroundings
Plug 'tpope/vim-unimpaired'                                                 " Toggle shortcut
Plug 'tpope/vim-commentary'                                                 " Easy commenting
Plug 'tpope/vim-repeat'                                                      " Add repeat support for plugin mapping
Plug 'osyo-manga/vim-over', { 'on': 'OverCommandLine' }                     " Search Multiple Highlighting
Plug 'scrooloose/nerdtree'                                                  " Side window files navigation
Plug 'tpope/vim-fugitive'                                                   " Git commands, useful for other plugins such as nerdtree or fzf
Plug 'Xuyuanp/nerdtree-git-plugin'                                          " To see new or modified files in the nerdtree window
Plug 'https://github.com/editorconfig/editorconfig-vim'                     " Support of '.editorconfig' files
Plug 'shmargum/vim-sass-colors'                                             " Highlight sass/scss/less/css colors and color variables
" Auto completion
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'pappasam/coc-jedi', { 'do': 'yarn install --frozen-lockfile && yarn build' }      "Python, using jedi
Plug 'stsewd/isort.nvim', { 'do': ':UpdateRemotePlugins'  }
Plug 'vitalk/vim-simple-todo'                                               " Allow to manage todo list easily
" Search
Plug 'jremmen/vim-ripgrep'                                                  " Use ripgrep as vimgrep
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }                         " Fuzzy search, ensure fzf is fresh installed
Plug 'junegunn/fzf.vim'                                                     " fzf for vim/neovim
Plug 'stsewd/fzf-checkout.vim'                                              " Fuzzy search in git branches
Plug 'ryanoasis/vim-devicons'                                               " Add icons to plugins
Plug 'chrisbra/csv.vim'                                                     " To diplay and manage CSV files
Plug 'akinsho/toggleterm.nvim', {'tag' : '2.*'}
call plug#end()

" Format indentation
if has("autocmd")
  filetype plugin indent on
endif

" add some tags for html indentations
let g:html_indent_inctags="html,body,head,tbody"

set smartindent
set tabstop=4
set expandtab
set softtabstop=4
set shiftwidth=4
set showcmd                                                                 " Show (partial) command in status line.
set showmode                                                                " Show indication of having changed modes
set showmatch                                                               " Show matching brackets.
set ignorecase                                                              " Do case insensitive matching
set smartcase                                                               " Do smart case matching
let g:rg_highlight='true'                                                   " Activate ripgrep Highlighting
nnoremap <silent> <C-l> :nohlsearch<CR><C-l>                                " set C-l to :nohlsearch
set autowrite                                                               " Automatically save before commands like :next and :make
set hidden                                                                  " Hide buffers when they are abandoned
set mouse=a                                                                 " Enable mouse usage (all modes)
set linebreak                                                               " Line wrap
set tw=79                                                                   " Lines longer than 79 chars will be wrapped
autocmd FileType gitcommit set textwidth=72                                 " Wrap lines longer than 72 chars for git messages
set colorcolumn=+1                                                          " Colors the tw+1 column
autocmd FileType gitcommit set colorcolumn+=51                              " Add a colored column at 51 chars for git message titles
set number	                                                                " Line numbering
set cursorline                                                              " Color the cursor line
set modeline                                                                " Support modelines
set termguicolors

" Do not keep history when opening files on autofs mounted directories
set shada+=r/home/igor/net

" Terminal buffer options
" Start terminal buffer without line numbering
au TermOpen * setlocal listchars= nonumber norelativenumber

" Spelling activated, by default for French and English
set spell
set spelllang=fr,en
" Specific spelling configuration for git commit messages
autocmd FileType gitcommit setlocal spell
autocmd FileType gitcommit setlocal spelllang=en
" Path for grammalecte-cli to get grammar check in French
let g:grammalecte_cli_py='/usr/bin/grammalecte-cli'

" #########################################
" #########################################
" Status line options 
set statusline^=%{coc#status()}

" #########################################
" #########################################
" Fold
set foldmethod=syntax
set foldlevel=1

" #########################################
" #########################################
" Default filetype configuration 

" Markdown
autocmd FileType pandoc set tabstop=2
autocmd FileType pandoc set softtabstop=2
autocmd FileType pandoc set shiftwidth=2

" JSON
" Consider `.jsonld` as JSON
autocmd BufNewFile,BufRead *.jsonld set filetype=json
autocmd FileType json setlocal foldmethod=syntax
autocmd FileType json set foldlevel=2
autocmd FileType json set tabstop=2
autocmd FileType json set softtabstop=2
au FileType json set shiftwidth=2

" HTML 
autocmd FileType html set tabstop=2
autocmd FileType html set softtabstop=2
autocmd FileType html set shiftwidth=2
au FileType xml setlocal foldmethod=indent
autocmd FileType xml set foldlevel=2

" XML 
let g:xml_syntax_folding=3
au FileType xml setlocal foldmethod=syntax
autocmd FileType xml set foldlevel=1

" Use the system clipboard
set clipboard+=unnamedplus

" Airline
let g:airline_powerline_fonts=1
let g:airline#extensions#wordcount#filetypes='pandoc\|text\|'                   "Add support when pandoc is activated
let g:airline_theme='edge'

" Vim-table-mode. Set the table separator
let g:table_mode_corner='|'

" NERDTree. By default, NERDTree is open when no file is provided when launching vim/neovim
" autocmd StdinReadPre * let s:std_in=1
" autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif
let g:NERDTreeWinSize=40

" vim-json, don't conceal
let g:vim_json_syntax_conceal=0

" Pandoc
" Autoformatting with hardwrap
let g:pandoc#formatting#mode="hA"
" ctrl+s switch to softwrap
nnoremap <C-s> :call pandoc#formatting#UseSoftWraps()
" ctrl+h switch to hardwrap
nnoremap <C-h> :call pandoc#formatting#UseHardWraps()
" ctrl+t toggle autoformat (mainly to deactivate it when necessary)
nnoremap <C-t> :call pandoc#formatting#ToggleAutoformat()
let g:mkdp_filetypes = ['markdown', 'pandoc', 'pandoc.markdown']

" #########################################
" #########################################
" autocompletion, mainly coc configuration
" as inspired from the project README

" Give more space for displaying messages
set cmdheight=2
" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience
set updatetime=300

" Always show the signcolumn, otherwise it would shift the text each time
" diagnostics appear/become resolved.
if has("patch-8.1.1564")
  " Recently vim can merge signcolumn and number column into one
  set signcolumn=number
else
  set signcolumn=yes
endif

" Use `[g` and `]g` to navigate diagnostics
" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list.
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" GoTo code navigation.
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)

" Use K to show documentation in preview window.
nnoremap <silent> K :call <SID>show_documentation()<CR>

function! s:show_documentation()
  if (index(['vim','help'], &filetype) >= 0)
    execute 'h '.expand('<cword>')
  elseif (coc#rpc#ready())
    call CocActionAsync('doHover')
  else
    execute '!' . &keywordprg . " " . expand('<cword>')
  endif
endfunction

" Install missing coc extensions
let g:coc_global_extensions = ['coc-html', 'coc-json', 'coc-css', 'coc-markdownlint', 'coc-git', 'coc-vimtex', 'coc-yaml', 'coc-esbonio'] 
autocmd FileType scss setl iskeyword+=@-@                                   " Add @ to iskeyword option
let g:coc_filetype_map = { 'pandoc': 'markdown' }                           " Allow markdownlint to recognized pandoc filetype

" Set the Semantic Menu highlight group
hi CocMenuSel ctermbg=252

" #########################################
" #########################################
" Python provider in a pyenv
let g:python3_host_prog='$HOME/.pyenv/versions/neovim3/bin/python'

" Imports sorting
let g:isort_command='isort'

" #########################################
" #########################################
" Vimtex configuration
let g:vimtex_compiler_method = 'tectonic'
let g:vimtex_compiler_tectonic = {}

" #########################################
" #########################################
" Key bindings for FZF
nnoremap <leader>gf :GFiles<CR>
nnoremap <leader>gs :GFiles?<CR>
nnoremap <leader>h :History<CR>
nnoremap <leader>hc :History:<CR>
nnoremap <leader>hs :History/<CR>
nnoremap <leader>l :Lines<CR>
nnoremap <leader>bl :BLines<CR>
nnoremap <leader>c :Commits<CR>
nnoremap <leader>bc :BCommits<CR>
nnoremap <leader>? :Helptags<CR>

" #########################################
" #########################################
let g:goyo_width=85

" Integrate Limelight into Goyo
autocmd! User GoyoEnter Limelight
autocmd! User GoyoLeave Limelight!

" #########################################
" #########################################
" Syntax coloration and color theme
syntax enable
set background=dark
" let g:edge_style = "light"
colorscheme nord

" #########################################
" #########################################
" Snippets
autocmd BufNewFile *.html 0r ~/.config/nvim/snippets/boilerplate.html
autocmd BufNewFile *.md 0r ~/.config/nvim/snippets/template.md

" #########################################
" #########################################
" Terminal: use zsh
set shell=/usr/bin/zsh
lua require("toggleterm").setup()

" #########################################
" #########################################
" mkdnflow configuration
lua <<EOF
require('mkdnflow').setup({
    -- Config goes here; leave blank for defaults
    links = {
        conceal = true 
        },
    modules = {
        folds = false,
        lists = false,
        tables = false
        -- TODO: evaluate if it could replace vim-table
        }
})
EOF
