" --- see also ---{{{
" /etc/vim/vimrc
" /etc/vim/vimrc.local
" $VIMRUNTIME -> /usr/share/vim/vim<version>
" $VIMRUNTIME/debian.vim
" $VIMRUNTIME/defaults.vim
" https://github.com/upekkha/dotfiles/blob/master/.vimrc
" https://gist.github.com/millermedeiros/1262085
"}}}

" --- general settings ---{{{
" load debian settings from $VIMRUNTIME/debian.vim
runtime! debian.vim

" insert custom path to &runtimepath
let &runtimepath=$ENVRCD_VIM_PATH.','.&runtimepath

syntax on               "enable syntax highlighting
set nocompatible        "use vim defaults instead of 100% vi compatibility
set encoding=utf8       "default file encoding
set ttyfast             "fast terminal
set mouse=              "disable mouse
"set mouse=i             "enable mouse in insert mode
filetype plugin on      "enable filetype plugins
filetype indent on      "automatic indentation according to filetype
"set autoindent          "preserve indentation on new line
set backspace=eol,start,indent  "allow backspace at end of line etc
set showmatch           "show matching parenthesis
"set linebreak           "break line at end of a word
"set textwidth=0         "don't break text after a certain length
set tabstop=4           "show existing tab with 4 spaces width
set shiftwidth=4        "when indenting with '>', use 4 spaces width
set softtabstop=4       "use 4 spaces per tab when editing
set expandtab           "when pressing tab, insert 4 spaces
set smarttab            "use sw at beginning of line, ts otherwise
set incsearch           "incremental search
set wrapscan            "continue search from top when reaching the end
set ignorecase          "search is not case-sensitive
set smartcase           "search case-sensitive for uppercase patterns
set hlsearch            "search pattern highlighting
set magic               "enable extended regexes
"set gdefault            "RegExp global by default (by default adds /g to :s/)
"set spell              "spellchecking
"set spelllang=en       "set spellchecking language to english
set spellsuggest=7      "show 7 suggestions when spellchecking
set nopaste             "fix middlemouse button paste (seems default setting)
set history=999         "increase history (default = 20)
set undolevels=999      "more undo (default=100)
"set autoread            "reload files if changed externally
set nobackup            "toggle keeping ~ backups of files when saving
set swapfile            "use swp file while a file is open
set modeline            "scan first/last lines of file for vim commands
set modelines=5         "number of lines checked for modelines
set display=lastline    "show beginning of broken line at bottom of window instead of displaying @
set clipboard=unnamed   "make all operations such as yy, dd, p work with the clipboard
set wildmenu            "show matches for command-line completion
set wildmode=longest:full,full  "define how tab completion proceeds on partial match
set wildignore+=*.o,*.pdf       "Let tab completion ignore certain file types
set fillchars=fold:-
set t_Co=256            "use 256 colors

" temporary workaround for jessie's old vim version
if v:version >704 || v:version==704 && has('patch710')
  set listchars=eol:¬,tab:>-,trail:~,space:·  "define replacement for invisible characters (set invlist)
endif

" Disable auto-comment after breaking lines with formatoptions
au FileType * setl fo-=c fo-=r fo-=o
"}}}

" --- functions ---{{{
" --- map key to toggle opt ---
function MapToggle(key, opt)
  let cmd = ':set '.a:opt.'! \| set '.a:opt."?\<CR>"
  exec 'nnoremap '.a:key.' '.cmd
  exec 'inoremap '.a:key." \<C-O>".cmd
endfunction
command -nargs=+ MapToggle call MapToggle(<f-args>)

" --- toggle mouse=i on/off ---
function ToggleMouse()
  if (&mouse == 'i') || (&mouse == 'a')
    set mouse=
  else
    set mouse=i
  endif
endfunc

" --- Clean trailing spaces ---
function! CleanSpaces()
    %s/\s\+$//e
endfunction
"}}}

" --- keyboard mappings ---{{{
" --- F key toggles ---
" toggle paste mode (normal/insert)
MapToggle <F2> paste
set pastetoggle=<F2>
" toggle mouse mode (normal/insert)
nnoremap <F3> :call ToggleMouse()<CR>
inoremap <F3> <C-O>:call ToggleMouse()<CR>
" paste text at mouse position (insert)
inoremap <MiddleMouse> <LeftMouse><MiddleMouse>
" toggle list mode (normal/insert)
MapToggle <F4> list

" --- normal mappings ---
" toggle paste mode
MapToggle <Leader>p paste
" set mouse modes
nnoremap <Leader>m :set mouse=<CR>
nnoremap <Leader>mi :set mouse=i<CR>
nnoremap <Leader>ma :set mouse=a<CR>
" toggle list of invisible characters
MapToggle <Leader>w list
" remap space to fold/unfold
map <space> za
" remap \s to toggle spellchecking
map <Leader>s :set invspell<CR>
" remap \n to toggle display of line numbers
map <Leader>n :set invnu<CR>
" remap \h to stop hlsearch until next search
map <Leader>h :noh<CR>
"}}}

" --- colorscheme ---{{{
" colorschemes (color: <scheme> | colorscheme: <scheme>)
" nice:        elflord
" green:       murphy
" green-dark:  pablo
" default:     ron
" red:         slate

" use pablo color scheme
colorscheme pablo
:silent! colorscheme jellybeans
" make comments more readable with lighter gray
highlight Comment           ctermfg=Gray                                    guifg=Gray

" --- background ---
" use no background in terminal instead of gray
highlight Normal            ctermbg=NONE                                                    guibg=#080808
highlight NonText           ctermbg=NONE                                                    guibg=#080808
highlight SpecialKey        ctermbg=NONE                                                    guibg=#080808

" --- highlights ---
" todo
highlight Todo              ctermfg=Cyan    ctermbg=NONE    cterm=bold      guifg=Cyan      guibg=NONE      gui=bold
" search
highlight Search            ctermfg=161     ctermbg=NONE    cterm=standout  guifg=#df005f   guibg=NONE      gui=bold,standout
" superfluous extra whitespace
highlight ExtraWhiteSpace   ctermfg=White   ctermbg=167     cterm=bold      guifg=White     guibg=#df5f5f   gui=bold
"}}}

" --- whitespace ---{{{
" match whitespace
match ExtraWhitespace /\s\+$/
" enable when opening buffer
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
" disable when entering insert mode
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
" enable when leaving insert mode
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
"}}}

" --- airline statusbar ---{{{
set laststatus=2
let g:airline_theme='simple'
" https://github.com/vim-airline/vim-airline/wiki/FAQ#the-powerline-font-symbols-are-not-showing-up
let g:airline_powerline_fonts = 1

" --- airline powerline fonts (disabled) ---{{{
"" enable eye candy
"let g:airline_powerline_fonts = 1
"
"" install powerline fonts as root:      apt install fonts-powerline
""                                       fc-cache -vf /usr/share/fonts/
"" or manually for user only:            see: https://powerline.readthedocs.io/en/latest/installation/linux.html#fonts-installation
""                                       wget https://github.com/powerline/powerline/raw/develop/font/PowerlineSymbols.otf -O ~/.local/share/fonts/PowerlineSymbols.otf
""                                       mkdir -p ~/.config/fontconfig/conf.d
""                                       wget https://github.com/powerline/powerline/raw/develop/font/10-powerline-symbols.conf -O ~/.config/fontconfig/conf.d/10-powerline-symbols.conf
""                                       fc-cache -vf ~/.local/share/fonts/
"
"" to improve font rendering:
"" see:                                  https://github.com/vim-airline/vim-airline/wiki/Dummies-Guide-to-the-status-bar-symbols-(Powerline-fonts)-on-Fedora,-Ubuntu-and-Windows
"" install patched fonts:                git clone git@github.com:powerline/fonts.git
""                                       fonts/install.sh
""                                       fc-cache -vf ~/.local/share/fonts/
""
"" test fonts in terminal settings
"" select a font for use in airline bar:
""set guifont=Source\ Code\ Pro\ Light\ for\ Powerline:h15:cANSI
"
"" --- airline symbols ---
"if !exists('g:airline_symbols')
"    let g:airline_symbols = {}
"endif
"
"" unicode symbols
""let g:airline_left_sep = '»'
""let g:airline_left_sep = '▶'
""let g:airline_right_sep = '«'
""let g:airline_right_sep = '◀'
"let g:airline_symbols.crypt = '🔒'
""let g:airline_symbols.linenr = '☰'
""let g:airline_symbols.linenr = '␊'
""let g:airline_symbols.linenr = '␤'
""let g:airline_symbols.linenr = '¶'
"let g:airline_symbols.maxlinenr = ''
""let g:airline_symbols.maxlinenr = '㏑'
""let g:airline_symbols.branch = '⎇'
""let g:airline_symbols.paste = 'ρ'
""let g:airline_symbols.paste = 'Þ'
""let g:airline_symbols.paste = '∥'
"let g:airline_symbols.paste = 'P'
"let g:airline_symbols.spell = 'Ꞩ'
"let g:airline_symbols.notexists = 'Ɇ'
"let g:airline_symbols.whitespace = 'Ξ'
"
"" powerline symbols
"let g:airline_left_sep = ''
"let g:airline_left_alt_sep = ''
"let g:airline_right_sep = ''
"let g:airline_right_alt_sep = ''
"let g:airline_symbols.branch = ''
"let g:airline_symbols.readonly = ''
"let g:airline_symbols.linenr = '☰'
""let g:airline_symbols.maxlinenr = ''
"}}}
"}}}

" --- gpg ---{{{
" this is a fix to gnupg.vim that allows the use of gpg-agent with pinentry-curses
" set g:GPGPrimeAgent to 1 in your .vimrc to enable priming of gpg-agent
let g:GPGPrimeAgent = 1
" load optional gnupg package (jammy), needs system package vim-scripts
silent! packadd gnupg
"}}}

" --- markdown ---{{{
"au filetype markdown set conceallevel=2     "conceal markdown commands (broke in jammy)
au filetype markdown set wrap               "wrap lines

let g:markdown_folding = 1
au filetype markdown setlocal foldlevel=1

let g:markdown_fenced_languages = ['ruby', 'perl', 'bash=sh', 'sh', 'vim', 'html', 'javascript', 'css', 'python', 'yaml']
let g:markdown_minlines = 100       "synchronize syntax highlighting with more lines (default:50)

"au filetype markdown syntax match Comment /%%.*/
"au filetype markdown syntax match RedTodo /TODO/

""Enable concealing of links (https://github.com/tpope/vim-markdown/pull/9/commits/44dec444c959fa57c2fc835980ad15dbbbf11d1c)
"au filetype markdown syn region markdownLinkText matchgroup=markdownLinkTextDelimiter start="!\=\[\%(\_[^]]*]\%( \=[[(]\)\)\@=" end="\]\%( \=[[(]\)\@=" keepend nextgroup=markdownLink,markdownId skipwhite contains=@markdownInline,markdownLineStart concealends
"au filetype markdown syn region markdownLink matchgroup=markdownLinkDelimiter start="(" end=")" contains=markdownUrl keepend contained conceal
"au filetype markdown syn region markdownId matchgroup=markdownIdDelimiter start="\s*\[" end="\]" keepend contained conceal
"au filetype markdown syn region markdownAutomaticLink matchgroup=markdownUrlDelimiter start="<\%(\w\+:\|[[:alnum:]_+-]\+@\)\@=" end=">" keepend oneline concealends

"Custom markdown folding (disabled because insanely slows down typing)
"au filetype markdown setlocal foldexpr=MyMarkdownFold()
"au filetype markdown setlocal foldmethod=expr
"au filetype markdown setlocal foldlevel=1
"function! MyMarkdownFold()
"    let line = getline(v:lnum)
"    " regular headers
"    let depth = match(line, '\(^##\+\)\@<=\( .*$\)\@=')
"    if depth > 0
"        return ">" . depth
"    endif
"    " setext headers
"    let nextline = getline(v:lnum + 1)
"    if (line =~ '^.\+$') && (nextline =~ '^=\+$')
"        return ">1"
"    endif
"    if (line =~ '^.\+$') && (nextline =~ '^-\+$')
"        return ">2"
"    endif
"    return "="
"endfunction
"}}}

" --- ansible ---{{{
let g:ansible_unindent_after_newline = 1
"do not auto indent when writing ':'
autocmd FileType yaml.ansible setlocal indentkeys-=<:>
"enable syntax highlighting for .jinja file ending
autocmd BufNewFile,BufRead *.jinja set filetype=jinja2
"}}}

" --- python-mode ---{{{
" dow not show line numbers
autocmd FileType python setlocal nonumber
let g:pymode_python = 'python3'
let g:pymode_options_max_line_length = 100
"}}}

" --- httplog syntax (nginx, apache) ---{{{
autocmd BufRead,BufNewFile /var/log/nginx/** set filetype=httplog
"}}}

" --- unused ---{{{
" workaround for https://github.com/vim/vim/issues/1start671
"if has("unix")
"  let s:uname = system("echo -n \"$(uname)\"")
"  if !v:shell_error && s:uname == "Linux"
"    set t_BE=
"  endif
"endif
"}}}

" --- vim modeline ---{{{
" vim: set foldmethod=marker:
"}}}