" vim: fdm=marker:fdl=0:noml:
set nocp

augroup vimrc
  autocmd!
augroup END

let s:darwin = has('mac')
let s:linux = has('linux')
let s:nvim = has('nvim')
let mapleader      = ' '
let maplocalleader = ' '

set nocuc nocul noru nornu " causes all lines to redraw
set noeb bo=all
set nosc nosmd
set nosol " keep cursor on the same column
sil! set nomle
set nosm
set notitle
set spc=
set mouse=
set novb
if exists('&fixeol')
  set nofixeol
endif

set ar cf hid shm=aTIc
" minimal vimrc
set bs=2 cot= t_te= t_ti=
set enc=utf-8 " scriptencoding utf-8
set et ts=2 sw=2
set fdls=99 fdm=manual
set hi=50
set nohls nois
set ic scs
sil! set lz
set mls=2
set ls=2 stal=1 tpm=2
set so=5 siso=10
set statusline=%f%m\ %y\ %=\ [ln:%l,col:%v]
sil! set viminfo=
set wcm=<C-Z>
set wmnu wim=full " longest,list

map q: :
set cedit=^F
map ZZ <Nop>
augroup FixAltSlash
  autocmd!
  autocmd VimEnter * nnoremap <Char-247> <Esc>
augroup END


command! -bang -nargs=? -complete=file W w<bang> <args>
command! -bang -nargs=? -complete=file Wq wq<bang> <args>
command! -bang -nargs=? -complete=file WQ wq<bang> <args>
command! -nargs=? Help help <args>


" basic {{{

noremap <C-F> <C-D>
noremap <C-B> <C-U>

" save
" ----------------------------------------------------------------------------
" c-S | <leader>s | <leader>w
" map <C-s> :write<CR>
inoremap <C-s> <C-O>:update<CR>
nnoremap <C-s> :update<CR>
" imap <C-s> <Esc><C-s>
" inoremap <silent> <C-s> <Esc>:w<CR>a
" vmap <C-s> <Esc><C-s>
nnoremap <Leader>s :update<CR>
nnoremap <Leader>w :update<CR>
" nmap <Leader>w :w<CR>

" quit
" ----------------------------------------------------------------------------
" c-Q | <leader>q
nnoremap <C-q> :q<CR>
" noremap <C-q><C-q> :qa!<CR>
inoremap <C-q> <Esc>:q<CR>
vnoremap <C-q> <Esc>
nnoremap <Leader>q :q<CR>
nnoremap <Leader>Q :q<CR>
" nmap <silent> q :<C-u>q<CR>
" nnoremap <silent> <Leader>q :<C-u>cclose<CR>
" nnoremap <Leader>Q :qa!<CR>
nnoremap <silent> Q :<C-U>q<CR>
" nmap <silent> Q :<C-u>q!<CR>

" escaping
" ----------------------------------------------------------------------------
" alt+X | alt+Z
nnoremap <A-x> <Esc>
nnoremap <A-z> <Esc>
inoremap <A-x> <Esc><Right>
inoremap <A-z> <Esc><Right>
vnoremap <A-x> <Esc>
vnoremap <A-z> <Esc>
snoremap <A-x> <Esc>
snoremap <A-z> <Esc>
tnoremap <A-x> <C-\><C-n>
tnoremap <A-z> <C-\><C-n>
cmap <A-x> <Esc>
cmap <A-z> <Esc>
if !has('nvim')
  nnoremap ^@ <Esc>
  inoremap ^@ <Esc>
  vnoremap ^@ <Esc>
  cmap ^@ <Esc>
endif

" jk | escaping!
inoremap jk <Esc>
xnoremap jk <Esc>
cnoremap jk <C-C>

" ; ' | quick command mode (second binding to get find next)
nnoremap ; :
vnoremap ; :
nnoremap ' ;
vnoremap ' ;

" x | delete without saving it to register (blackhole)
nnoremap x "_x
vnoremap x "_x
nnoremap XX "_dd

" paste
" ----------------------------------------------------------------------------
" p | jump to end of pasted text. dont move cursor. paste multiple times ppppp
nnoremap p p`]
vnoremap <silent> p p`]
" _p | copy/paste from system clipboard.
nmap <silent> <Leader>p "+p
vmap <Leader>p "+p
" c-V | paste from buffer
inoremap <C-v> <Space><Backspace><Esc>pa
" a-V | paste from system clipboard
imap <A-V> <Space><Backspace><Esc>"+pa

" yank
" ----------------------------------------------------------------------------
" Y | make Y behave like other capitals yank to eol (without newline) " yy yank line
nnoremap Y y$
" _y | yank to system clipboard.
nmap <Leader>y "+y
vmap <Leader>y "+y
" y - make visual yanks pace the cursor back where started
vnoremap y ygv<Esc>
" Y | always yank as lines, even if a partial line is selected
" vnoremap <silent> Y y:call setreg('', getreg(), "V")<CR>
" c-C | yank to system clipboard.
xnoremap <C-c> "+y

" <shift-Up/Down/Left/Right> | quickly move cursor
" ----------------------------------------------------------------------------
nnoremap <S-up> <Esc>7<Up>
nnoremap <S-down> <Esc>7<Down>
nnoremap <S-left> <Esc>0
nnoremap <S-right> <Esc>$
inoremap <silent><expr> <S-up> pumvisible() ? "\<Space>\<Backspace>\<up>\<up>\<up>\<up>\<up>" : "\<up>\<up>\<up>\<up>\<up>"
inoremap <silent><expr> <S-down> pumvisible() ? "\<Space>\<Backspace>\<down>\<down>\<down>\<down>\<down>" : "\<down>\<down>\<down>\<down>\<down>"
inoremap <S-left> <Esc>I
inoremap <S-right> <Esc>A
vnoremap <S-up> <Up><Up><Up><Up><Up>
vnoremap <S-down> <Down><Down><Down><Down><Down>
vnoremap <S-left> 0
if s:nvim
  vnoremap <S-right> $
else
  vnoremap <S-right> $<Left>
endif
tnoremap <S-left> <C-A>
tnoremap <S-right> <C-E>

" }}}

" co | h m n r w {{{
" ----------------------------------------------------------------------------
" co? : Toggle options (inspired by unimpaired.vim)
" ----------------------------------------------------------------------------
function! s:map_change_option(...)
  let [key, opt] = a:000[0:1]
  let op = get(a:, 3, 'set '.opt.'!')
  execute printf("nnoremap co%s :%s<bar>set %s?<cr>", key, op, opt)
endfunction

call s:map_change_option('p', 'paste')
call s:map_change_option('n', 'number')
call s:map_change_option('w', 'wrap')
call s:map_change_option('h', 'hlsearch')
call s:map_change_option('m', 'mouse', 'let &mouse = &mouse == "" ? "a" : ""')
call s:map_change_option('r', 'relativenumber', 'let &relativenumber = &relativenumber == "" ? "1" : "0"')
call s:map_change_option('t', 'textwidth',
    \ 'let &textwidth = input("textwidth (". &textwidth ."): ")<bar>redraw')
call s:map_change_option('b', 'background',
    \ 'let &background = &background == "dark" ? "light" : "dark"<bar>redraw')

" }}}

" <enter> | quick command mode
noremap <CR> :

" HJKL | quickly move cursor
nnoremap K 7<Up>
nnoremap J 7<Down>
nnoremap H 0
nnoremap L $

" moving lines
" ----------------------------------------------------------------------------
" c-[j/k] | move line up/down ala vscode
nnoremap <silent> <C-k> :move-2<CR>
nnoremap <silent> <C-j> :move+<CR>
nnoremap <silent> <C-h> <<
nnoremap <silent> <C-l> >>
xnoremap <silent> <C-k> :move-2<CR>gv
xnoremap <silent> <C-j> :move'>+<CR>gv
xnoremap <silent> <C-h> <gv
xnoremap <silent> <C-l> >gv
" < > - keep visual selection when indenting. visual shifting (builtin-repeat)
xnoremap < <gv
xnoremap > >gv

" + | duplicate line just above
map + "ayy<Up>"ap
" = | duplicate line just below
map = "ayy"ap

" D | delete to end of line
nnoremap D d$

" dsc | delete a surrounding function call (which surround doesnt support OOTB)
nmap dsc :call search('\<', 'bc')<CR>dt(ds)

" dw | delete a word backwards
nnoremap dw vb"_d

" ff - fold-unfold
nnoremap <silent> ff @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>

" g. | last inserted text
nnoremap g. :normal! `[v`]<CR><left>

" U - redo
nnoremap U <C-R>

" vv | select line (without newline)
nnoremap vv ^vg_

" z | folds
" ----------------------------------------------------------------------------
" z-Up/Down/Left/Right | jump between folding nodes
nnoremap z<Left> zk
nnoremap z<Right> zj
nnoremap z<Up> [z
nnoremap z<Down> ]z
" z+hjkl | jump between folding nodes
nnoremap zh zk
nnoremap zl zj
nnoremap zj ]z
nnoremap zk [z
" zO | recursively open top level fold we're in. no matter where cursor is.
nnoremap zO zCzO
" zz | open all folds more easily
nnoremap zz zR


imap <C-e> <Esc>Ea
" movement in insert mode
inoremap <C-h> <C-O>h
inoremap <C-l> <C-O>a
inoremap <C-j> <C-O>j
inoremap <C-k> <C-O>k
inoremap <C-^> <C-O><C-^>

" undo behavior
inoremap <BS> <C-G>u<BS>
inoremap <CR> <C-G>u<CR>
inoremap <Del> <C-G>u<Del>
" delete only word before
inoremap <C-w> <C-G>u<C-W>
" c-U | default undo deletes a lot
inoremap <C-u> <C-G>u<C-U>

" a-Enter | equivalent: 'norm! o'
inoremap <A-CR> <C-G>u<C-O>o
" a-b | back a word
inoremap <A-b> <C-Left>
" a-f | forward a word
inoremap <A-f> <C-Right>
" a-BS - delete backward word
inoremap <A-BS> <C-W>
" a-d - delete forward word
inoremap <A-d> <C-O>dw
" a-o | equivalent: 'norm! o'
inoremap <A-o> <C-G>u<C-O>o
" a-O | equivalent: 'norm! O'
inoremap <A-S-o> <C-G>u<C-O>O
" a-u | undo typed text
inoremap <A-u> <C-G>u<C-O>u
" a-U | redo
inoremap <A-S-u> <C-G>u<C-O><C-R>
" a-v | go to visual mode
inoremap <A-v> <Esc>V

" <a-Up/Down> | move current line / block with Alt-j/k ala vscode
inoremap <silent> <A-up> <Esc><Cmd>m .-2<CR>==gi
inoremap <silent> <A-down> <Esc><Cmd>m .+1<CR>==gi

" HJKL | quickly move cursor
vnoremap K 5<Up>
vnoremap J 5<Down>
vnoremap H 0
vnoremap L $h

" v | quit visual mode
vnoremap v <Esc>

" c-X | delete
vmap <C-x> d

cnoremap <C-a> <Home>
cnoremap <C-b> <Left>
cnoremap <expr> <C-d> getcmdpos()>strlen(getcmdline())?"\<Lt>C-D>":"\<Lt>Del>"
cnoremap <expr> <C-f> getcmdpos()>strlen(getcmdline())?&cedit:"\<Lt>Right>"
cnoremap <C-e> <End>
" bash bg
cmap <C-G> <C-C>
cnoremap <C-h> <C-W>
cnoremap <C-n> <Down>
cnoremap <C-p> <Up>
cnoremap <A-b> <S-Left>
cnoremap <A-f> <S-Right>
silent! exe "set <S-Left>=\<Esc>b"
silent! exe "set <S-Right>=\<Esc>f"
cnoremap <A-BS> <C-W>
cnoremap <A-d> <C-Right><C-W>

" ><esc> | quick fold and unfold
nnoremap <silent> <Leader><Esc> :normal!za<CR>

" _b | buffers
nnoremap <Leader>b :buffers<CR>:buffer<Space>
nnoremap <Leader>bb <Cmd>e #<CR>
noremap <Leader>bc :bp\|:bd#<CR>

" edit
nnoremap <Leader>ee :e %:p:h/<C-Z>
nnoremap <Leader>ev :vs %:p:h/<C-Z>
nnoremap <Leader>ff :edit **/
nnoremap <Leader>fv :vertical split **/

" #!! | shebang
inorea <expr> #!! "#!/usr/bin/env" . (empty(&filetype) ? '' : ' '.&filetype)

" ex: iabbr <silent> if if ()<Left><C-R>=Eatchar('\s')<CR>
function! s:Eatchar(pat)
  let c = nr2char(getchar(0))
  return (c =~ a:pat) ? '' : c
endfunc

"command abbrevs we can use `:E<space>` (and similar) to edit a file in the
"same dir as current file
cabbrev E <C-R>="e "  . expand("%:h") . "/"<CR><C-R>=<SID>Eatchar(' ')<CR>
cabbrev Sp <C-R>="sp " . expand("%:h") . "/"<CR><C-R>=<SID>Eatchar(' ')<CR>
cabbrev SP <C-R>="sp " . expand("%:h") . "/"<CR><C-R>=<SID>Eatchar(' ')<CR>
cabbrev Vs <C-R>="vs " . expand("%:h") . "/"<CR><C-R>=<SID>Eatchar(' ')<CR>
cabbrev VS <C-R>="vs " . expand("%:h") . "/"<CR><C-R>=<SID>Eatchar(' ')<CR>
cabbrev R <C-R>="r " . expand("%:h") . "/"<CR><C-R>=<SID>Eatchar(' ')<CR>

" cab
cabbrev <expr> eh getcmdtype() == ':' ? 'e~/'.<SID>Eatchar('\s') : 'eh'
cabbrev <expr> es getcmdtype() == ':' ? 'e%:p:s/'.<SID>Eatchar('\s') : 'es'

" ----------------------------------------------------------------------------

augroup vimrc
  " improved_autoread
  autocmd FocusGained,BufEnter * silent! checktime
  " emit warning if the file changed
  autocmd FileChangedShellPost *
    \ echohl WarningMsg
    \ | echo "File changed on disk. Buffer reloaded."
    \ | echohl None

  " restore <quit> in buffers
  autocmd FileType help nnoremap <buffer> q :q<CR>
  autocmd FileType man nnoremap <buffer> q :q<CR>

  " unset paste on InsertLeave
  autocmd InsertLeave * set nopaste

  " close preview window
  if exists('##CompleteDone')
  " auto close popup menu when finish completion
  " autocmd CompleteDone * if pumvisible() == 0 | pclose | endif
    au CompleteDone * pclose
  else
  " autocmd InsertLeave * if pumvisible() == 0 | pclose | endif
    au InsertLeave * if !pumvisible() && (!exists('*getcmdwintype') || empty(getcmdwintype())) | pclose | endif
  endif
augroup END
