" vim: ft=vim:fdm=marker:fdl=0:noml:
"
"           ██
"          ░░
"  ██    ██ ██ ██████████
" ░██   ░██░██░░██░░██░░██
" ░░██ ░██ ░██ ░██ ░██ ░██
"  ░░████  ░██ ░██ ░██ ░██
"   ░░██   ░██ ███ ░██ ░██
"    ░░    ░░ ░░░  ░░  ░░
"
" xdg {{{
if empty($MYVIMRC) | let $MYVIMRC = expand('<sfile>:p') | endif
if empty($XDG_CACHE_HOME) | let $XDG_CACHE_HOME = $HOME."/.cache" | endif
if empty($XDG_CONFIG_HOME) | let $XDG_CONFIG_HOME = $HOME."/.config" | endif
if empty($XDG_DATA_HOME) | let $XDG_DATA_HOME = $HOME."/.local/share" | endif
if empty($XDG_STATE_HOME) | let $XDG_STATE_HOME = $HOME."/.local/state" | endif
if !empty($XDG_STATE_HOME)
  let s:state_home = substitute($XDG_STATE_HOME, '/$', '', '') . '/vim/'
elseif has('win32')
  let s:state_home = expand('~/AppData/Local/vim-data/')
else
  let s:state_home = expand('~/.local/state/vim/')
endif
let &undodir = s:state_home . 'undo//'
let &directory = s:state_home . 'swap//'
let &backupdir = s:state_home . 'backup//'
let &viewdir = s:state_home . 'view//'
if !isdirectory(&undodir) | call mkdir(&undodir, 'p', 0700) | endif
if !isdirectory(&directory) | call mkdir(&directory, 'p', 0700) | endif
if !isdirectory(&backupdir) | call mkdir(&backupdir, 'p', 0700) | endif
if !isdirectory(&viewdir) | call mkdir(&viewdir, 'p', 0700) | endif
set vif=$XDG_STATE_HOME/vim/viminfo
set viminfo='20,<50,s10,h,r/tmp,n~/.local/state/vim/viminfo
if has('packages')
  let &packpath = &runtimepath
endif
" }}}
set nocompatible
augroup vimrc
  autocmd!
augroup END

set encoding=utf-8
" scriptencoding utf-8
" if v:lang =~ "utf8$" || v:lang =~ "UTF-8$"
"   set fencs=ucs-bom,utf-8,latin1
" endif
let g:mapleader = "\<Space>"
" term/gui {{{
if $TERM =~ '^\(tmux\|screen\|foot\)\(-.*\)\?$'
  set termguicolors
  "let &t_8f = "\<Esc>[38:2::%lu:%lu:%lum"
  "let &t_8b = "\<Esc>[48:2::%lu:%lu:%lum"
  let &t_8f = "\e[38:2:%lu:%lu:%lum"
  let &t_8b = "\e[48:2:%lu:%lu:%lum"
  let &t_RF = "\e]10;?\e\\"
  let &t_RB = "\e]11;?\e\\"
endif
" bracketed paste
let &t_BE = "\e[?2004h"
let &t_BD = "\e[?2004l"
let &t_PS = "\e[200~"
let &t_PE = "\e[201~"
" termcap-cursor-shape
"let &t_SH = "\e[6 q"
"let &t_SI = "\e[6 q"
"let &t_SR = "\e[4 q"
"let &t_EI = "\e[2 q"
" cursor control
let &t_RC = "\e[?12$p"
let &t_SH = "\e[%d q"
let &t_RS = "\eP$q q\e\\"
let &t_SI = "\e[5 q"
let &t_SR = "\e[3 q"
let &t_EI = "\e[1 q"
let &t_VS = "\e[?12l"
let &t_ut=''
" }}}
" builtin/pack {{{
filetype plugin indent on
if has('packages')
  let g:netrw_home = $XDG_STATE_HOME."/vim"
  " pa! for lazy load
  silent pa! editorconfig
    let g:EditorConfig_enable_for_new_buf = 1
    let g:EditorConfig_exclude_patterns = ['term://.*', 'scp://.*']
  silent! pa comment
  silent! pa surround
  "silent pa! gnupg
  "  let g:GPGPreferArmor = 1
  "runtime ftplugin/man.vim
  " for plugins => setup matchit-related variables matchup can use
  "runtime macros/matchit.vim
endif

" always load Cfilter/Lfilter commands plugin
pa cfilter

" :h standard-plugin-list
let loaded_getscriptPlugin = 1
let g:loaded_logiPat = 1
let g:loaded_vimballPlugin = 1
let g:loaded_vimball = 1
let loaded_spellfile_plugin = 1
let loaded_gzip = 1
let g:loaded_tarPlugin = 1
let g:loaded_tar = 1
let g:loaded_tutor_mode_plugin = 1
let g:loaded_zipPlugin = 1
let g:loaded_zip = 1
"let loaded_matchparen = 1 && set sm mat=3
let matchparen_disable_cursor_hl = 1
let g:matchparen_insert_timeout = 3

" netrw
" prevent .netrwhist creation
let g:netrw_dirhistmax=0
let g:netrw_banner=0
" hide dotfiles by default, use 'a' to cycle
let g:netrw_list_hide='\(^\|\s\s\)\zs\.\S\+'
"let g:netrw_liststyle= 3
"let g:netrw_sizestyle='H'
let g:netrw_uid= "anonymous"
let g:netrw_usetab=1
let g:netrw_winsize= 20
"let g:os_viewer= 'xdg-open'
"let g:netrw_browser_viewer= 'browser'
let g:netrw_nogx= 1
"if executable('openk')
"  let g:netrw_http_cmd = "openk %s >"
"else
"  let g:netrw_http_cmd = "curl -Ls -o"
"endif

set rtp+=~/.local/fzf
" }}}
" syntax {{{
"if &t_Co > 2 || has("gui_running")
"  syntax on
"endif
if !exists('syntax_on')
  syntax enable
endif
if exists('+synmaxcol')
  set synmaxcol=150
endif
" syntax settings
" ---------------
let c_syntax_for_h = 1
let c_no_comment_fold = 1
let c_no_curly_error = 1
let c_no_if0_fold = 1
let g:diff_translations = 0
let hs_highlight_delimiters = 1
let html_no_rendering=1
let g:vim_json_conceal = 0
let make_no_commands = 1
let make_no_comments = 1
let g:markdown_fenced_languages = ['html', 'python', 'ruby', 'bash=sh']
let nroff_is_groff = 1
let nroff_space_errors = 1
set para=BlBdPpIt sect=ShSs
let g:pandoc#syntax#conceal#use = 0
let perl_include_pod = 0
let perl_no_scope_in_variables = 1
let perl_no_extended_vars = 1
let perl_nofold_packages = 1
let php_sql_query = 1
let python_highlight_all = 1
let readline_has_bash = 1
let rst_syntax_code_list = []
"let ruby_fold = 1
let ruby_operators = 1
let ruby_no_expensive = 1
let g:is_posix = 1
"let g:sh_fold_enabled = 0 "has('folding')
let g:sh_fold_enabled = has('folding')
let g:sh_no_error= 1
"let g:tex_nospell = 1
let g:tex_comment_nospell= 1
let g:vimsyn_embed = 0
let g:vimsyn_folding = 0
"let g:xml_syntax_folding = 1

" diff | no syntax highlighting in diff mode
if &diff | syntax off | endif

" filetype settings
" -----------------
"let g:awk_is_gawk = 1
let g:ft_man_folding_enable = 0
"let g:ft_man_no_sect_fallback = 1
let g:markdown_folding = 0
let g:org_folding = 1
let g:qf_disable_statusline = 1
" recommended style: et sw=4 sts=4 tw=99
"let g:rust_recommended_style = 0
let g:rustfmt_autosave = 1
let g:rustfmt_autosave_if_config_present = 0
let g:rustfmt_command = 'rustfmt +stable'
"let g:rustc_path = $CARGO_HOME."/bin/rustc"
let g:termdebug_wide = 1
" shell | iskeyword => polluting other filetypes even after 'set ft=' change
let g:sh_noisk = 1

" indent settings
" ---------------
" indent after <p> paragraph tags too
let g:html_indent_inctags = "p"
"let g:html_indent_inctags = "html,body,head,tbody,div"
"let g:vim_indent_cont = 2 * 3

" compiler settings
" -----------------
let g:compiler_gcc_ignore_unmatched_lines=1
" let g:pylint_makeprg_params = "--max-line-length "..&textwidth
let g:pylint_makeprg_params = "--rcfile ~/.config/pylint/pylintrc"
let g:tex_flavor = 'latex'
" }}}
" settings {{{
" menu-unmap
":unmenu *   " remove all in Normal and visual mode
":unmenu! *  " remove all in Insert and Command-line mode
":aunmenu *  " remove all in all modes, except for Terminal mode
":tlunmenu * " remove all in Terminal mode
":aunmenu *
":tlunmenu *

set nobk noswf
set nocuc nocul nosc nosm nosmd
set noeb novb
"if exists('&fixeol')
"  set nofixeol
"endif
set nojs nosol
"set nolrm winaltkeys=no mousem=extend
set mouse=
if exists('+autoshelldir')
  set noautoshelldir
endif
set ar cf hid mls=1 shm=ltToOCFaIc
set bdir-=.
set bs=indent,eol,start
" sta ^ =>sw | =>ts/sts
set sta
set et sw=2 sts=2 ai
"set ts=8 sts=0
"if exists('*shiftwidth')
"  set sw=0 sts=-1
"endif
set bri sbr=\ +
set cb^=unnamed
if has('unnamedplus')
  set cb^=unnamedplus
endif
" makes screen redrawing slower
set cc=80
"if exists('+colorcolumn')
"  set cc=+1
"endif
set cd=,, path-=/usr/include
set cedit=<C-F>
" :0 | no extra indentation for case in switch
"set cino+=:0,g0
"set cino=:0,t0,+2,(2
"set cino=l1,:0,g0,E-s,N-s,t0,(s,J1,j1
"cino=Ls,:0,l1,t0,(s,U1,W4
"cpp => set cino=g0,+0,N-s
"cppg=> set cino=h1,l1,g1,t0,i4,+4,(0,w1,W4
"default: cinkeys=0{,0},0),0],:,0#,!^F,o,O,e
"set cinkeys=0{,0},:,0#,0<Tab>,!^F
" default: cpt=.,w,b,u,t,i
set cot=menuone,noselect cpt=.,w,b,k,d ph=10
" make "cw" consistent with other "w" commands
set cpo-=_
set ofu=syntaxcomplete#Complete cfu=syntaxcomplete#Complete
if !has('win32')
  set dict=/usr/share/dict/words
  set dict+=/usr/share/dict/british-english
  set tsr^=$VIMCONFIG/thesaurus/thesaurus.txt
endif
" default: internal,filler,closeoff
set dip+=vertical
" use a (usually) better diff algorithm.
" set dip+=algorithm:patience
" set dip+=indent-heuristic
set dy=lastline
set ef=errors.err
set fdm=marker "fdls=99
"set ft=text
" don't break lines > tw
"set fo=cjql
"set foldcolumn=2
" ep: program used for "=" command
" fp: to format lines with "gq" command
if executable('par')
  set fp=par
endif
if executable('rg')
  let &grepprg = 'rg --vimgrep'
  let &grepformat = '%f:%l:%c:%m,%f:%l:%m'
elseif executable('glr')
  set grepprg=glr
elseif executable('grep')
  set grepprg=grep\ -nHrI\ $*\ /dev/null
endif
set hi=1000 udf ul=1000 ur=1000
set ic scs inf "nofic
set is nohls inc=
"foobar=~/<ctrl-><ctrl-F>
set isf-==
set kp=:Man
" unicode/ascii
set list
if has('multi_byte_encoding')
  " tab:⇥\ ,trail:␣,nbsp:·,extends:→
  "lcs=tab:\\u21e5\\u0020,trail:\\u2423,nbsp:\\u00b7,extends:\\u2192
  let &g:lcs = "tab:\u21e5\u00b7,trail:\u2423,extends:\u21c9,precedes:\u21c7,nbsp:\u00b7"
else
  set lcs=tab:>\ ,trail:·,extends:>,precedes:<,nbsp:+,eol:$
endif
" update faster => CursorHold event
set lz ut=1000
set magic
set nf-=octal
set nu nuw=3 ls=2 stal=1
" always show changed line count
set report=0
set ru ruf=%30(%=%l/%L:%c%V\ %y\ %p%%\ %)
set sb spr tpm=30
set so=5 siso=10
"set so=1 siso=5
set spl=en spc= sps=double,5
" add new words (via zg) here (undo via zug)
set spf=$VIMCONFIG/spell/en.utf-8.add,$VIMCONFIG/spell/custom.utf-8.add
set ssop-=options vop-=options
" only save cursor/fold/buffer/window/tab positions.
"set ssop=blank,buffers,folds,help,tabpages,winsize vop-=options
set tags=./tags; tc=match
set tm=500 ttimeout ttm=50
set ve=block
set su+=.log,.old,.out su-=.h
set wig=*.o,*~,*.pyc wig+=*/.git/*,*/.svn/*,*.swp,*/tmp/*,*/.DS_Store
set wcm=<Tab>
set wmnu wim=full wop=pum
"set ww+=<,>

set bg=light
"colo shine
colo vacme
"hi NonText cterm=NONE ctermfg=NONE gui=NONE guifg=#B2B2B2 guibg=NONE
"hi SpecialKey cterm=NONE ctermfg=242 gui=NONE guifg=#6C6C6C guibg=NONE
"hi Comment cterm=NONE ctermfg=245 gui=italic guifg=#8A8A8A guibg=NONE
"hi ColorColumn cterm=NONE ctermfg=NONE ctermbg=253 gui=NONE guibg=#D0D0D0

"hi Comment cterm=NONE ctermfg=7 gui=NONE
"hi Normal cterm=NONE ctermbg=NONE gui=NONE guibg=NONE
"hi Folded cterm=NONE ctermbg=NONE gui=NONE guibg=NONE
"hi Visual NONE cterm=reverse ctermfg=6 gui=reverse
" no syntax highlighting; only highlight interface elements
hi Ignore      NONE
hi CursorLine  NONE
hi Folded      NONE
hi ColorColumn NONE ctermbg=yellow
"hi Constant    NONE ctermfg=red
hi SpecialKey  NONE ctermfg=gray
hi EndOfBuffer NONE ctermfg=gray
hi Pmenu       NONE ctermbg=gray
hi Search      NONE ctermbg=yellow
hi IncSearch   NONE ctermbg=yellow
hi CurSearch   NONE ctermbg=yellow
hi PmenuSel    NONE cterm=reverse
hi Visual      NONE cterm=reverse
hi MatchParen  NONE cterm=underline
hi Cursor      NONE cterm=reverse
hi StatusLine  NONE cterm=reverse,bold
hi ModeMsg     NONE cterm=reverse,bold

"highlight ExtraWhitespace ctermbg=red guibg=red
"match ExtraWhitespace /\s\+$/
"highlight MixedTabs ctermbg=darkgreen guibg=darkgreen
"call matchadd('MixedTabs', '\s*\( \t\|\t \)\s*')
"highlight ExtraWhitespace ctermbg=darkgreen guibg=darkgreen
"call matchadd('ExtraWhitespace', '\s\+$')
"hi LineTooLong ctermfg=223
"highlight LineTooLong ctermbg=darkgray ctermfg=black
"call matchadd('LineTooLong', '\%81v', 100)
" highlight VCS conflict markers
"match ErrorMsg '^\(<\|=\|>\)\{7\}\([^=].\+\)\?$'
" }}}
" functions {{{
" NOTE:
" regex depends on case sensitivity settings and nomagic setting
" prepend with \m\C => to make regexes act like nomagic and noignorecase
" magic levels (\v) | case sensitivities (\c)
" getline(1) =~ '^#!' || !~
"
" s:is_function(string) abort
" exists('*' . a:string)
" exists('*' . 'M')

" Call system() and then call :redraw!
" Pass args as data-first to allow use as a method.
" Check v:shell_error if you need to know the exit code.
fu! s:SysR(arr, cmd)
  let l:ret = system(a:cmd, a:arr)
  redraw!
  return l:ret
endfu

" Maybe return a string if the first arg is not empty.
fu! M(x, y)
  return a:x == '' || a:x == v:false ? '' : a:y . a:x
endfu
fu! W(x, y)
 return a:x == '' || a:x == v:false ? '' : a:x . a:y
endfu

"function! s:Ask(abbr,expansion,defprompt)
"  let answer = confirm("Expand '" . a:abbr . "'?", "&Yes\n&No", a:defprompt)
"  " testing against 1 and not 2, I correctly take care of <abort>
"  return answer == 1 ? a:expansion : a:abbr
"endfunction
"iabbrev <expr> for <SID>Ask('for', "for () {\n}", 2)

"function! s:GetSelectedText()
"  let [lnum1, col1] = getpos("'<")[1:2]
"  let [lnum2, col2] = getpos("'>")[1:2]
"  if (line2byte(lnum1) + col1) > (line2byte(lnum2) + col2)
"    let [lnum1, col1, lnum2, col2] = [lnum2, col2, lnum1, col1]
"  endif
"  let lines = getline(lnum1, lnum2)
"  if empty(lines)
"    return ''
"  endif
"  let lines[-1] = lines[-1][: col2 - (&selection ==# 'inclusive' ? 1 : 2)]
"  let lines[0] = lines[0][col1 - 1:]
"  return join(lines, "\n")
"endfunction

" get selected text in visual mode.
" see: https://overflow.adminforge.de/questions/1533565/placeholder#6271254
function! s:GetSelectedText()
  let [lnum1, col1] = getpos("'<")[1:2]
  let [lnum2, col2] = getpos("'>")[1:2]
  let lines = getline(lnum1, lnum2)
  let lines[-1] = lines[-1][: col2 - (&selection == 'inclusive' ? 1 : 2)]
  let lines[0] = lines[0][col1 - 1:]
  return join(lines, "\n")
endfunction

" Return a dictionary containing the start position, end position and length of
" the current visual selection.
function! s:get_visual_selection()
  let start_pos = getpos("'<")
  let end_pos = getpos("'>")
  let [lnum1, col1] = start_pos[1:2]
  let [lnum2, col2] = end_pos[1:2]
  let lines = getline(lnum1, lnum2)
  let lines[-1] = lines[-1][: col2 - 1]
  let lines[0] = lines[0][col1 - 1:]
  return {
        \ 'start_pos': start_pos,
        \ 'end_pos': end_pos,
        \ 'length': len(join(lines, "\n"))
        \}
endfunction

function! s:GetSelection()
  return getline('.')[col("'<")-1:col("'>")-1]
endfunction

function! Preserve(command)
  let l:search=@/
  let l:line = line(".")
  let l:col = col(".")
  exe a:command
  " clean up: restore previous search history,cursor position
  let @/=l:search
  call cursor(l:line, l:col)
endfunction

"---------------------------
function! s:Error(msg) abort
  echohl ErrorMsg
  echomsg a:msg
  echohl Normal
endfunction
" }}}
" commands {{{
" :AppendToLog | open daily log and append a time stamp.
" vim '+call AppendToLog()'
function! AppendToLog() abort
  let time=strftime('%F')
  sp ~/.log
  call append('$', ['', time])
  exe "normal! Go* "
  startinsert!
endfunc

" :AutoSave
function! s:autosave(enable) abort
  augroup autosave
    autocmd!
    if a:enable
      autocmd TextChanged,InsertLeave <buffer>
          \  if empty(&buftype) && !empty(bufname(''))
          \|   silent! update
          \| endif
    endif
  augroup END
endfunction
com! -bang AutoSave call s:autosave(<bang>1)

" :BufDo | execute <command> in all buffers and return to original buffer.
function! BufDo(command) abort
  let current=bufnr('%')
  exe 'bufdo ' . a:command
  exe 'buffer ' . current
endfunction
com! -nargs=+ -complete=command BufDo call BufDo(<q-args>)

" :Cclear | :Search | search all buffers.
" enables to search in all open buffers with :Search <pattern>.
" see: https://overflow.adminforge.de/exchange/vi/questions/2904/#2905
function! BuffersList() abort
  let all = range(0, bufnr('$'))
  let res = []
  for b in all
    if buflisted(b)
      call add(res, bufname(b))
    endif
  endfor
  return res
endfunction
function! GrepBuffers(expression) abort
  exe 'vimgrep/'.a:expression.'/ '.join(BuffersList())
endfunction
"function! GrepBufs (expression)
"nnoremap <Leader>z :call GrepBuffers("<C-R><C-w>")<CR>
"  exe 'vimgrep/'.a:expression.'/j '.join(BuffersList())
"endfunction
command! -nargs=+ GrepBufs call GrepBuffers(<q-args>) "<Bar> cwindow
nnoremap <Leader>sb :GrepBufs<Space>
"nnoremap <Leader>z :call GrepBuffers("<C-R><C-w>")<CR>
com! -nargs=0 Cclear call setqflist([]) | cclose
com! -nargs=+ Search call setqflist([]) | call GrepBuffers(<q-args>) | cope

" :Cleanup | close unused buffers.
function! CloseHiddenBuffers() abort
  let open_buffers = []
  for i in range(tabpagenr('$'))
    call extend(open_buffers, tabpagebuflist(i + 1))
  endfor
  for num in range(1, bufnr('$') + 1)
    if buflisted(num) && index(open_buffers, num) == -1
      exe 'bdelete '.num
    endif
  endfor
endfunction
com! Cleanup call <SID>CloseHiddenBuffers()

" :ClearRegisters
" see: https://overflow.adminforge.de/questions/19431165/placeholder#39348498
com! ClearRegisters
    \ for i in range(34,122) | silent! call setreg(nr2char(i), []) | endfor

" :CopyMatches | copy all matching string.
function! CopyMatches(reg) abort
  let l:hits = []
  %s//\=len(add(l:hits, submatch(0))) ? submatch(0) : ''/gne
  let l:reg = empty(a:reg) ? '+' : a:reg
  exe 'let @'.l:reg.' = join(hits, "\n") . "\n"'
endfunction
com! -register CopyMatches call CopyMatches(<q-reg>)

" :Count
com! -nargs=1 Count exe printf('%%s/%s//gn', escape(<q-args>, '/')) | normal! ``

" :Csearch
com! -count -nargs=+ Csearch
  \ cexpr [] <Bar>
  \ exe printf('%s vimgrep /%s/g %%', <count> > 0 ? <q-count> : '', escape(<q-args>, '/'))

" :CSSSort | alphabetically sort CSS properties in file.
com! CSSSort :g#\({\n\)\@<=#.,/}/sort
" >S | sort CSS Properties
"nn <Leader>S ?{<CR>jV/^\s*\}?$<CR>k:sort<CR>:noh<CR>

" :DateISO
com! DateISO :norm a<C-R>=strftime('%FT%T%z')<CR>

" :DATES
com! DATES vimgrep /\v<\d{4}-\d{2}-\d{2}>/j % | cw

" :Delete
com! -bang Delete
    \ let s:file = expand('%:p') |
    \ exe 'bdelete!' |
    \ if delete(s:file) != 0 |
    \   echoerr 'Failed to delete "' . s:file . '"' |
    \ endif |
    \ unlet s:file

" :Diff | current window and "next" window or a newly split file.
function! Diff(filename) abort
  if a:filename != ""
    exe "vsplit " . a:filename
  endif
  if winnr("$") >= 2
    diffthis
    wincmd w
    diffthis
    wincmd p
  endif
endfunction
com! -bar -nargs=? Diff call Diff(<q-args>)

" :DiffOrig | diff a buffer against its original contents.
" shows unsaved differences between this buffer and original file.
if !exists(':DiffOrig')
  command DiffOrig vert new | set bt=nofile | read ++edit # | 0d_ | diffthis
      \ | wincmd p | diffthis
endif

" :Drawmode | toggle virtualedit.
" useful for ascii art and for transposing columns with a visual selection
com! Drawmode exe "set ve=". (&ve == 'all' ? 'block' : 'all') | echo &ve

" :Duplicate
function! DuplicateCurrentFile() abort
  let old_file = expand('%')
  let new_file = input('Duplicate as: ', old_file, 'file')
  if (new_file == '' || new_file == old_file) | return | endif
  if buflisted(new_file) | exe 'bd! ' . new_file | endif
  exe ':saveas! ' . new_file
endfunction
com! Duplicate :call DuplicateCurrentFile()<CR>

" :EqualizeWindows
command EqualizeWindows norm <C-w>=
command MaximizeWindow norm <C-w><C-_><C-w><C-|>

" :Ex | fuzzy-finder file explorer (of sorts).
com! Ex
    \ call <SID>SysR('', 'ftree '. expand('%:p:h'))
    \ ->trim()
    \ ->fnameescape()
    \ ->{x -> x == ''
    \     ? ''
    \     : isdirectory(x) ? 'lcd '. x : 'edit '. x
    \ }()
    \ ->execute()

" :EX | execute current buffer | aka RUN
" ? vsplit | terminal ./%
"com! EX if !empty(expand('%'))
"    \|   write
"    \|   call system('chmod +x '.expand('%'))
"    \|   silent e
"    \| else
"    \|   echohl WarningMsg
"    \|   echo 'Save the file first'
"    \|   echohl None
"    \| endif

" :Filter
com! -nargs=? Filter
    \ let @a='' | exe 'g/<args>/y A' | new | setlocal bt=nofile | put! a

" :FindConditionals | search for conditional branches, both implicit/explicit
com! FindConditionals :norm /\<if\>\|\<unless\>\|\<and\>\|\<or\>\|||\|&&<CR>

" :FormatJSON
com! FormatJSON %!python -m json.tool

" :Goto
com! -nargs=1 Goto :call cursor(byte2line(<args>), <args>-line2byte(byte2line(<args>))+1)

" :Greparglist | grep all files in the arglist.
com! -nargs=* Greparglist grep <args> ##

" :Grepbuflist | grep across all loaded buffers.
com! -nargs=* Grepbuflist call range(0, bufnr('$'))
    \ ->filter({i, x -> buflisted(x)})
    \ ->map({i, x -> fnameescape(bufname(x))})
    \ ->join(' ')
    \ ->M('grep <args> ')
    \ ->execute()

" :Grepqflist | grep all files in the quickfix list.
com! -nargs=* Grepqflist call getqflist()
    \ ->map({i, x -> fnameescape(bufname(x.bufnr))})
    \ ->sort() ->uniq() ->join(' ')
    \ ->M('grep <args> ')
    \ ->execute()

" :Help
"com! -nargs=? Help help <args>
com! -nargs=* -complete=help Help tab help <args>

" :HL | find out syntax group.
function! s:hl() abort
  if !exists('*synstack')
    return
  endif
  echo join(map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")'), '/')
endfunction
com! HL call <SID>hl()

" :InsertTemplate
function! InsertTemplate(file)
  try
    exe 'r ' . get(split(globpath(&rtp, "templates/" . a:file), "\n"), -1)
  catch /E484:/
    echo 'File not found.'
  endtry
endfunction
function! InsertTemplateComplete(A, L, P)
  return split(get(split(globpath(&rtp, "templates/" . a:A . "*"), "/"), -1, ""), "\n")
endfunction
com! -complete=customlist,InsertTemplateComplete -nargs=1 InsertTemplate
    \ call InsertTemplate(<f-args>)

com! InsertTime :normal a<C-R>=strftime('%F %H:%M:%S.0 %z')<CR>

" :Jrnl | add a journal entry | for use with shrc function.
" create a dedicated file and prepare for writing it with markdown.
function! s:MakeJournalEntry() abort
  cd $JOURNAL
  let l:fname = $JOURNAL . '/' . strftime('%Y_%m_%d.md')
  exe 'edit ' . l:fname
  if filereadable(l:fname) ==? v:false
    exe 'norm I# ' . strftime('%A, the %d of %B %Y')
  endif
  exe "normal! Go\<CR>## " . strftime('%H:%M')
  exe "normal! o\<CR>"
  startinsert
endfunction
com! Jrnl :call <SID>MakeJournalEntry()

" :LongLines
com! LongLinesSearch silent lvimgrep /\%>79v.\+/ %
com! LongLinesHighlight match ErrorMsg /\%>79v.\+/

" :Lr | to wrap lr(1) and open files on return
" :Lr <lr-args> to browse lr(1) results in a new window
com! -nargs=* -complete=file Lr
    \ silent exe "R" "lr" <q-args> | res | silent f [lr] | map <buffer><CR> $hgF

" :Lt
com! -nargs=* -complete=dir Lt silent exe "R" "lr -oM" <q-args> | res | silent f | map <buffer><CR> $hgF
"nn <Leader><Enter> :Lt<CR>

" :MD5 | show MD5 of the current buffer.
com! -range MD5
    \ echo system('echo '.shellescape(join(getline(<line1>, <line2>), '\n'))
    \ .' | md5')

" :Mkdirwrite | make necessary directories to be able to write current file.
com! Mkdirwrite call <SID>SysR('', 'mkdir -p '. expand('%:h')) | execute('w')

" :NOs
" :Nobackticks | replace `..` with $() notation in shell scripts
com! Nobackticks silent! %s/`\([^`]*\)`/$(\1)/gc

" :Nobl
"com! Nobl g/^\\s*$/d
"com! Nows %s/\\s\\+$//e
" Nomixedquotes %s/'\"'\"'/'\\''/gc

" :Nocurly | replace curly quotes with straight quotes in the entire file.
function! Nocurly() abort
  silent! %s/‘/'/g
  silent! %s/’/'/g
  silent! %s/“/"/g
  silent! %s/”/"/g
endfunction
com! Nocurly call Nocurly()

" :Noecho | replace echo with POSIX compliant printf.
function! Noecho() abort
  silent! %s/echo -e /printf '%b\\n' /g
  silent! %s/echo -ne /printf '%b' /g
  silent! %s/echo -n /printf '%s' /g
  silent! %s/echo -en /printf '%b' /g
endfunction
com! Noecho call Noecho()

function! RemoveFancyCharacters() abort
  let typo = {}
  let typo["“"] = '"'
  let typo["”"] = '"'
  let typo["‘"] = "'"
  let typo["’"] = "'"
  let typo["–"] = '--'
  let typo["—"] = '---'
  let typo["…"] = '...'
  :exe ":%s/".join(keys(typo), '\|').'/\=typo[submatch(0)]/ge'
endfunction
com! Nofancycharacters :call RemoveFancyCharacters()

" :Nohttp | replace http with https.
function! Nohttp() abort
  silent! %s/http:\/\//https:\/\//g
endfunction
com! Nohttp call Nohttp()

" six-per-em space: %s/\%u2006//gc
"todo(2025-12-13): convert to command!
" >grl | remove empty lines if there are more than 2
"nn <Leader>grl :%s/\n\{3,}/\r\r/e
" >rlines | removes empty lines if there are more than 2
"nn <Leader>rlines :%s/\n\{3,}/\r\r/e
" %s/\n\{2,}/\r/gc

" :NoteHeader
function AddNoteHeader()
  let l:note_title = $NOTE_TITLE
  if len(l:note_title) == 0
    let l:name = substitute(trim(expand('%:t')), '.md$', '', '')
    let l:note_title = substitute(l:name, '_', ' ', 'g')
  endif
  call setline(1, '---')
  call setline(2, 'title: '.l:note_title)
  call setline(3, 'created: '.trim(system('date')))
  call setline(4, '---')
  call setline(5, '')
  call setline(6, '<++>')
  exe 'normal! ggjf:llv$'
endfunction
com! NoteHeader call AddNoteHeader()

" :NL | numlines.
com! -range=% -nargs=1 NL
    \ <line1>,<line2>!nl -w <args> -s '. ' | perl -pe 's/^.{<args>}..$//'

" :LocListToQuickfix | QuickfixToLocList
com! LocListToQuickfix call setqflist(getloclist(0))
com! LocListClear call setloclist('.', [])
com! QuickfixToLocList call setloclist(0, getqflist())

" :Qfchoose | :Llchoose
" use a fuzzy-finder to switch betweeen quickfix/location-list history entries.
com! Llchoose
    \ redir => _redir | silent lhistory | redir END
    \ | call <SID>SysR(_redir, 'fzy')
    \ ->matchstr('[0-9]\+') ->W('lhistory') ->execute()

com! Qfchoose
    \ redir => _redir | silent chistory | redir END
    \ | call <SID>SysR(_redir, 'fzy')
    \ ->matchstr('[0-9]\+') ->W('chistory') ->execute()

" :Qfjump | fuzzy-find and edit a file in the quickfix list.
" Jumps to the first match in that file.
" (The qflist does not surface index numbers for some reason, so we need
" a song-and-dance here to retain them and in-order.)
com! Qfjump
    \ call getqflist()
    \ ->map({i, x -> [bufname(x.bufnr), i + 1]})
    \ ->filter({i, x -> x[0] != ''})
    \ ->reverse()
    \ ->reduce({acc, cur -> extend(acc, {cur[0]: cur[1]})}, {})
    \ ->map({key, val -> val .' - '. key})
    \ ->values() ->sort('N')
    \ -><SID>SysR('fzy -p "Jump > "')
    \ ->matchstr('[0-9]\+')
    \ ->M('crewind ') ->execute()
    \ ->{ -> 'norm zv'}() ->execute()

" :Qf2files | collapse all Quickfix entries into a new Quickfix of unique files.
com! Qf2files
    \ call getqflist()
    \ ->map({i, x -> x.bufnr})
    \ ->filter({i, x -> x != ''})
    \ ->sort() ->uniq()
    \ ->map({i, x -> {'bufnr': x}})
    \ ->setqflist()

" :Qf2ll | copy all quickfix entries for current file into location list entries.
" this is a simple way to skate around a single file without losing your
" position in the qf list.
com! Qf2ll call getqflist()
    \ ->filter({i, x -> x.bufnr == bufnr()})
    \ ->setloclist(0)

" :Qfsave | save the current quickfix list to a file.
com! Qfsave call getqflist()
    \ ->map({i, x -> (
    \     x.bufnr != 0
    \         ? bufname(x.bufnr) .":". x.lnum .":". x.col .":"
    \         : ''
    \ ). x.text })
    \ ->writefile(input('Write? ', 'Quickfix.txt'), 's')

" :BufSaveAsQf | save open buffers to a file that can be loaded as qf list(-q).
com! BufSaveAsQf call getbufinfo()
    \ ->filter({i, x -> x.listed && x.name != ''})
    \ ->map({i, x -> fnamemodify(x.name, ':~') .':'. string(x.lnum) .': '})
    \ ->writefile(input('Write? ', 'Quickfix.txt'), 's')

" :Qftodo | add all TODOs in the current file as quickfix entries.
com! Qftodo silent grep TODO %:p | redraw!

" :R | execute command with output to a scratch buffer.
com! -nargs=+ -complete=shellcmd R new|setl bt=nofile noswf|exe "0r!" <q-args>|0

" :Sil(ent) cmd | run a command cmd inside Vim with terminal output.
" e.g., :Silent lazygit

" :RR | execute command asynchronously to a scratch buffer.
" :RKill to kill it
com! -nargs=+ -complete=shellcmd RR
    \ new|setl bt=nofile noswf| let b:job = job_start(["/bin/sh", "-c", <q-args>], {'out_io':'buffer', 'out_buf':bufnr(), 'pty':1})
com! RKill eval job_stop(b:job)

com! -range=0 -complete=shellcmd -nargs=1 Silent exe 'silent' (<range> > 0 ? '<line1>,<line2>' : '')
    \ (has('gui_running') && exists(':terminal') == 2 ? 'terminal ++close' : '!') <q-args> | exe ':redraw!'
com! -range=0 -complete=shellcmd -nargs=1 Sil exe (<range> > 0 ? '<line1>,<line2>' : '') 'Silent' <q-args>

" :Reload | reload vimrc.
command -bar Reload source $MYVIMRC <Bar> nohlsearch

" :RmAnsi | remove ANSI escape sequences
" com! -range=% -nargs=0 RmAnsi <line1>,<line2>s/\%x1b\[[0-9;]*[Km]//g
" :RmCtrl | remove control characters
" com! -range=% -nargs=0 RmCtrl <line1>,<line2>s/[[:cntrl:]]//g
" Remove ANSI color escape codes for the edited file. This is handy when
" piping colored text into Vim.
"nn <Leader>rac :%s/<C-v><Esc>\[\(\d\{1,2}\(;\d\{1,2}\)\{0,2\}\)\?[m\|K]//g

" :Root | change directory to the root of the git repository.
function! s:root()
  let root = systemlist('git rev-parse --show-toplevel')[0]
  if v:shell_error
    echo 'Not in git repo'
  else
    exe 'lcd' root
    echo 'Changed directory to: '.root
  endif
endfunction
com! Root call s:root()

" :S | convert buffer to/from scratch.
"alias -g VV=' |& vim +S -'
"command S
"    \  if &buftype == 'nofile' | setl swf bt= bufhidden=
"    \| else                     | setl noswf bt=nofile bufhidden=hide | endif
"    \| echo printf('swf=%s bt=%s bh=%s', &swapfile, &buftype, &bufhidden)

" :Fill
" Usage: `call s:fill(git_log_cmd)`
" if type == 'diff' | call s:fill(target) setf diff | endif
function! s:fill(cmd)
  setlocal modifiable
  %delete _
  silent execute 'read' escape('!'.a:cmd, '%')
  normal! gg"_dd
  setlocal nomodifiable
endfunction
com! Fill call <SID>fill(cmd)

" :Scratch | make the current buffer a scratch buffer.
fu! s:Scratch()
  setl buftype=nofile bufhidden=delete nobuflisted
  echo "This file is now a scratch file!"
  return bufnr()
endfu
" call setbufline(bufnr, 1, 'some text')
fu! s:Scratchadd()
  let l:bufnr = bufadd('')
  call bufload(l:bufnr)
  call setbufvar(l:bufnr, '&buftype', 'nofile')
  call setbufvar(l:bufnr, '&bufhidden', 'delete')
  return l:bufnr
endfu
com! Scratch call <SID>Scratch()

" :Redir
function! s:redir_open(cmd, mods) abort
    for win in filter(range(1, winnr('$')), 'getwinvar(v:val, "scratch")')
      exe win . 'windo close'
    endfor
    if a:cmd =~# '^!'
      let cmd = a:cmd =~# ' %' ? substitute(a:cmd, ' %', ' ' . expand('%:p'), '') : a:cmd
      let output = systemlist(matchstr(cmd, '^!\zs.*'))
    elseif a:cmd =~# '^@'
      let output = getreg(a:cmd[1], 1, 1)
    else
      let output = split(execute(a:cmd), "\n")
    endif
    exe a:mods . ' new'
    let w:scratch = 1
    call setline(1, output)
    nnoremap <buffer> q <C-w>q
    setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nomodifiable
    augroup redir
      autocmd BufEnter <buffer> ++nested if winnr('$') < 2 | q | endif
    augroup END
endfunction
"com! -nargs=1 -complete=command Redir call redir#open(<q-args>, <q-mods>)
com! -nargs=1 -complete=command Redir call <SID>redir_open(<q-args>, <q-mods>)
com! -nargs=? Maps <mods> Redir map <args>
com! -nargs=? Marks <mods> Redir marks <args>
com! -nargs=? Registers <mods> Redir registers <args>
"com! -nargs=? Display <mods> Redir display <args>
com! -nargs=? Commands <mods> Redir command <args>
com! -nargs=0 Jumps <mods> Redir jumps
com! -nargs=0 Changes <mods> Redir changes
com! -nargs=0 Digraphs <mods> Redir digraphs
com! -nargs=0 Scriptnames <mods> Redir scriptnames
com! -nargs=0 Messages <mods> Redir messages

" :SaveMacro | :LoadMacro
function! s:save_macro(name, file)
  let content = eval('@'.a:name)
  if !empty(content)
    call writefile(split(content, "\n"), a:file)
    echom len(content) . " bytes save to ". a:file
  endif
endfunction
com! -nargs=* SaveMacro call <SID>save_macro(<f-args>)
function! s:load_macro(file, name)
  let data = join(readfile(a:file), "\n")
  call setreg(a:name, data, 'c')
  echom "Macro loaded to @". a:name
endfunction
com! -nargs=* LoadMacro call <SID>load_macro(<f-args>)

" :SetTab | shortcut change tab width
function! SetTab(...) abort
  if a:0 == 0
    " no arguments means use tabs and make them look like 4 spaces
    set noexpandtab
    set shiftwidth=4
    set tabstop=4
    set softtabstop=4
  else
    " if argument is passed, use n spaces (where n is the argument)
    set expandtab
    "let &tabstop=a:1
    let &softtabstop=a:1
    let &shiftwidth=a:1
  endif
endfunction
com! -nargs=? SetTab :call SetTab(<f-args>)

" :Spaces
function Spaces(num) abort
  exe 'set et'
  exe 'set ts =' . a:num
  exe 'set sw =' . a:num
endfunction
com -nargs=1 Spaces call Spaces(<args>)
com -nargs=1 Tabs :set sts=<args> sw=<args> ts=<args>

" Space2Tab | convert spaces to tabs
com! -range=% -nargs=0 Space2Tab
    \ exe '<line1>,<line2>s#^\( \{'.&ts.'\}\)\+#\=repeat("\t", len(submatch(0))/' . &ts . ')'
" Tab2Space | convert tabs to spaces
com! -range=% -nargs=0 Tab2Space
    \ exe '<line1>,<line2>s#^\t\+#\=repeat(" ", len(submatch(0))*' . &ts . ')'
" >t2 | tab2space
nn <Leader>t2 <Cmd>Tab2Space<CR>
" >t | =tN N-space tabs
"nn <Leader>t2 :set ts=2 sw=2 et<CR>
"nn <Leader>t4 :set ts=4 sw=4 et<CR>
"nn <Leader>t8 :set ts=8 sw=8 et<CR>

" :Spelling
com! -nargs=? Spelling
  \ if empty('<args>') | setl spell! | else | setl spell spl=<args> | endif

" :Todo | add TODO items to quickfix list.
" relative to where you opened Vim
function! s:todo() abort
  let entries = []
  for cmd in ['rg -niw --binary --regexp=TODO --regexp=FIXME . 2>/dev/null',
            \ 'git grep -niIw -e TODO -e FIXME 2>/dev/null',
            \ 'grep -rniIw -e TODO -e FIXME . 2>/dev/null']
    let lines = split(system(cmd), '\n')
    if v:shell_error != 0 | continue | endif
    for line in lines
      let [fname, lno, text] = matchlist(line, '^\([^:]*\):\([^:]*\):\(.*\)')[1:3]
      call add(entries, { 'filename': fname, 'lnum': lno, 'text': text })
    endfor
    break
  endfor
  if !empty(entries)
    call setqflist(entries)
    copen
  endif
endfunction
com! Todo call s:todo()
nn <Leader>td :Todo<CR>

" :TODO
com! TODO vimgrep TODO % | cw

" :Term :Sterm :Vterm | open split terminal
command Sterm split term://$SHELL
command Tterm tabnew term://$SHELL
command Vterm vsplit term://$SHELL

" :T | terminal
com! -nargs=* T botright term <args>
" :Terminal
com! -nargs=* Terminal <mods> split | lcd %:h | terminal ++curwin <args>

" :TP :VT | terminal popup
com! -nargs=* TP botright sp | resize 20 | term <args>
"noremap <C-t> :TP<CR>a
com! -nargs=* VT vsp | term <args>

" :Ybuffer | yank entire buffer
com! -range=% Ybuffer <line1>,<line2>y+
" :Ypath | yank path
com! Ypath let @+=expand('%')

" :Zk
" see: https://kdwarn.net/programming/blog/a-zettelkasten-with-vim-and-bash
function! SaveWithTS() abort
  if !expand('%:t')
    let l:filename = escape(strftime("%Y-%m-%d-%H%M"), ' ')
    exe "write " . "~/projects/zk/notes/" . l:filename . ".md"
  else
    echo 'File already saved and named.'
  endif
endfunction
com! Zk call SaveWithTS()
"noremap <Leader>zl :let @y = "[[" . expand("%") . "]] " <bar> :1,1y z <bar> let @" = @y . @z<CR>

" :W | :Wq | :WQ
com! -bang -nargs=? -complete=file W w<bang> <args>
com! -bang -nargs=? -complete=file Wq wq<bang> <args>
com! -bang -nargs=? -complete=file WQ wq<bang> <args>
" :Q | behaves like :q for windows, but for buffers
com! -bang Q :if len(filter(range(1,bufnr('$')),'bufloaded(v:val)'))==1 | q<bang> | else | bd<bang> | endif
" }}}
" git-commands {{{
" :FindConflicts | grep for conflict markers and add to quickfix list.
com! FindConflicts grep '^<<<<<' %

" :Gdiff | diff unstaged changes.
com! -nargs=* -complete=dir Gdiff
    \ silent exe "R" "git-diff-qf HEAD" <q-args> | res | silent f | map <buffer><CR> 0gF

" :Gitfiles | search through files in repo.
com! -nargs=* -complete=dir Gitfiles
    \ silent exe "R" "git --no-pager log --stat --name-only --format='' " <q-args> | res | silent f | map <buffer><CR> $hgF

" :Gitlog
com! -range -nargs=* -complete=file Gitlog
    \ silent exe "R" "git log --oneline" <q-args> | res | silent f | map <buffer><CR> viw :Gshow<CR>

" :Gshow
com! -nargs=* Gshow cgetexpr system('git show '. expand('<cword>')) | res

" :Gitqf | load Git changes for the specified commits.
com! -nargs=* Gitqf cgetexpr system('git quickfix '. expand('<args>'))

" :Qffromdiff | load all Git changes in the work tree as quickfix entries.
com! Qffromdiff cgetexpr
    \ system('git quickfix -m modified')

" :Llfromdiff | load all Git changes to the current file as location list entries.
com! Llfromdiff lgetexpr
    \ system('git quickfix -m modified -- '. expand('%:p'))

" :Gitweb | open GitHub/GitLab page for the current file (and line range).
com! -range Gitweb
    \ echo system('git web-uri -u '. expand('%') .' '. expand('<line1> <line2>')
    \ .' | xe which-open')

" :GBlame | show git blame window.
com! Gblame :exe 'tabnew +'. line('.') .' %'
    \| :53vnew
    \| :silent! call <SID>Scratch()
    \| :exe 'r !git blame -f --date=relative -- '. expand('#:p:~:.')
    \   ." | awk '{ print $1, substr($0, index($0, \"(\") + 1) }'"
    \| 1delete
    \| :exe line('.', win_getid(winnr('#')))
    \| :windo setl nofoldenable nowrap
    \| :windo setl scrollbind

" :Gannotateline | show full commit for current line.
com! Gannotateline :call
    \ printf("!git blame -l -L %s,+1 -- %s \| awk '{ print $1 }' \| xargs git sh",
    \     getpos('.')[1],
    \     expand('%:p'))
    \ ->execute("")

" :OpenChangedFiles | open a split for each dirty file in git.
function! OpenChangedFiles() abort
  " close all windows, unless they're modified
  only
  let status = system('git status -s | grep "^ \?\(M\|A\|UU\)" | sed "s/^.\{3\}//"')
  let filenames = split(status, "\n")
  exe "edit " . filenames[0]
  for filename in filenames[1:]
    exe "vs " . filename
  endfor
endfunction
com! OpenChangedFiles :call OpenChangedFiles()
" }}}
" key
" mapping {{{
" NOTE:
":map    |mapmode-nvo| :map  | Normal, Visual and Operator-pending
":map!   |mapmode-ic|  :map! | Insert and Command-line

" :%! [cmd]
" :echo mapcheck(';g', 'n')
" <C-[> is Esc
" <C-C> visual -> normal (temporary)
" <C-C> select -> visual (temporary)
" <C-G> select -> visual (definitely)
" <C-O> insert -> normal
"  `0 go to position where Vim was previously exited
" `" go to position when last editing this file
" `. go to position of the last change in this file
" '' go to last line before jump
" ga | g8 | ascii utf8 chars value
" }}}
" fn-maps {{{
" f1/f2 | toggle the quickfix and location list windows.
com! Toggleqf
    \ call getqflist({'qfbufnr': 0}).qfbufnr ->bufwinnr()
    \ ->{x -> x != -1 ? ':cclose' : ':botright copen | :wincmd p'}()
    \ ->execute()

com! Togglell
    \ call getloclist(winnr(), {'qfbufnr': 0}).qfbufnr ->bufwinnr()
    \ ->{x -> x != -1 ? ':lclose' : ':lopen | :wincmd p'}()
    \ ->execute()

map <F1> :Togglell<CR>
map <F2> :Toggleqf<CR>

" <f2> | insert filename *without* path: >.vimrc<.
inoremap <F2> <C-R>=expand('%:t:r')<CR>

" <f3> <s-f3> | jump between locations in quickfix, or differences if in diff.
nnoremap <expr> <F3> (&diff ? "]c" : ":cnext\<CR>")
nnoremap <expr> <S-F3> (&diff ? "[c" : ":cprev\<CR>")

" f4 | repeat last command.
nn <F4> @:
xnoremap <F4> @:
" s-f4 | send output of previous global command to a new window.
nmap <F16> :redir @a<CR>:g//<CR>:redir END<CR>:new<CR>:put! a<CR><CR>

" f5 | search-replace word under cursor
nn <F5> :%s/<C-R><C-w>/<C-R><C-w>/gc<C-F>$F/i
vnoremap <F5> y:%s/\<<C-R>"\>/<C-R>"/gc<left><left><left>
" <s-f5> | search non-ascii characters
nn <F17> /[^\x00-\x7F]<CR>

" toggle using tabs vs spaces
function! TabToggle()
  if &shiftwidth == 2
    setlocal shiftwidth=0
    setlocal softtabstop=0
    setlocal noexpandtab
    echo "Tabs"
  elseif &shiftwidth == 0
    setlocal shiftwidth=4
    setlocal softtabstop=4
    setlocal noexpandtab
    echo "4/8"
  elseif &shiftwidth == 4 && !&expandtab
    setlocal shiftwidth=4
    setlocal softtabstop=4
    setlocal expandtab
    echo "Spaces 4"
  else
    setlocal shiftwidth=2
    setlocal softtabstop=2
    setlocal expandtab
    echo "Spaces 2"
  endif
endfunction
nnoremap <F6> :call TabToggle()<CR>

" <f8> | update "Last Change" line.
map <F8> msHmtgg/Last [cC]hange:\s*/e+1<CR>"_D"=strftime("%Y %b %d")<CR>p'tzt`s
map <F20> msHmtgg/Last [mM]odified:\s*/e+1<CR>"_D"=strftime("%Y %b %d")<CR>p'tzt`s

" Shortcut: F7 = Run anything with a shebang, Shift+F7 for arguments
fun! RunFile(...)
  if exists('b:interpreter')
    let l:run_str = '!'.b:interpreter.' %'
  elseif exists('b:f7_run_cmd')
    let l:run_str = '!'.b:f7_run_cmd
  endif
  if a:0 == 1 && a:1 == 1
    exec(l:run_str)
  else
    call feedkeys(':' . l:run_str . ' ')
  endif
endfun
map <F7> :call RunFile(1)<CR>
map <F19> :call RunFile()<CR>
"anoremenu Tools.Run<Tab><F7>  :call RunFile()<CR>

" f11 | popup terminal.
"nmap <F11> :let $VIMCONFIG=expand('%:p:h')<CR>:vert terminal<CR>cd $VIMCONFIG<CR>
"nmap <F11> :!tmux popup -E -w 160 -h 40 -d $(pwd)<CR>

" f11 | open current directory on a terminal. shown on vertical split window.
nmap <F11> :lcd %:p:h<CR>:bel terminal<CR>
imap <F11> <Esc>:lcd %:p:h<CR>:bel terminal<CR>
" launch a new terminal window in the current working directory of Vim
" we use setsid here to decouple the new terminal from Vim. otherwise,
" pressing ^Z in Vim to pause it would also pause the new terminal,
" which is very irritating.
" closing the FDs works around VTE bug #204.
"map <Leader>sx :silent !setsid --fork terminal-wrapper </dev/null >/dev/null 2>&1<CR>

" f12 | toggle mouse.
nmap <F12> <Esc>:exe &mouse!=""? "set mouse=" : "set mouse=nvi"<CR>
imap <F12> <Esc>:exe "normal \<F12>"<CR>i
vmap <F12> <Esc>:exe "normal \<F12>"<CR>v

" TODO(2025-09-29): indenting options
"set comments +=fb:*,fb:[-],fb:[+],fb:>>,fb:[1],fb:[2],fb:[3],fb:[4],fb:[5],fb:[6],n::
"set fo +=n2
" compile + run macro
"nn c :!clang % -o %:r && ./%:r
"nn cpp :!c++ % -o %:r && ./%:r
"nn jv :!javac % && java %:r
"nn py :!python %<CR>
" LaTeX compile
" <Cmd>!xelatex '%'<CR>
" <Cmd>!xelatex --shell-escape 'main'<CR>
" }}}
" basic {{{
" annoys to no end
map q: :
nn q/ q/
nn q <Nop>

" <alt-x> | escaping
nnoremap <A-x> <ESC>
inoremap <A-x> <ESC><right>
vnoremap <A-x> <ESC>
snoremap <A-x> <ESC>
tnoremap <A-x> <C-\><C-n>
cmap <A-x> <ESC>
nnoremap ^@ <ESC>
inoremap ^@ <ESC>
vnoremap ^@ <ESC>
cmap ^@ <ESC>
" move cursor to last insert position
"inoremap <C-c> <ESC>`^
" for de keyboards
inoremap jj <ESC>`^

" no ex mode
"nn Q <Esc>
" Q | no ex mode. quit.
"nn Q :<Cmd>q<CR>

" Q | reflows the current paragraph/selection
"map Q gq
map Q gwap
vmap Q gq
" >Q | formats the current paragraph
"nn <Leader>Q gqap
" >q | formats the current paragraph
"nn <Leader>q gqap

"nn Q q
"map <Leader>wq Vapgq<CR>
"map Q gq
" dont use Ex mode, use Q for formatting
"nn Q gqap
"vnormap Q gq

" >w <c-s> | save
nnoremap <C-s> :update<CR>
"nnoremap <C-s> :<C-U>update<CR>
"inoremap <C-s> <Esc>:update<CR>a
inoremap <C-s> <C-O>:update<CR>
vnoremap <C-s> <C-C>:update<CR>
nn <Leader>w :update<CR>
nn <Leader>W :update!<CR>

" >q <c-q> | quit
nnoremap <C-q> :q<CR>
inoremap <C-q> <Esc>:q<CR>
vnoremap <C-q> <Esc>:q<CR>
nn <Leader>q :q<CR>

" >p <alt-V> | paste from system clipboard
nor <Leader>p "+p
imap <A-V> <Space><Backspace><ESC>"+pa
if has('mac')
  " paste from clipboard. only works on mac. on linux use system-copy plugin
  map <Leader>p :set paste<CR>o<Esc>"*]p:set nopaste<CR>:retab<CR>
  " <cmd-> | osx mappings
  nnoremap <D-s> :w<CR>
  vnoremap <D-c> "+y
  nnoremap <D-v> "+P
  vnoremap <D-v> "+P
  cnoremap <D-v> <C-R>+
  inoremap <D-v> <ESC>l"+Pli
  nnoremap <D-a> ggVG
  inoremap <D-a> <C-O>gg<C-O>VG
  nor <D-v> +p<CR>
  cmap <D-v> <C-R>+
  imap <D-v> <C-R>+
  tmap <D-v> <C-R>+
  vmap <D-v> <C-R>+
endif

" >y | yank to system clipboard
nn Y y$
vnoremap y "+y
nn <Leader>Y "+y$
nn <Leader>y "+y
xnoremap <Leader>y "+y
" Y | make Y be consistent with C and D which reach the end of line
if has('linux')
  " copy to attached terminal using the yank(1) script:
  function! Yank(text) abort
    let escape = system('yank', a:text)
    if v:shell_error
      echoerr escape
    else
      call writefile([escape], '/dev/tty', 'b')
    endif
  endfunction
  noremap <Leader>y y:<C-U>call Yank(@0)<CR>
  " >p will paste clipboard into buffer
  "nn <Leader>p <Cmd>read !wl-paste<CR>
  " automatically run yank(1) whenever yanking in Vim
  " (this snippet was contributed by Larry Sanderson)
  function! CopyYank() abort
    call Yank(join(v:event.regcontents, "\n"))
  endfunction
  autocmd TextYankPost * call CopyYank()
endif

" HJKL | quickly move cursor
nn K 7<up>
nn J 7<down>
nn H 0
nn L $
vnoremap K 5<up>
vnoremap J 5<down>
vnoremap H 0
vnoremap L $h

" <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
vnoremap <S-right> $<left>
tnoremap <S-left> <C-a>
tnoremap <S-right> <C-e>

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

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

" nn <A-h> vg0
" nn <A-l> v$h
" vnoremap <A-h> 0
" vnoremap <A-l> $h
" nn <A-f> vF
" nn <A-t> vT
" vnoremap <A-f> F
" vnoremap <A-t> T

" <a-o> | add a line without changing position or leaving mode
" nor <A-o> :set paste<CR>m`o<Esc>``:set nopaste<CR>
" nor <A-O> :set paste<CR>m`O<Esc>``:set nopaste<CR>
" map <A-o> <Cmd>call append(line('.'), repeat([''], v:count1))<CR>
" map <A-O> <Cmd>call append(line('.') - 1, repeat([''], v:count1))<CR>
" imap <A-o> <C-G>u<C-O>o
" imap <A-O> <C-G>u<C-O>O

" ,, | comment/uncomment
nmap ,, gcc
vmap ,, gcgv

" add comment below/above
"nn gco o<esc>Vcx<esc><cmd>normal gcc<cr>fxa<bs>
"nn gcO O<esc>Vcx<esc><cmd>normal gcc<cr>fxa<bs>

" & | repeat last :substitute command with previous flags
nn & :&&<CR>
xnoremap & :&&<CR>

" in Visual Mode I almost never want $ to select the newline
"noremap $ g_

" remove operator
nn x "_d
xnoremap x "_d
nn X "_D
nn xx "_d_

" <c-z> | bg in insert mode. write before suspending
nn <C-z> :update<CR>:stop<CR>
inoremap <C-z> <C-O>:update<CR><C-O>:stop<CR>
" }}}
" format {{{
" NOTE: 'ep'
" to run reformatter, select text and press '='
" to run reformatter on whole file, use 'go=<Enter>'
function! SyntaxName() abort
  return synIDattr(synID(line('.'), col('.'), 1), 'name')
endfunction

function! ReflowText() abort
  if SyntaxName() =~? 'comment'
    normal! gqac
  else
    normal! gqap
  endif
endfunction
" <alt-q> | ReflowText
nn <A-q> :call ReflowText()<CR>
xnoremap <A-q> gq
imap <A-q> <C-O><A-q>

function! s:ExecuteRestoringView(cmd) abort
  " https://breeze.hostux.net/vim/wiki/Restore_the_cursor_position_after_undoing_text_change_made_by_a_script
  normal! ix
  normal! x
  let l:view = winsaveview()
  let l:old_shellredir = &shellredir
  let l:errfile = tempname()
  let &shellredir = '>%s 2>' . l:errfile
  try
    silent exe a:cmd
  finally
    let &shellredir = l:old_shellredir
    call winrestview(l:view)
  endtry
  if v:shell_error isnot 0
    call s:Error(readfile(l:errfile)[0])
  endif
endfunction

" formatcode
function! FormatCode(...) abort range
  if exists('b:format_command')
    let l:cmd = b:format_command
  elseif &filetype is# 'awk'
    let l:cmd = 'gawk -f- -o/dev/stdout'
  elseif &filetype is# 'c' || &filetype is# 'cpp'
    let l:cmd = 'clang-format'
  elseif &filetype is# 'css'
    let l:cmd = 'deno fmt --ext=css' . ' -'
  elseif &filetype is# 'caddyfile'
    let l:cmd = 'caddy fmt --overwrite' . ' -'
  elseif &filetype is# 'html'
    "let l:cmd = 'tidy -config $HTML_TIDY'
    let l:cmd = 'tidy -quiet --indent yes --indent-spaces 2 --tidy-mark no --wrap 80'
  elseif &filetype is# 'just'
    let l:cmd = 'just --fmt --unstable --check'
  elseif &filetype is# 'markdown'
    let l:cmd = 'pandoc -f markdown -t gfm -sp --tab-stop=2'
  elseif &filetype is# 'perl'
    let l:cmd = 'perltidy'
  elseif &filetype is# 'rst'
    let l:cmd = 'pandoc -f rst -t rst -s --columns=79'
  elseif &filetype is# 'rust'
    let l:cmd = 'rustfmt'
  elseif &filetype is# 'sh' || &filetype is# 'bash' || &filetype is# 'zsh'
    let l:cmd = 'shfmt -i 2 -bn -ci' . ' -'
  else
    let l:ft = empty(&filetype) ? '<no filetype>' : &filetype
    call s:Error('Unable to format ' . l:ft . ' file')
    return
  endif
  let l:first = split(l:cmd)[0]
  if !executable(l:first)
    call s:Error('Executable not found: ' . l:first)
    return
  endif
  let l:range = get(a:, 1, a:firstline . ',' . a:lastline)
  call s:ExecuteRestoringView(l:range . '!' . l:cmd)
endfunction
nn <Leader>af :call FormatCode('%')<CR>
xnoremap <Leader>af :call FormatCode()<CR>

" lintcode
" todo(2026-02-24): py:pylint rust:analyzer-cargo
"                   c:clangtidy-clangd cpp:clangtidy-cppcheck
function! LintCode(...) abort range
  if exists('b:lint_command')
    let l:cmd = b:lint_command
  elseif &filetype is# 'sh'
    let l:cmd = 'shellcheck -'
  else
    let l:ft = empty(&filetype) ? '<no filetype>' : &filetype
    call s:Error('Unable to lint ' . l:ft . ' file')
    return
  endif
  let l:first = split(l:cmd)[0]
  if !executable(l:first)
    call s:Error('Executable not found: ' . l:first)
    return
  endif
  let l:range = get(a:, 1, a:firstline . ',' . a:lastline)
  exe l:range . 'w !' . l:cmd
endfunction
nnoremap <Leader>al :call LintCode('%')<CR>
xnoremap <Leader>al :call LintCode()<CR>
" }}}
" expandsnip {{{
" utils
function! ExpandSnip(snip) abort
  let line = getline('.')
  call setline('.', line . a:snip)
  redraw
  call inputsave()
  let expand_value = input('{++}: ')
  call inputrestore()
  call setline('.', line . substitute(a:snip, '{++}', expand_value, 'g'))
endfunction

" common
"map ;; /<++><CR>:noh<CR>cf>
nnoremap ;; /<++><CR>:noh<CR>"_cf>
inoremap ;; <Esc>/<++><CR>:noh<CR>"_cf>
vnoremap ;; <Esc>/<++><CR>:noh<CR>"_cf>
" }}}
" co | h l m n r w {{{
" -----------------------------------------------------------------------------
" co? : toggle options (inspired by unimpaired.vim)
" -----------------------------------------------------------------------------
function! s:map_change_option(...) abort
  let [key, opt] = a:000[0:1]
  let op = get(a:, 3, 'set '.opt.'!')
  exe printf("nnoremap co%s :%s<Bar>set %s?<CR>", key, op, opt)
endfunction

call s:map_change_option('b', 'background',
    \ 'let &background = &background == "dark" ? "light" : "dark"<Bar>redraw')
call s:map_change_option('c', 'conceallevel', 'let &cole = &cole == "" ? "1" : "0"')
call s:map_change_option('f', 'ff', 'let &ff = &ff == "" ? "unix" : ""')
call s:map_change_option('g', 'spell',
    \ 'if &spell<Bar>set nospell nowrap tw=80<Bar>else<Bar>set spell wrap fo-=c tw=0<Bar>endif')
call s:map_change_option('h', 'hlsearch')
call s:map_change_option('l', 'colorcolumn', 'let &cc = &cc == "" ? "80" : ""')
call s:map_change_option('m', 'mouse', 'let &mouse = &mouse == "" ? "nvi" : ""')
call s:map_change_option('n', 'number')
call s:map_change_option('p', 'list',
    \ 'if &list<Bar>set nolist nonu nofen noru nosmd nosc noci nosi noai spell cpt+=s<Bar>else<Bar>set list nu fen ru ai nospell cpt-=s<Bar>endif')
call s:map_change_option('r', 'relativenumber', 'let &relativenumber = &relativenumber == "" ? "1" : "0"')
call s:map_change_option('s', 'shiftwidth', 'let &sw = &sw == "" ? "4" : "2"')
call s:map_change_option('t', 'textwidth',
    \ 'let &textwidth = input("textwidth (". &textwidth ."): ")<Bar>redraw')
call s:map_change_option('w', 'wrap')
call s:map_change_option('y', 'syntax',
    \ 'if exists("g:syntax_on")<Bar>syntax off<Bar>else<Bar>syntax enable<Bar>endif<Bar>redraw')
call s:map_change_option('z', 'spell',
    \ 'if &spell<Bar>set nospell cpt-=kspell<Bar>else<Bar>set spell cpt+=kspell<Bar>endif')
" }}}
" normal {{{
" NOTE: :help key-notation
" <c-d>/<c-u> scroll window downwards/upwards
" <Bar> vs \|
" \|    | works if 'b' is not in 'cpoptions' `:map _l :!ls \| more`
"'[  '] | jump to the beginning and end of previous change
"
" delete comment blocks+blank lines :g/\m^$\|^\s*"/d
" delete blank lines                :g/^$/d
" delete empty lines                :g/^\s\+$/d
" delete lines quoted               :g/^[> ]\+$/d
"
" squeeze empty lines:              :g/^$/,/./-j
" squeeze blank lines:              :g/^\s*$/,/\S/-j

" don't use fish for 'shell', but if it exists use it as the default shell in
" terminal buffers
"nn <expr> `<CR> '<Cmd>bo term' .. (executable('zsh') ? ' zsh' : '') .. '<CR>'
"nn <expr> `<Space> ':bo te '

"nn <Leader>t :<C-U>terminal<CR>
"nn <Space><Space>t :terminal<CR><C-w>T

" <enter> | quick command mode - except in quickfix window
nn <expr> <CR> &buftype ==# 'quickfix' ? "\<CR>" : ':'
" <backspace> | go to previous buffer, but ignore unloaded ones
nn <BS> <Cmd>exe v:count ? v:count .. 'b' : 'b' .. (bufloaded(0) ? '#' : 'n')<CR>
" <esc><esc> | clear highlights
"nn <Esc><Esc> :nohls<CR>

" * | make * respect smartcase and also set @/ (to enable 'n' and 'N')
nmap *  :let @/ = '\<'.expand('<cword>').'\>' ==? @/ ? @/ : '\<'.expand('<cword>').'\>'<CR>n
"nn <Leader>* :<C-U>let @/ = expand('<cword>') <Bar> let &hlsearch = &hlsearch<CR>

" - | fold-unfold
nn <silent> - @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>
" + _ | duplicate line above/below
nn + "0yy<up>"0p
nn _ "0yy"0p

" / ? | mark position to 's' before search, jump back with <'s>
"nn / ms/
"nn ? ms?

" <tab>/<s-tab> | circular buffer-tab navigation
function! NextBufOrTab() abort
  if tabpagenr('$') > 1
    tabnext
  else
    bnext
  endif
endfunction
function! PrevBufOrTab() abort
  if tabpagenr('$') > 1
    tabprevious
  else
    bprevious
  endif
endfunction
nn <Tab> :call NextBufOrTab()<CR>
nn <S-Tab> :call PrevBufOrTab()<CR>

" @c | box comments
"nn @c I# <Esc>A #<Esc>yyPlvt#r-yyjp

" 0p | easier "0p
nn 0p "0p

" cd | change directory to directory of current file
nn cd :exe 'cd ' . expand ('%:p:h')<CR>:pwd<CR>
" cp | change directory to previous dir
nn cp :lcd -<CR><Bar>:pwd<CR>

" D | delete to end of line
nn D d$
" dP | diffput current line only
nmap dP :.diffput<CR>
" dw | word delete a word backwards
nn dw vb"_d

" NOTE:
" g; g, | previous/next insertion
" gh    | start select mode
" g8    | print hex value of bytes used in UTF-8

" g# g* | recursive to pick up the * mapping
"nmap g# #:vimgrep // %<CR>
"nmap g* *:vimgrep // %<CR>
" g* | execute current line as macro
"nmap g* my"yyy@y`y
"map <F3> "ayy@a<CR>

" g! | execute current line as shell command
nmap g! :exe "!".getline('.')<CR>
" g= | indent line/selection as much as line above
nmap g= :le <C-R>=indent(line('.')-1)<CR><CR>
vmap g= :'<,'>le <C-R>=indent(line('v')-1)<CR><CR>
"nn g= mvgg=G`g
" g. | open directory file is in
"nmap g. :e %:h<CR>
" g. | go to last buffer modification position
nn g. `.
" g/tr | trim blanks
nn g/tr :%s/\s\+$//gic<CR>
" gb | better list and change buffers
nn gb :ls<CR>:b<Space>
" gf | open file under cursor w linenr
nmap gf gF
" gI | goto last insert spot. gi moves to last insert mode (default)
nn gI `^
" gK | use gK for keywordprg, since K gets mapped to 'hover'
nn gK K
" gl | go to line end
nn gl $
" gn | make gn jump into visual block mode, instead if plain visual mode
"nn gn gn<C-V>
" gq | formatting
" format whole buffer with formatprg without changing cursor position
"nn gq<CR> mzgggqG`z
"nn gq? <Cmd>set formatprg? formatexpr?<CR>
" gs | sort
function! Sort(type, ...) abort
  '[,']sort
  call setpos('.', getpos("''"))
endfunction
nn gs m'<Cmd>set operatorfunc=Sort<CR>g@
" gv | select last selection
" gV | select last insertion/edited
nn gV `[v`]
"nn gV `[V`]
" gY
nn gY <Cmd>let @+=@*<CR>
" gx
" openurl {{{
function! OpenURL(query) abort
  if a:query != ""
    let l:url = shellescape(a:query, 1)
    silent! exe "!browser ".l:url
  else
    if &filetype == 'qf'
      if w:quickfix_title =~# '^:\(shellcheck\|L\?ShellCheck\)'
        let id = matchstr(getline('.'), ' \(error\|warning\|note\) \zs\d\+\ze')
        if id =~# '^\d\+$'
          let l:url = "https://github.com/koalaman/shellcheck/wiki/SC" . id
        endif
        echo l:url
      elseif w:quickfix_title =~# '^:\(mdl\)'
        let l:url = matchstr(getline('.'), '[a-z]*:\/\/[^ >,;")]*')
        echo l:url
      endif
    else
      " URLs end in letter, digit or forward slash
      "url_re= '\%(\%(http\|ftp\|irc\)s\?\|file\)://\S\{-}'
      "URL= matchstr(expand('<cWORD>'), '\<' .. l:url_re .. '\ze[^A-Za-z0-9/]*$')
      let l:re = '\%(\%(http\|ftp\|irc\)s\?\|file\)://\S\{-}\ze[^A-Za-z0-9/]*$'
      let l:cl = matchstr(expand('<cWORD>'), l:re)
      if l:cl == ""
        let l:cl = matchstr(getline('.'), l:re)
      endif
      "let l:url = escape(matchstr(cl, '[a-z]*:\/\/\/\?[^ >,;()]*'), '#%')
      "let l:url = escape(matchstr(cl, '[a-z]*:\/\/\/\?[^ >,;()]*'), '%')
      "let l:url = matchstr(cl, '[a-z]*:\/\/\/\?[^ >,;()]*')
      let l:url = matchstr(cl, '[a-z]*:\/\/[^ >,;''")]*')
      "let l:url = matchstr(getline('.'), '[a-z]*:\/\/[^ >,;''")]*')
      "let s:uri = matchstr(getline('.'), '[a-z]*:\/\/[^ >,;()]*')
      ""\\[][\\`*_{}()<>#+.!-]"
    endif
    if empty(l:url)
      "if &filetype == 'vim' || &filetype == 'help'
      " open the current URL
      " - if line begins with "Plug" open the github page of the plugin.
      let cl = getline('.')
      let url = escape(matchstr(cl, '[a-z]*:\/\/\/\?[^ >,;()]*'), '#%')
      if cl =~# 'Plug'
        let pn = cl[match(cl, "'", 0, 1) + 1 :
                  \ match(cl, "'", 0, 2) - 1]
        let url = printf('https://github.com/%s', pn)
      endif
    endif
    if l:url != ""
      let l:url = shellescape(l:url, 1)
      silent! exe "!browser ".l:url
      :redraw!
    else
      silent! exe "!xdg-open %"
    endif
  endif
endfunction
" }}}
nn <silent> gx :call OpenURL('')<CR>
vnoremap <silent> gx :call OpenURL(<SID>GetSelection())<CR>

"vim.keymap.set("n", "tt", ":10 split term://zsh<CR>", opts)
"vim.keymap.set("n", "tv", ":vsplit term://zsh<CR>", opts)

" U | redo
nn U <C-R>
" vv | select line (without newline)
nn vv ^vg_

" vm | VisualVLine {{{
function! s:VisualVLine() abort
  let [_, lnum, col; _] = getcurpos()
  let line = getline('.')
  let col += strdisplaywidth(line) - strwidth(line)

  let [from, to] = [lnum, lnum]
  while strdisplaywidth(getline(from - 1)) >= col
    let from -= 1
  endwhile

  while strdisplaywidth(getline(to + 1)) >= col
    let to += 1
  endwhile

  return "\<C-V>" .
      \ (to == lnum ? '' : (to - lnum . 'jo')) .
      \ (from == lnum ? '' : (lnum - from . 'k'))
endfunction
" }}}
nn <expr> vm <SID>VisualVLine()

" for search
"nn v/ /\v
"vnoremap z/ <Esc>/\%V
"vnoremap z? <Esc>?\%V

" zG | add to custom dict
nn zG 2zg
" zi | insert one char
"map <expr> m 'i'.nr2char(getchar())."\<Esc>"
map zi i$<Esc>r
" zl | zip right
" moves the character under the cursor to the end of the line.
"     foo => println()foo
" source this line, place your cursor on ), press zl and you'll understand
"    println()foo
nn zl :let @z=@"<CR>x$p:let @"=@z<CR>

" z | folds
" z-up/down/left/right | jump between folding nodes
nn z<left> zk
nn z<right> zj
nn z<up> [z
nn z<down> ]z
" z+hjkl | jump between folding nodes
"nn zh zk
"nn zl zj
nn zj ]z
nn zk [z
" zo | recursively open top level fold we are in. no matter where cursor is.
nn zo zCzO
" Mnemonic: "z This" | show fold we're currently in, collapse all other folds.
nn zT zMzvzczO

" bracket-maps
" ]a | argument-list
nn [a :prev<CR>
nn ]a :ne<CR>
nn [A :first<CR>
nn ]A :last<CR>
" ]b | buffers
nn [b :bp<CR>
nn ]b :bn<CR>
nn [B :first<CR>
nn ]B :blast<CR>
" ]L | location-list
nn [L :lfirst<CR>
nn ]L :llast<CR>
" ]Q | quickfix
nmap [Q :cfirst<CR>
nmap ]Q :clast<CR>
" ]t | tag movements
nn [t :tp<CR>
nn ]t :tn<CR>
nn [T :tfirst<CR>
nn ]T :tlast<CR>
" ]space | blank line above/below
nn [<Space> :<C-U>put! =repeat(nr2char(10), v:count1)<CR>'[
nn ]<Space> :<C-U>put =repeat(nr2char(10), v:count1)<CR>
" show an outline of the current buffer
nn gO <Cmd>exe 'lvim /^#\+\(.*\)/ % \| lope'<CR>

" ]c | jump to diffs
nn [c [czz
nn ]c ]czz
" ]l | location-list
nn [l :lprev<CR>zz
nn ]l :lnext<CR>zz
" ]q | quickfix
nn [q :cprev<CR>zv
nn ]q :cnext<CR>zz

" unimpaired style mappings
" ]e | move line above/below
nn <expr> [e '<Cmd>.move --' . v:count1 . '<CR>'
nn <expr> ]e '<Cmd>.move +' . v:count1 . '<CR>'
xnoremap <expr> [e ':move --' . v:count1 . '<CR>gv'
xnoremap <expr> ]e ':move +' . (v:count1 + line('''>') - line('''<')) . '<CR>gv'
" ]j | jump list
nn [j <C-o>zz
nn ]j <C-i>zz
" ]s | spellcheck
nn [s [szz
nn ]s ]szz
" ]w | window
nn [w <C-w>W
nn ]w <C-w>w

" leader
" -----------------------------------------------------------------------------
" ><leader> | toggle between qf window + back
nmap <silent><expr> <Leader><Leader> &buftype ==# 'quickfix' ? ':bd<CR>' : ':cw\|silent only<CR>'
" keybindings for easy movement with content tags
"nn <Leader><Leader> /<++><CR>"_c4l
"nn <Leader><Space> :let @/=""<CR>

" >* | grep for the word under the cursor.
nn <Leader>* :grep <cword><CR>

" >, | jump to last edit position mark. think "where was I?" `"
nor <Leader>, `.
sunmap <Leader>,

" leader< leader> | adjust indent of last edit; good for pasting.
nn <Leader><lt> :<C-U>'[,']<lt><CR>
nn <Leader>> :<C-U>'[,']><CR>

" >/ | :vimgrep ready to enter a search pattern.
nn <Leader>/ :<C-U>vimgrep /\c/j **<S-left><S-left><right>

" >\ | open a quickfix window for the last search.
"nn <Leader>\ :exe 'vimgrep /'.@/.'/g %'<CR>:copen<CR>
" q/ | open a quickfix window for the last search.
"nn q/ :exe 'vimgrep /'.@/.'/g %'<CR>:copen<CR>
" stolen from Steve Losh vimrc:
" open a Quickfix window for the last search.
"nnoremap <Leader>q/ :exe 'vimgrep /'.@/.'/g %'<CR>:copen<CR>

" ># | display number of matches for last search
nmap <Leader># :%s///gn<CR>

" >8 | insert an organizing ruler
"nn <Leader>8 80i#<Esc>

" markdown headings
" -----------------------------------------------------------------------------
" >0-4 >m1 >m2
nn <Leader>0 :s/\v^#+ *//e<CR>
nn <Leader>1 :s/\v^#+ *//e<CR>0i#<space><Esc>0:nohls<CR>
nn <Leader>2 :s/\v^#+ *//e<CR>0i##<space><Esc>0:nohls<CR>
nn <Leader>3 :s/\v^#+ *//e<CR>0i###<space><Esc>0:nohls<CR>
nn <Leader>4 :s/\v^#+ *//e<CR>0i####<space><Esc>0:nohls<CR>
nn <Leader>5 :s/\v^#+ *//e<CR>0i#####<space><Esc>0:nohls<CR>
nn <Leader>m1 m`yypVr=``
nn <Leader>m2 m`yypVr-``

" :ReIndent | reindent entire file.
"com! ReIndent call Preserve("normal! gg=G<C-O><C-O>zz")

" preserve cursor position when joining lines
"nnoremap J :call Preserve("normal! J")<CR>
" split line and preserve cursor position
"nnoremap S :call Preserve("normal! i\r")<CR>

" >$ | fix mixed EOLs (^m) carriage returns U+000D
nor <Leader>$ :call Preserve("%s/<C-V><CR>//e")<CR>
" >9 | strip trailing whitespaces
nn <Leader>9 :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar><CR>
" _s is used to save and restore the last search pattern
" register (so next time the user presses n they will continue their last search)
"nn <F5>      :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar>:nohl<Bar>:unlet _s<CR>
" <F5> :let _s=@/ <Bar> :%s/\s\+$//e <Bar> :let @/=_s <Bar> :nohl <Bar> :unlet _s <CR>

" >" | surround
nnoremap <Leader>" viW<Esc>a"<Esc>hBi"<Esc>lel
" \b | put word in braces
nmap <Leader>} bi{<Esc>ea}<Esc>
" \q | wrap in ``
"nmap <Leader>` bi`<Esc>ea`<Esc>
" \p | wrap in ()
"nmap <Leader>) bi(<Esc>ea)<Esc>
"inoremap <buffer> ;lkj <Esc>Bi`<Esc>Ea`<Esc>A
"      ,) and ,( :
vmap <Leader>( v`<i(<Esc>`>a)<Esc>
vmap <Leader>) v`<i(<Esc>`>a)<Esc>

" surround text with characters
" surround('foo', 1, '<')   // => <foo>
"fu! s:Surround(text, is_inline, surround_char, ...)
"  let l:common_pairs = {
"      \'[': ']', ']': '[',
"      \'{': '}', '}': '{',
"      \'(': ')', ')': '(',
"      \'<': '>', '>': '<',
"  \}
"
"  let l:open = a:surround_char
"  let l:close = get(l:common_pairs, l:open, l:open)
"
"  if !a:is_inline
"    let l:open = l:open ."\n"
"  endif
"
"  let l:ret = substitute(a:text, '^', l:open, "")
"  let l:ret = substitute(l:ret, '$', l:close, "")
"
"  return l:ret
"endfu
""" Surround a visual selection of opfunc movement with characters.
" E.g., to surround with parens: \s(iw
" TODO: Is this really better than: c<motion>"<C-r><C-o>""<Esc>
"nmap <expr> <leader>s( opfuncwrapper#WrapOpfunc('surround#Surround', 1, '(')
"nmap <expr> <leader>s[ opfuncwrapper#WrapOpfunc('surround#Surround', 1, '[')
"nmap <expr> <leader>s{ opfuncwrapper#WrapOpfunc('surround#Surround', 1, '{')
"nmap <expr> <leader>s< opfuncwrapper#WrapOpfunc('surround#Surround', 1, '<')
"nmap <expr> <leader>s" opfuncwrapper#WrapOpfunc('surround#Surround', 1, '"')
"nmap <expr> <leader>s' opfuncwrapper#WrapOpfunc('surround#Surround', 1, "'")
"nmap <expr> <leader>s` opfuncwrapper#WrapOpfunc('surround#Surround', 1, '`')
"nmap <expr> <leader>s_ opfuncwrapper#WrapOpfunc('surround#Surround', 1, '_')
"nmap <expr> <leader>s* opfuncwrapper#WrapOpfunc('surround#Surround', 1, '*')
"nmap <expr> <leader>ss opfuncwrapper#WrapOpfunc('surround#Surround', 1,
"    \input("Surround with what chars? "))
"vmap <silent> <leader>s( :<C-U>call opfuncwrapper#WrapOpfunc('surround#Surround', 0, '(')<cr>

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

" >A/I | prepend/append to all adjacent lines with same indentation
nmap <Leader>A ^vio<C-V>$A
nmap <Leader>I ^vio<C-V>I

" >. | run configured make program into the location list
"nn <Leader>. :<C-U>lmake!<CR>
" >aa | run configured make program into quickfix
nn <Leader>a <Cmd>make! %<CR>
" quickfix :make
"nmap <Leader>m :wa<CR>:silent! make \| redraw! \| cw<CR><CR>
"vmap <Leader>m :wa<CR>:silent! make \| redraw! \| cw<CR><CR>
" >aq | :QuickFixAddCurrent
nn <Leader>aq <Cmd>caddexpr expand('%') .. ':' .. line('.') ..  ':' .. getline('.')<CR>

" >as | ASCII small
nn <Leader>as <Cmd>.!figlet -d ~/.local/share/fonts/figlet -w 100 -f 3d<CR>

" >b | buffer-maps
" >bb | switch buffer
nn <Leader>b :ls<CR>:b<Space>
nn <Leader>bb <Cmd>e #<CR>
" >bc | close current buffer - but first switch to previous buffer
nn <Leader>bc :bp<Bar>:bd#<CR>
" Mnemonic: (b)uffer (o)nly | close all buffers but current
" :BufOnly | close all buffers but current one
com! BufOnly silent! exe "%bd|e#|bd#"
nn <Leader>bo :BufOnly<CR>
" >bQ | close all the buffers
nmap <Leader>bQ :bufdo bd<CR>
" Mnemonic: (b)uffer (s)earch | buf-search
nn <Leader>bs :cex []<Bar>bufdo vimgrepadd @@g %<Bar>cw<S-left><S-left><right>

" view error
"nn qi <Cmd>cc<CR>
" >.. | jump to quickfix current error number
"nn <Leader>.. :cc<CR>

" >c | close quickfix/location window
nmap <Leader>c :ccl<Bar>lcl<CR>

" >cd >ud | change directory to the path of the current file; and back again
nn <Leader>cd :lcd %:p:h<CR><Bar>:pwd<CR>
nn <Leader>ud :lcd -<CR><Bar>:pwd<CR>

" Mnemonic: (c)urrent(f)ile --
" >cfl | full path + line number (/usr/blah/src/foo.txt:2023)
nn <Leader>cfl :let @+=expand('%:p') .':' . line(".") \| :echo getreg('+')<CR>
" >cfn | filename only (foo.txt) | also "% register
nn <Leader>cfn :let @+=expand('%:t')<CR>
" >cfp | full path
nn <Leader>cfp :let @+=expand('%:p')<CR>
" >cfr | relative path
nn <Leader>cfr :let @+=expand('%')<CR>

" >cu | put a commented out duplicate of current line above it
nmap <Leader>cu mc"0yy"0Pgcc'c

" >cx >ux | chmod +x make current file executable - reverse
nn <Leader>cx <Cmd>!chmod u+rwx %<CR>
nn <Leader>ux <Cmd>!chmod -x %<CR>

" >d= >d- >d~ | :Divider
" use `:normal` rather than `:normal!` so the mapping works recursively.
function! Divider(char)
  let len = strlen(getline('.'))
  call append('.', repeat(a:char, len))
  normal! j
endfunction
nor <Leader>d= :call Divider('=')<CR>
nor <Leader>d- :call Divider('-')<CR>
nor <Leader>d~ :call Divider('~')<CR>
" iabbrev <expr> === getline('.')[0:2] == '===' ? '/*====================*/' : '==='

" >d | insert date in my format
nmap <silent> <Leader>d a<C-R>=tolower(strftime('%d%b%Y'))."  +".$USER."+"<CR><Esc>
" >dh | date header
nmap <Leader>dh :.!date +\%Y-\%m-\%d<enter>o==========<Esc>

" >du | refresh the diff
"nmap <silent> <Leader>du :diffupdate<CR>

" >ee es et ev | edit-files: in buffers path
" Synonyms: {e: edit, where: {w: window, s: split, v: vertical split, t: tab}}
nn <Leader>ee :e <C-R>=expand('%:p:h').'/'<CR>
nn <Leader>es :sp %:p:h/<Tab>
nn <Leader>ev :vs %:p:h/<Tab>
nn <Leader>et :tabe <C-R>=escape(expand('%:p:h'), " ")<CR>/
"nn <Leader>ew :e %:p:h/<Tab>
" eb - edit files in ~/.local/bin
nmap <Leader>eb :next ~/bin/

" >fl | to fill line with character
nn <Leader>fl y1l$80p079ld$

" Mnemonic: (f)ind in (b)uffers (c)loclist (d)ir (l)ines (w)ord
" >fb | search all file buffers (clear qf first)
nn <Leader>fb  mS:<C-U>cexpr []<Bar>exe 'bufdo silent! noau vimgrepa/\C/j %'<Bar>bo cope<S-left><S-left><left><left><left>
" >fc | search current buffer and open results in loclist
nn <Leader>fc  ms:<C-U>lvimgrep // % <Bar>lw<S-left><left><left><left><left>
" >fd | grep current dir (no-ignore-case).
nn <Leader>fd  mS:<C-U>vimgrep /\C/j **<left><left><left><left><left>
" >fl | display all lines with keyword under cursor, ask which one to jump to
"nn <Leader>fl [I:let nr = input("Which one: ")<Bar>exe "normal! " . nr ."[\t"<CR>
" >fs | find last search in quickfix
nn <Leader>fs :exe 'vimgrep /'.@/.'/g %'<CR>:copen<CR>
" >fw | search word under cursor in current dir + all subdirectories + open qf
nn <Leader>fw :exe "vimgrep /" . expand('<cWORD>') . "/j **" <Bar>cw<CR>
" >fW | search word under cursor in current file + open qf
"nn <Leader>fW :vimgrep /<C-R><C-w>/gj **/*<CR>:copen<CR>

" >ft | shortcut to set filetype=
nn <Leader>ft<Space> :set ft=
nn <Leader>ftm :set ft=markdown<CR>
nn <Leader>fts :set ft=sh<CR>

" >gf | open file under cursor in existing split
"nn <Leader>gf 0gf
" >gf | open directory file is in
nmap <Leader>gf :e %:h<CR>
" open file in previous window
"nn <silent>gp :let mycurf=expand('<cfile>')<CR><C-w>p:execute("e ".mycurf)<CR>

"nn gs :vertical wincmd f<CR>
"nn gi <C-w>f
"" >gf | go to file in a vertical split
"nn <Leader>gf :vertical botright wincmd F<CR>

" >gj | join two or more space to a single space
nmap <Leader>gj vip:s/  \+/ /g<CR>
vmap <Leader>gj    :s/  \+/ /g<CR>

" >gl | git log
nn <Leader>gdc <Cmd>Redir !git changed<CR>
nn <Leader>gl <Cmd>Redir !git log --oneline<CR>
nn <Leader>gt <Cmd>Redir !git log --patch --max-count=1<CR>
" >gs | git show HEAD
nn <Leader>gs <Cmd>exe "!git show " .expand('<cword>')<CR>

" >gr/gR | for replace
" see: https://overflow.adminforge.de/questions/597932/#597932
" local replace
"nn <Leader>gr gd[{V%::s/<C-R>///gc<left><left><left>
" global replace
"nn <Leader>gR gD:%s/<C-R>///gc<left><left><left>

" >gw | search word under cursor
nn <Leader>gw :grep! "\b<C-R><C-w>\b"<CR>:cw<CR>

" >hi | display RGB color under the cursor eg #445588 #FFB545
nmap <Leader>hi :hi Normal guibg=#<C-R>=expand('<cword>')<CR><CR>
" >hl | SyntaxName
nn <Leader>hl :echo SyntaxName()<CR>

" >hs | split
nn <Leader>hs <Cmd>split<CR>

" >ll | show listchars and cursorcolumn; highlight lines more than 80 chars,
" trailing spaces, only whitespace.
nn <silent> <Leader>ll
  \ :set nolist!<CR>:set nolist?<CR> <Bar>
  \ :set cursorcolumn!<CR>:silent set cursorcolumn?<CR> <Bar>
  \ :if exists('w:long_line_match') <Bar>
  \   silent! call matchdelete(w:long_line_match) <Bar>
  \   unlet w:long_line_match <Bar>
  \ elseif &textwidth > 0 <Bar>
  \   let w:long_line_match = matchadd('ErrorMsg', '\%>'.&tw.'v.\+', -1) <Bar>
  \ else <Bar>
  \   let w:long_line_match = matchadd('ErrorMsg', '\%>80v.\+', -1) <Bar>
  \ endif<CR>

" >ls | list search results in location window
nn <Leader>ls :lv /<C-R>=expand('<cword>')<CR>/ %<CR>:lw<CR>

" :Marksjump
function! s:marks_jump() abort
  marks abcdefghijklmnopqrstuvwxyz.
  echo 'Jump to mark: '
  let l:mark=nr2char(getchar())
  redraw
  exe 'normal! `'.l:mark
endfunction
com! Marksjump call <SID>marks_jump()
nn <Leader>j <Cmd>Marksjump<CR>

" explorer mappings
" >n | netrw
nn <Leader>n :Lex<CR>
"nn <Leader>nt :NERDTreeToggle<CR>
"nn <Leader>nf :NERDTreeFind<CR>
"nn <Leader>nn :e .<CR>
"nn <Leader>nd :e %:h<CR>

" netrw -not a plugin, but replaces one (:-
" map ctrl-t to NetRW
"map <C-t> :Vexplore<CR>
"nn <Leader>tv :Vexplore<CR>
"nn <Leader>tx :Explore<CR>
" netrw-mappings
" c-B - file-explorer - open on the left
" :e .
" :Exp(lore)     : file explorer note capital Ex
" :Sex(plore)    : file explorer in split window
" display marked files.
" :echo netrw#Expose("netrwmarkfilelist")
"command! Oexplore exe 'Explore' getcwd()
"nnoremap <C-o> :Explore<CR>
" Open on the left
"nnoremap <Leader>v :Hexplore<CR>
"nnoremap <Leader>V :Oexplore<CR>

" >ni >nn >nv
"nn <Leader>ni :e $NOTE_DIR/index.md<CR>:cd $NOTE_DIR<CR>
" :Ngrep | 'Notes Grep' search markdown using ripgrep
"com! -nargs=1 Ngrep :silent grep! "<args>" -i -g '*.md' $NOTE_DIR | exe ':redraw!'
"com! -nargs=1 Ngrep grep "<args>" -g "*.md" $NOTE_DIR
" >nn | 'Notes Grep' search markdown using ripgrep
"nn <Leader>nn :Ngrep
" :Vlist | open quickfix list in right vertical split (good for Ngrep results)
com! Vlist botright vertical copen | vertical resize 50
nn <Leader>nv : Vlist<CR>

" >o | oldfiles
function! ListOldFiles() abort
  "return v:oldfiles[:10]
  let l:f = filter(copy(v:oldfiles), "v:val !~ 'PRE\\|Net\\|tags\\|^/tmp/\\|^/opt/\\|.git/'")
  return l:f[:10]
  \ ->mapnew({idx, filename -> (idx + 1) .. "\t" .. filename .. "\t" .. (idx + 1)})
  \ ->join("\n")
endfunction
nn <Leader>o :echo ListOldFiles()<CR>:edit #<

" search-replace
" -----------------------------------------------------------------------------
" NOTE: count-items
" :%s/./&/gn        characters
" :%s/\i\+/&/gn     words
" :%s/^//n          lines
" :%s/the/&/gn      "the" anywhere
" :%s/\<the\>/&/gn  "the" as a word
" vip:w !wc -w      words in current paragraph

" show a character count of the current paragraph
"nmap `` vip:w !wc -c<cr>
"vmap ``    :w !wc -c<cr>

" :%s/FILE/\=expand("%:t")

" substitute
" -----------------------------------------------------------------------------
" S | easier :%s///g search-replace word under cursor everywhere =>
nnoremap S :%s//g<left><left>
"vnoremap S :s//g<left><left>

" quick replace
"nn <Leader>sr :%s/\<<C-R><C-w>\>//I<left><left>
" replace under cursor
"nn <Leader>sr :%s/\<<C-R><C-w>\>/
" global replace
"nn <Leader>sg :%s//g<left><left>
" change all matches
"nn cM :%s/<C-R>///g<left><left>
" delete all search matches
"nn dM :%s/<C-R>//g<CR>

" substitute in visual selection
" :'<,'>s/\%V//g
" :s/\%V/g
"xnoremap s :s/\%V//g<left><left><left>
xnoremap s/ <Esc>:s/\%V//g<left><left>

" search-replace selected text
"" <c-r> | visual search-replace current selection
"vnoremap <C-r> "hy:%s/<C-R>h//gc<left><left><left>
"vnoremap <C-r> "hy:%s/<C-R>h//gc<left><left><left>
"xmap <F5> "hy:%s/<C-R>h//gc<left><left><left>

"" <c-s> | easier substitute
"vnoremap <C-s> :s/\%V//g<left><left><left>

" s | search-replace
"vnoremap s //e<C-R>=&selection=='exclusive'?'+1':''<CR><CR>
"    \:<C-U>call histdel('search',-1)<Bar>let @/=histget('search',-1)<CR>gv
"omap s :normal! vs<CR>

" >s | search-replace word under cursor.
nn <Leader>s :%s/<C-R><C-w>//gc<left><left><left>
vnoremap <Leader>s "+y<C-C>:%s/<C-R>"//gc<left><left><left>

"nn <Leader>s :%s/\\<C-R><C-w>\\>/<C-R><C-w>/gI<left><left><left>
" >s | search-replace - global and ask for confirmation.
"nn <Leader>s :%s///gc<left><left><left><left>

" \s | search-replace within the current file.
"nn \s :let @s='\<'.expand('<cword>').'\>'<CR>:%s/<C-R>s//<left>

"nn \s :%s/<C-R><C-w>//<left>
"xnoremap \s "sy:%s/<C-R>s//<left>

" \S | search-replace project-wide using grep.
"nn \S
"  \ :let @s='\<'.expand('<cword>').'\>'<CR>
"  \ :let &grepprg=&grepprg . ' -w'<CR>
"  \ :silent grep <C-R><C-w><CR>
"  \ :let &grepprg='rg --vimgrep --smart-case'<CR>
"  \ :cfdo %s/<C-R>s// \| update
"  \ <left><left><left><left><left><left><left><left><left><left><left>
"xnoremap \S
"  \ "sy\|
"  \ :silent grep <C-R>s<CR>
"  \ :cfdo %s/<C-R>s// \| update
"  \ <left><left><left><left><left><left><left><left><left><left><left>

" >l | lint
"nn <Leader>l :make lint \| cwindow<CR>
" >r | grep current word
"nn <Leader>r :grep <cword> \| cwindow<CR>

" >rw | [r]eplace [w]ord under cursor and all occurences.
nn <Leader>rw :%s/\<<C-R><C-w>\>//g<left><left>
xnoremap <Leader>rw y:<C-U>%s/<C-R>"//g<left><left>
"nn <Leader>rc :%s/\<<C-R><C-w>\>/
"vnoremap <Leader>rc y:%s/<C-R>"/

" without prefilled pattern
"nn gss :%s///g<left><left><left>
" last search pattern
"nn gs/ :%s///g<left><left>
" from default register
"nn gs" :%s/<C-R>"//g<left><left>

"nn <Leader>r :<C-U>%s/\C\<<C-R><C-w>\>/<C-R><C-w>/g<left><left>
"nn <Leader>s        :%s/\<<C-R><C-w>\>/<C-R><C-w>/gI<left><left><left>

" >cc | allows you to easily change current word and all occurrences.
" the difference between this and the previous mapping is that the mapping
" below pre-fills the current word for you to change.
"nn <Leader>cc :%s/\<<C-R><C-w>\>/<C-R><C-w>
vnoremap <Leader>cc y:%s/<C-R>"/<C-R>"

" >r | regexp
"nnoremap g/ :<C-U>%s/\C\<<C-R><C-w>\>//g<left><left>
"nnoremap g? :<C-U>%s/\C\<<C-R><C-w>\>//gc<left><left><left>
"xnoremap g/ :s/\C\<<C-R><C-w>\>//g<left><left>
"xnoremap g? :s/\C\<<C-R><C-w>\>//gc<left><left><left>
"" regexp
"noremap <Leader>r :<C-U>%s/\v//g<left><left><left>
"xnoremap <Leader>r "sy:%s/\v<C-R>=substitute(@s, '/', '\\/', 'g')<CR>//g<left><left>

" >rs | quickly search-replace the word under the cursor
nn <Leader>rs :keeppatterns %s/\<<C-R>=expand('<cword>')<CR>\>/
vnoremap <Leader>rs :<C-U>keeppatterns '<,'>s/

" >r" | 7 special registers.
" tip: `:reg0` what you last yanked not affected by delete.
nn <Leader>r" :reg .-/%:*"<CR>

" >sa >si >st | linting.
map <Leader>sa /[^\x00-\x7F]<CR>
map <Leader>si :%s/[^[:space:]]\zs[[:space:]]\{2,\}\ze[^[:space:]]/ /gc<CR>
map <Leader>st :%s/[[:space:]]\+$//gc<CR>

" >sep = | print a n-char line separator + commented
nn <Leader>sep 76i=<Esc><Cmd>norm gcc<CR>
"map <Leader>sep 36i* <Esc>x
" >sp -  | print a 78-char line separator + commented
nn <Leader>sp 76i-<Esc><Cmd>norm gcc<CR>

" >so | sort words in string
nmap <Leader>so :.!perl -pe 's/"\K(.*?)(?=")/join(" ",sort(split(" ", $1)))/eg'<CR>

" >sw | swap two words
nmap <Leader>sw "0dawb"0Pe

" >t | tab-maps
" default: <c-tab> g<tab>
nn <Leader>tc :tabclose<CR>
nn <Leader>th :tabfirst<CR>
nn <Leader>tj :tabprev<CR>
nn <Leader>tk :tabnext<CR>
nn <Leader>tl :tablast<CR>
nn <Leader>tn :tabnew<CR>
nn <Leader>to :tabonly<CR>
nn <Leader>tp :tabp<CR>
" move tab to first position
nn <Leader>tH :tabm 0<CR>
nn <Leader>tL :tabm<CR>
"nn <Leader>ft<Space> :set ft=

" TS | TT | convert from/to spaces/tabs..
nn <Leader>TS :set expandtab<CR>:%retab!<CR>
nn <Leader>TT :set noexpandtab<CR>:%retab!<CR>

" >x | create scratch buffer, run a command, send output to that scratch buffer
" -----------------------------------------------------------------------------
" run `<space>x`, type `rg --vimgrep TODO` to get a buffer filled in with todos
" type `:cbufer` convert to a quickfix list. easier navigation with `:cn` `:cp`
nn <Leader>x :exe 'nos vnew'<Bar>:set bt=nofile<Bar>:set bh=wipe<Bar>:call setline(1, systemlist(input('')))<CR>

" >X | run current line as if it were a command
"nn <Leader>X :exe getline(line('.'))<CR>

" get me the function name!
"map _F ma[[k"xyy`a:echo @x

" " in addition to C-w: delete word around/after the cursor
"imap <C-d> <C-O>daw
"nmap <C-d> daw

" put a commented out duplicate of the current line above it
"nmap <Leader>= mcyyPgcc`c
"nmap <C-d> mzyyp`z

" <alt-1..5> | tab navigation
nn <A-1> :tabn 1<CR>
nn <A-2> :tabn 2<CR>
nn <A-3> :tabn 3<CR>
nn <A-4> :tabn 4<CR>
nn <A-5> :tabn 5<CR>

" <alt-.> | select last inserted text
"nn g. :normal! `[v`]<CR><left>
"nn g. :normal! `[v`]<CR><left>
"nn <A-,> <Esc>`[v`]
"nn <A-.> <Esc>:normal! `[v`]<CR><left>
"nn <A-i> vi

" <alt-'> | all registers. {{{
" NOTE:
" %  current filename
" 1  unnamed register ""
" 2  10 numbered registers "0 to "9
" 3  small delete register "-
" 4  26 named registers "a to "z or "A to "Z
" 5  three read-only registers ":, "., "%
" 6  alternate buffer register "#
" 7  expression register "=
" 8  selection registers "* and "+
" 9  black hole register "_
" 10 last search pattern register "/
" }}}
nn <A-'> :<C-U>registers<CR>
inoremap <A-'> <Esc><Cmd>Registers<CR>

" replace tabs with four spaces. make sure that there is a tab character between
" the first pair of slashes when you copy this mapping into your .vimrc!
"nn <Leader>rts :%s/  /    /g
"nn <Leader>r4t :%s/ \{4\}/ /g
"nn <Leader>r2t :%s/ \{2\}/ /g

" >ul | UrlToMarkdownLink: paste raw url => :call UrlToMarkdownLink()<CR>
function! UrlToMarkdownLink() abort
  normal! diW
  normal! a[]()
  " paste url twice
  normal! PBp2T/
  " keep last part of url
  normal! dT[
  s/\.html//e
  " titelize last part of url
  normal! "ayi[
  if exists('g:loaded_abolish')
    call setreg('a', substitute(getreg('a'), '-', '_', 'g'))
  else
    call setreg('a', substitute(getreg('a'), '-', ' ', 'g'))
  endif
  normal! di[h"ap
  if exists('g:loaded_abolish')
    normal hcrt
  endif
  " check for trailing slashes
  normal! f]h
  let l:lastChar = getline('.')[col('.')-1]
  if l:lastChar ==# '/'
    normal! x
  endif
endfunction
" >ul | convert pasted url to markdown link
"nn <Leader>ul :call UrlToMarkdownLink()<CR>
"nn <Leader>ur <Cmd>silent w !urlview<CR>
"nn <Leader>ur :w<Home>silent <End> !urlview<CR>

" >un | insert codepoint of character under cursor on next line in form U+XXXX
nn <Leader>un mz"zylo<C-R>=printf('U+%04X', char2nr(@z))<CR><Esc>`z

" select word/WORD under cursor
" >v | use + (vim-expand-region)
" >V | use ++/+++/++++ (vim-expand-region)
nn <Leader>v viw
nn <Leader>V viW

" >vi | edit $VIMCONFIG/
nn <Leader>vi :Lt $VIMCONFIG/<CR>
" >vs | vsplit
nn <Leader>vs <Cmd>vsplit<CR>
" >vv | openlastfile
nn <silent> <Leader>vv :exe 'edit' v:oldfiles[0]<CR>

" >zz | open a new tab of the current buffer and cursor position ("tmux-esque zoom")
nmap <Leader>zz :exe 'tabnew +'. line('.') .' %'<CR>

" \r | get output of shell command in vim window
function! SplitRunCommand()
  call inputsave()
  let l:cmd = input('Command: ')
  new
  setlocal buftype=nofile
  call append(0, systemlist(l:cmd))
  call inputrestore()
endfunction
nn <Leader>R :call SplitRunCommand()<CR>

" use :tjump | :tjump opens a menu if multiple tags match whereas :tag does not
"nn <C-]> g<C-]>
"nn g[ :pop<CR>
"xnoremap <C-]> g<C-]>

" 2<c-g> | gives more verbose information, use it by default.
" please note that here we need to prevent a loop in the mapping by
" using the comamnd "noremap"!
nor <C-g> 2<C-G>

" <c-n> <c-m> | quickfix shortcuts
"map <C-n> :cn<CR>
"map <C-m> :cp<CR>

"nn <C-t><C-s> m'A<C-R>=strftime('%Y%m%dT%H%M%S')<CR>

" c-w/. | swap windows
nn <C-w>. <C-w>r
" c-w/h | horizontal window
nn <C-w>h <C-w>s
" c-w/O
" Mnemonic: (w)indow(o)nly | make last active window the only window
nn <C-w>O <C-w>p<C-w>o
" c-w/Q | tabclose
nn <C-w>Q :tabclose<CR>
" c-w/z | generic close
nn <C-w>z :wincmd z<Bar>cclose<Bar>lclose<CR>
" c-w/c-d | open dup in diffmode
function! OpenDup(file) abort
  let l:filename = a:file . ".dup"
  exe 'vsplit' l:filename
  windo diffthis
endfunction
nn <C-w><C-d> :call OpenDup(@%)<CR>
" c-w/c-t | duplicate current tab
" :DuplicateTab
function! s:duplicate_tab() abort
  let s:ssop = &ssop
  try
    let &ssop = 'blank,help,folds,winsize,localoptions'
    let s:file = tempname()
    exe 'mksession ' . s:file
    tabnew
      exe 'source ' . s:file
  finally
    silent call delete(s:file)
    let &ssop = s:ssop
    unlet! s:file s:ssop
  endtry
endfunction
com! DuplicateTab call <SID>duplicate_tab()
nn <C-w><C-t> <Cmd>DuplicateTab<CR>
" c-w/c-w | go to last accessed window
nn <C-w><C-w> :wincmd p<CR>

" <alt-a> | select entire file
" >ww | visual block the whole page
"map <Leader>ww ggVG<CR>
" >wv | format entire page with textwidth=78
"map <Leader>wv ggVGgq<CR>
noremap <A-a> ggVG
inoremap <A-a> <Esc>ggVG
" mapping separately for visual - select modes to always end up in visual mode
snoremap <A-a> <Esc>ggVG
xnoremap <A-a> <Esc>ggVG

" <a-j> | keep the cursor in place while joining lines.
nnoremap <A-j> mzJ`z
" <a-j> | join lines without space
vnoremap <A-j> J:s/( /(/g<CR>:s/,)/)/g<CR>
" J to join line
"vnoremap J :left<CR>gv:join!<CR>gv:s/,/, /ge<CR>gv=gv:s/\s\+$//e<CR>

" NOTE: lower/uppercase
"guu  : current line upper => lower
"gUU  : current LINE lower => upper
"guw  : to end of current WORD upper => lower
"guaw : all of current WORD => lower
"gUw  : to end of current WORD lower => upper
"gUaw : all of current WORD => upper
"g~~  : case to entire line
"g~w  : case to current WORD
"guG  : to lowercase until the end of document
"gU)  : until end of sentence to upper case
"gu}  : to end of paragraph to lower case
"gU5j : 5 lines below to upper case
"gu3k : 3 lines above to lower case
" <alt-u> | upper (U)/lower (u)/switch (~) case
"nn <A-u> <Esc>g~iw
" }}}
" insert {{{
" break undo/delete
inoremap <C-u> <C-G>u<C-u>
inoremap <C-w> <C-G>u<C-w>

inoremap <S-Tab> <C-\><C-O><<

" inserts the text on the clipboard as a link target into the text, using the
" previous word as the link text: [word](https://link.target)
"inoremap <C-]> <C-G>u<Esc>Bi[<Esc>Ea](<C-R>+)
" make the currently selected text the text of a markdown link.
" URL is in clipboard, register '+'.
" when hitting 'c' in visual mode, deleted text will be in register '"'.
"vnoremap <C-]> c[<C-R>"](<C-R>+)<Esc>

" <alt-enter> | equivalent: 'norm! o'
"inoremap <A-CR> <C-G>u<C-O>o
" <alt-b> <alt-f> | back/forward a word
inoremap <A-b> <C-Left>
inoremap <A-f> <C-Right>
" <alt-d> | delete forward word
inoremap <A-d> <C-O>"_dw
" <alt-D> | delete to end of line
" inoremap <A-D> <C-O>lv$h"_d
inoremap <A-D> <Esc>l"_Da
" <alt-u> <alt-U> | undo typed text vs redo
inoremap <A-u> <C-G>u<C-O>u
inoremap <A-U> <C-G>u<C-O><C-R>
" <alt-v> | go to visual mode
inoremap <A-v> <Esc>V

" nice feature.
" type (in the insert-mode) 4+4<c-b> and you will get the result.
" NOTE: '<c-a>' won't work under screen because <c-a><c-a> is a default
"        Keybinding of screen *g*
" '*' == sum            |       '+' == product
" '-' == difference     |       '/' == quotient
" '%' == remainder      |       '^' == scale(a^b) = min(scale(a)*b
"inoremap <C-b> <C-O>yiW<End>=<C-R>=<C-R>0<CR>

" ins-completion
" <ctrl-space> | map omnicompletion to <ctrl-space>.
" inoremap <Nul> <C-X><C-O>

" <c-x>f | map file completion relative to current file path.
" Usage: ./<ctrl-f>[navigate up/down completions]<tab><tab>[etc]<ctrl-y>
" inoremap <C-x>f <C-O>:let b:oldpwd = getcwd()<Bar>lcd %:p:h<CR><C-X><C-F>
" Maps file completion relative to current file path.
" Usage: ./<ctrl-f>[navigate up/down completions]<tab><tab>[etc]<ctrl-y>
inoremap <C-F>
    \ <C-O>:let b:oldpwd = getcwd() <bar>
    \ lcd %:p:h<cr><C-X><C-F>

"" <c-x>l | whole lines
"inoremap <C-x><C-l> <C-x><C-l>
"" <c-x>w | keyword completion from the current buffer => <c-b><c-n> to extend
"inoremap <C-x><C-w> <C-x><C-p>

" spelling
"inoremap <C-l> <C-g>u<Esc>[s1z=gi<C-g>u
"set spo+=camel

" completion and behavior of <Tab> in insert mode
function! TabWrapper()
  if strpart( getline('.'), 0, col('.')-1 ) =~ '^\s*$'
    return "\<Tab>"
  else
    return "\<C-N>"
  endif
endfunction
" function! TabWrapper()
"   let col  = virtcol('.') - 1
"   let end = charcol('.') - 1
"   let line = getline('.')
"   let char = line[end - 1]
"   " cursor at beginning of line or at tab; insert tab
"   if col == 0 || char == "\t"
"     " return "  "
"     return "\<Tab>"
"   endif
"   " cursor at space; insert spaces until next tabstop
"   if char == " "
"     return repeat(" ", &softtabstop - (col % &softtabstop))
"   endif
"   " get start of potential filename
"   let start = end
"   while start > 0 && line[start - 1] =~ '\f'
"     let start -= 1
"   endwhile
"   if start >= 0 && line[start:end] =~ '^\(\~\|\.\|\.\.\)\?/'
"     " filename begins with / or ~/ or ./ or ../
"     return "\<C-X>\<C-F>"
"   else
"     " do regular completion
"     return "\<C-N>"
"   endfi
" endfunction
" <enter> | confirm => `<C-G>u` means break undo chain at current position
inoremap <expr> <Tab> complete_info()['mode'] != "" ? "\<C-N>" : "\<C-R>=TabWrapper()\<CR>"

" chain multiple path completions with <tab> key. Selects the first suggestion
" if no current selection. Use ctrl-y to finish completion as normal.
" imap <expr> <tab> pumvisible()
"     \ ? len(v:completed_item) ? '<C-Y><C-F>' : '<C-N><C-Y><C-F>'
"     \ : '<tab>'

inoremap <expr> <S-Tab> complete_info()['mode'] != "" ? "\<C-P>" : "\<S-Tab>"
inoremap <expr> <Esc> complete_info()['mode'] != "" ? "\<C-E>" : "\<Esc>"
" inoremap <expr> <CR> complete_info()['mode'] != "" ? "\<C-Y>" : "\<CR>"
inoremap <expr> <CR> pumvisible() ? "\<C-Y>" : "\<C-G>u\<CR>"
"inoremap <expr> <Esc> pumvisible() ? "\<C-E>" : "\<Esc>"
" }}}
" operator {{{
" NOTE: common text objects
"iw / aw        # inner word / a word
"is / as        # inner sentence / a sentence
"ip / ap        # inner paragraph / a paragraph
"i( / a(        # inner parentheses / a parentheses
"i[ / a[        # inner brackets / a brackets
"i{ / a{        # inner braces / a braces
"i" / a"        # inner quotes / a quotes
"i' / a'        # inner single quotes / a single quotes
"it / at        # inner tag / a tag (HTML/XML)

"nnoremap ) <cmd>call search('[[:punct:]]', 'e')<cr>
"nnoremap ( <cmd>call search('[[:punct:]]', 'eb')<cr>
"onoremap ) <cmd>call search('[[:punct:]]', 'e')<cr>
"onoremap ( <cmd>call search('[[:punct:]]', 'eb')<cr>

" for easier bracket deletion
"onoremap b i[|
" for easier parens deletion
"onoremap p i(|

" operator snake case & camel case
function! s:search_line(pattern, num, opt)
  for i in range(a:num)
    call search(a:pattern, a:opt, line('.'))
  endfor
endfunction
onoremap s <Cmd>call <SID>search_line('[A-Z_]', v:count1, '')<CR>

" s:textobjects_inIndentation() {{{
" taken from this "Vim Ways" article
" see: https://vimways.org/2018/transactions-pending/
function! s:textobjects_inIndentation()
  " select all text in current indentation level excluding any empty lines
  " that precede or follow the current indentationt level;
  " the current implementation is pretty fast, even for many lines since it
  " uses "search()" with "\%v" to find the unindented levels
  " NOTE: if the current level of indentation is 1 (ie in virtual column 1),
  "       then the entire buffer will be selected
  " magic is needed for this
  let l:magic = &magic
  set magic
  " move to beginning of line and get virtcol (current indentation level)
  normal! ^
  let l:vCol = virtcol(getline('.') =~# '^\s*$' ? '$' : '.')
  " pattern matching anything except empty lines and lines with recorded
  " indentation level
  let l:pat = '^\(\s*\%'.l:vCol.'v\|^$\)\@!'
  " find first match (backwards & don't wrap or move cursor)
  let l:start = search(l:pat, 'bWn') + 1
  " next, find first match (forwards & don't wrap or move cursor)
  let l:end = search(l:pat, 'Wn')
  if (l:end !=# 0)
    " if search succeeded, it went too far, so subtract 1
    let l:end -= 1
  endif
  " go to start (this includes empty lines) and--importantly--column 0
  execute 'normal! '.l:start.'G0'
  " skip empty lines (unless already on one .. need to be in column 0)
  call search('^[^\n\r]', 'Wc')
  " go to end (this includes empty lines)
  execute 'normal! Vo'.l:end.'G'
  " skip backwards to last selected non-empty line
  call search('^[^\n\r]', 'bWc')
  " go to end-of-line 'cause why not
  normal! $o
  " restore magic
  let &magic = l:magic
endfunction
" }}}
xnoremap <silent> ii :<c-u>call <SID>textobjects_inIndentation()<cr>
onoremap <silent> ii :<c-u>call <SID>textobjects_inIndentation()<cr>

" simple text-objects
" -----------------------------
" i_ i. i: i, i; i| i/ i\ i* i+ i% i$
" a_ a. a: a, a; a| a/ a\ a* a+ a% a$
" -----------------------------
" '-', '#', '`' => '%' '$'
for char in [ '_', '.', ':', ',', ';', '<bar>', '/', '<bslash>', '*', '+', '%', '$' ]
  execute 'xnoremap i' . char . ' :<c-u>normal! T' . char . 'vt' . char . '<cr>'
  execute 'onoremap i' . char . ' :normal vi' . char . '<cr>'
  execute 'xnoremap a' . char . ' :<c-u>normal! F' . char . 'vf' . char . '<cr>'
  execute 'onoremap a' . char . ' :normal va' . char . '<cr>'
endfor

" 26 simple text objects
"for char in [ '_', '.', ':', ',', ';', '<bar>', '/', '<bslash>', '*', '+', '-', '#', '`' ]
"  execute 'xnoremap i' . char . ' :<c-u>normal! T' . char . 'vt' . char . '<cr>'
"  execute 'onoremap i' . char . ' :normal vi' . char . '<cr>'
"  execute 'xnoremap a' . char . ' :<c-u>normal! F' . char . 'vf' . char . '<cr>'
"  execute 'onoremap a' . char . ' :normal va' . char . '<cr>'
"endfor

" . | make repeat operator work with visual selections
" allow . to execute once for each line of a visual selection
"vnoremap . :normal .<CR>
xnoremap . `[o`]
onoremap . <Cmd>normal V.<CR>

" line text-objects | vim-textobj-line
xnoremap il g_o^
onoremap il :<C-U>normal vil<CR>
xnoremap al $o0
onoremap al :<C-U>normal val<CR>

xnoremap ik `]o`[
onoremap ik :<C-U>normal vik<CR>
onoremap ak :<C-U>normal vikV<CR>

"" a<space> i<space> | whitespace under cursor as text object
"onoremap <silent> a<space> :let r=@/ \| let @/="\\s*\\(\\%#\\&\\s\\)\\s*" \| :exe "normal! gn" \| let @/=r<CR>
"onoremap <silent> i<space> :let r=@/ \| let @/="\\s\\@<=\\s*\\(\\%#\\&\\s\\)\\s*" \| :exe "normal! gn" \| let @/=r<CR>

"" define a text-object for square brackets
"onoremap ir i[
"onoremap ar a[

" ?ie | entire object
"xnoremap <silent> ie gg0oG$
"onoremap <silent> ie :<C-U>execute "normal! m`"<Bar>keepjumps normal! ggVG<CR>

" ?il | inner line
"xnoremap <silent> il <Esc>^vg_
"onoremap <silent> il :<C-U>normal! ^vg_<CR>

" >_ | use last changed or yanked text as an object
onoremap <Leader>_ :<C-U>exe 'normal! `[v`]'<CR>
" >% >5 uses entire buffer as an object
"onoremap <Leader>% :<C-U>exe 'normal! 1GVG'<CR>
"omap <Leader>5 <Leader>%
" }}}
" visual {{{
" NOTE:
" v_g_CTRL-G: show word, character, line, byte counts for selection

" \n | add line numbers to a list
xmap <Bslash>n :'<,'>%!awk '{ print NR".", $0 }'<CR>

" @ | make macros work with visual selections.
" repeat a macro on a visual selection of lines.
" complete the command by choosing the register containing the macro.
"vnoremap @ :normal @
" repeat a macro on a visual selection of lines
" same as above but with a macro; complete the command by choosing the register
" containing the macro.
vnoremap <Leader>@ :normal @
" support running @{macro} on visual selections
"function! ExecuteMacroOverVisualRange() abort
"  echo "@".getcmdline()
"  exe ":'<,'>norm @".nr2char(getchar())
"endfunction
"xnoremap @ :<C-U>call ExecuteMacroOverVisualRange()<CR>

" / ? | mimic behavior of /%Vfoobar. searches within previous visual selection
" while in search mode, pressing / will do this
vnoremap / <Esc>/\%><C-R>=line("'<")-1<CR>l\%<<C-R>=line("'>")+1<CR>l
vnoremap ? <Esc>?\%><C-R>=line("'<")-1<CR>l\%<<C-R>=line("'>")+1<CR>l

" search for visually highlighted text
"   - press // in visual mode, will:
"     1. Yank highlighted ( 'y'           )
"     2. Initiate search  (  '/'          )
"     3. CTRL-R           (   '<C-R>'     )
"     4. Double-Quote     (        '"'    )
"         (CTRL-R " == PASTE YANKED)
"     5. Return           (         '<CR>')
"vnoremap // y/<C-R>"<CR>
" // | search for visually selected text with 'very no-magic'
xnoremap // y/\V<C-R>"<CR>

" search inside visual selection
"vnoremap <A-/> <Esc>/\%V
"xnoremap ? <Esc>?\%V
"<Esc>/\\%V
"xnoremap / <Esc>/\%V

" very magic
"vnoremap / <Esc>/\%V

"xnoremap / <C-\><C-n>`</\%V
"xnoremap ? <C-\><C-n>`>?\%V

"function! CmdLine(str)
"  call feedkeys(":" . a:str)
"endfunction
"" next/prev instance of visual selection
"function! VisualSelection(direction, extra_filter) range
"  let l:saved_reg = @"
"  exe "normal! vgvy"
"  let l:pattern = escape(@", "\\/.*'$^~[]")
"  let l:pattern = substitute(l:pattern, "\n$", "", "")
"  if a:direction == 'gv'
"    call CmdLine("Rg '" . l:pattern . "' " )
"  elseif a:direction == 'replace'
"    call CmdLine("%s" . '/'. l:pattern . '/')
"  endif
"  let @/ = l:pattern
"  let @" = l:saved_reg
"endfunction
"if !has('nvim')
"  " visual mode pressing * or # searches for the current selection
"  "vnoremap <silent> # :<C-U>call VisualSelection('', '')<CR>?<C-R>=@/<CR><CR>
"  "vnoremap <silent> # :<C-U>call VisualSelection('', '')<CR>?<C-R>=@/<CR><CR>"
"  "vnoremap <silent> * :<C-U>call VisualSelection('', '')<CR>/<C-R>=@/<CR><CR>
"  xnoremap # :<C-U>call VisualSelection('', '')<CR>?<C-R>=@/<CR><CR>
"  xnoremap * :<C-U>call VisualSelection('', '')<CR>/<C-R>=@/<CR><CR>
"endif
"" = | use function to search/replace visually selected text
""xnoremap = :<C-U>call VisualSelection('replace', '')<CR>/<C-R>=@/<CR><CR>

function! GetSelection(one_line) range
  let [lnum1, col1] = getpos("'<")[1:2]
  let [lnum2, col2] = getpos("'>")[1:2]
  let lines = getline(lnum1, lnum2)
  let lines[-1] = lines[-1][: col2 - (&selection == 'inclusive' ? 1 : 2)]
  let lines[0] = lines[0][col1 - 1:]
  let res = join(lines, a:one_line ? '\n' : "\n")
  return res
endfunction
function! ReplaceSelection() range
  let cmd = '":\<c-u>%sno/".GetSelection(1)."/"'
  return ":\<c-u>call feedkeys(". cmd. ", 'n')\<cr>"
endfunction
function! SearchSelection(forward) range
  let cmd = a:forward ? '"/' : '"?'
  let cmd .= '\<c-u>".GetSelection(1)."\<cr>"'
  return ":\<c-u>call feedkeys(". cmd . ", 'n')\<cr>"
endfunction
" make * and # work in visual mode as well
vnoremap <expr> <silent> * SearchSelection(1)
vnoremap <expr> <silent> # SearchSelection(0)

" match-case
"xnoremap # y?\V\C<C-R>"<CR>
"xnoremap * y/\V\C<C-R>"<CR>
" * | visual star
"vnoremap * "sy/<C-R>s<CR>
" for search
"vnoremap * y/<C-R>"<CR>

" aa | make vaa select entire file in visual selection mode
xnoremap aa <Esc>:mark ' \| keepj norm! ggVG<CR>
" gs | sort
xnoremap gs :sort<CR>

" paste replaces selection | paste over selection without yanking
"vnoremap p "_dP
"vmap p d"0P

" p | paste w/o overwriting clipboard (unnamedplus)
" see: https://breeze.hostux.net/vim/wiki/Replace_a_word_with_yanked_text
" p | prevent paste in visual mode from copying text
"xnoremap p p:let @+=@0<CR>:let @"=@0<CR>
" p | dont overwrite default register with the overwritten word
xnoremap p p:let @+=@0<CR>
" P | put from most recent yank instead of scratch register.
xnoremap P "0P

" p | maintain register when pasting over something else
"function! RestoreRegister() abort
"  let @" = s:saved_register
"  return ''
"endfunction
"function! VisualReplaceExpr() abort
"  let s:saved_register = @"
"  return "p@=RestoreRegister()\<CR>"
"endfunction
"xnoremap <expr> p VisualReplaceExpr()

" <space> | indent
"xnoremap <Space> I<Space><Esc>gv

" TODO(2026-02-14): test
" >c >C | format columns in visual mode.
"vnoremap <Leader>c :!sed 's/^/-/' \| column -t \| sed 's/^-//'<CR>
"vnoremap <Leader>C :!sed 's/^/-/' \| column -t \| sed 's/^-//'<CR>gv=

" >cc >ch >ci | comments => json md js
"vnoremap <Leader>cc :s/*\//* \//ge<CR>:noh<CR>gv<Esc>$a*/<Esc>gvo<Esc>^i/*<Esc>
"vnoremap <Leader>ch :s/-->/-- >/ge<CR>:noh<CR>gv<Esc>$a--><Esc>gvo<Esc>^i<!--<Esc>
"vnoremap <Leader>ci <C-V>I//<Esc><Esc>

" >n | number lines
xnoremap <Leader>n :s/\%V/0<C-V><Tab>/<CR>gvg<C-A>gv:retab<Esc>gvI<C-G>u<Esc>gv/ <CR>:s/\%V /./<CR>

" NOTE: sort by line length
" :1,$  ! awk '{ print length(), $0 | "sort -n | cut -d\\  -f2-" }'
" >s | sort lines
vnoremap <Leader>so :sort<CR>
" }}}
" cmdline {{{
" NOTE:
" CTRL-R CTRL-W       : pull word under cursor into a command line or search
" CTRL-R CTRL-A       : pull whole word including punctuation
" CTRL-R -            : pull small register
" CTRL-R [0-9a-z]     : pull named registers
" CTRL-R %            : pull file name (also #)
" :h visual<C-D><Tab> : obtain list of all visual help topics
"                     : then use tab to step through them
" :h ctrl<C-D>        : list help of all control keys
" if `set incsearch`  : CTRL-G next / CTRL-T previous search match

" // | search in visual selection with //
cnoremap <expr> / (getcmdtype() =~ '[/?]' && getcmdline() == '') ? "\<C-C>\<Esc>/\\%V" : '/'

" %% | expand current dir
cnoremap %% <C-R>=expand('%:h').'/'<CR>

" cd. | change working directory to that of the current file
cmap cd. <Cmd>lcd %:p:h<CR>:pwd<CR>

" w!! | sudo save (useful for handling the permission-denied error)
"cmap w!! w !sudo tee % >/dev/null
cnoremap w. w !sudo tee % >/dev/null

" readline-style
cnoremap <C-a> <Home>
cnoremap <C-b> <left>
cnoremap <expr> <C-d> getcmdpos()>strlen(getcmdline())?"\<lt>C-d>":"\<lt>Del>"
cnoremap <C-e> <End>
"cnoremap <expr> <C-f> getcmdpos()>strlen(getcmdline())?&cedit:"\<lt>Right>"
"cnoremap <expr> <C-f> getcmdpos() == (len(getcmdline()) + 1) ? '<C-F>' : '<right>'
cmap <C-g> <C-c>
cnoremap <expr> <C-n> wildmenumode() ? '<C-n>' : '<down>'
cnoremap <expr> <C-p> wildmenumode() ? '<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"

" <c-k> | kill
cnoremap <C-k> <C-\>estrpart(getcmdline(), 0, getcmdpos() - 1)<CR>

" <c-m> | make literal spaces match any whitespace in searches
"cnoremap <C-m> <C-\>e('/?' =~ getcmdtype() ? substitute(getcmdline(), '\\\@<! ', '\\_s\\+', 'g') : getcmdline())<CR><CR>

" cmdline-completion | c_<C-R> {{{
" NOTE:
" c-F filename under the cursor
" c-P filename under the cursor w path
" c-W Word under the cursor
" c-A WORD under the cursor
" c-L line under the cursor
" c-R insert register under cursor
" c-O insert object under cursor
" }}}
" <c-r><c-l> | edit line in cmdline
cnoremap <C-r><C-n> <C-R>=substitute(getline('.'), '^\s*', '', '')<CR>
" <c-r><c-v> | paste from clipboard
cnoremap <C-r><C-v> <C-R>+

cnoremap <C-x><C-a> <C-a>
cnoremap <C-x><C-f> <C-f>
" }}}
" abbreviations {{{
" s:Eatchar | delete the extra char added when using <space> to trigger an abbrev
" e.g., iabbr if if ()<left><C-R>=Eatchar('\s')<CR>
" e.g., iabbr <buffer> if if ()<left><C-R>=<SID>Eatchar('\s')<CR>
function! DelBuffer()
  if !buflisted(bufnr()) || len(getbufinfo({'buflisted':1})) == 1
    return 'quit'
  else
    return 'bdelete'
  endif
endfunction
command! -bang Quit execute DelBuffer() . '<bang>'
cabbrev quit Quit
cabbrev q Quit

func! 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>

cabbrev <expr> eh getcmdtype() == ':' ? 'e~/'.<SID>Eatchar('\s') : 'eh'
cab ,f :for i in range(1, 24) \| execute("map <F".i.">") \| endfor

" varall | shows all global and internal variables
cnorea varall let g: v:
" varbuf | shows all buffer, tab, and window local variables
cnorea varbuf let b: t: w:

cabbrev shckd !shellcheck -o all -x -e 1090 --shell=sh %
cabbrev shfmtd !shfmt -i 2 -ci -bn -d %

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

"iab """ """<CR>"""<up>
iabbrev <silent> abcd ABCDEFGHIJKLMNOPQRSTUVWXYZ <left><C-R>=<SID>Eatchar('\s')<CR>
"iabbrev copy@ © Copyright 2025, all rights reserved.

" me@
iabbrev <expr> me@ printf(&commentstring, tolower(strftime('%d%b%Y'))."  +".$USER."+")
" todo@
iabbrev todo@ <C-R>=printf(&commentstring, 'todo')<CR>(<C-R>=strftime('%Y-%m-%d')<CR>):

" todo/fixme
function! ExpandTodo(tag) abort
  return a:tag."(".strftime('%F').")"
endfunction
inorea <expr> TODO ExpandTodo("TODO")
inorea <expr> FIXME ExpandTodo("FIXME")

" date
iab DT <C-R>=strftime('%Y-%m-%d')<CR>
iab DBOX <C-R>=strftime('[%Y-%m-%d]')<CR>
iab YDT <C-R>=strftime('%y%m%d')<CR>
" `date '+%T %x'`
iab YHP <C-R>=strftime('%D')<CR>

" some simple "expand modifiers":
" insert current filename *with* path: >/home/user/.vimrc<
iab Ypathfile <C-R>=expand('%:p')<CR>

" digraphs | i_<c-k> | :help digraph-table
digr zs 8203|   "U+200B      zero width space
digr es 8337|   "U+2091=ₑ    subscript e
digr xs 8339|   "U+2093=ₓ    subscript x
digr \|\| 8214| "U+2016=‖    double vertical line
digr -- 8212|   "U+2014=—    em dash
digr -^ 8593|   "U+2191=↑    upwards arrow
digr -. 8230|   "U+2026=…    horizontal ellipsis
digr !, 8816|   "U+2270=≰    neither less-than nor equal to
digr !. 8817|   "U+2271=≱    neither greater-than nor equal to
digr fH 9753|   "reversed horizontal fleuron
digr fh 10087|  "horizontal fleuron
digr fv 10086|  "vertical fleuron
"digr -O 8888|   " ⊸
" }}}
" tool
" externals {{{
" gentags
if executable('gentags')
  " :Ctags | convenience for building tag files in current directory
  com! -bar Ctags :wall|silent! !gentags
endif

" github-link
if executable('github-link')
  function! CopyGithubPermaLink() range
    let path = expand('%:p')
    call system('github-link --clip ' . path)
  endfunction
  nn <Leader>gu :call CopyGithubPermaLink()<CR>
  function! OpenGithubPermaLink() range
    let path = expand('%:p')
    call system('github-link --open ' . path)
  endfunction
  nn <Leader>guo :call OpenGithubPermaLink()<CR>
endif

" reader | https://github.com/mrusme/reader
if executable('reader')
  function s:reader_url()
    "let l:uri = matchstr(getline('.'), '[a-z]*:\/\/[^ >,;()]*')
    "let l:uri = shellescape(l:uri, 1)
    "if l:uri != ''
    "  "let mycommand = "reader " . @u
    "  "exe "vertical terminal " . mycommand
    "  exe "terminal " . "reader '".l:uri."'"
    "endif
    normal! "uyiW
    let mycommand = "reader -o " . @u
    exe "new | r!" . mycommand
  endfunction
  noremap <Plug>reader_url :call <SID>reader_url()<CR>
  nmap <Leader>gx <Plug>reader_url
endif

if executable('par')
  "" keybindings for invoking 'par' to reflow text.
  "" 'lf' is for reflowing to shorter lines, usually for commit messages. (f)
  "" 'lg' is for standard 79 columns with 4 space tabs. (g)
  "" 'lh' is like 'lg', except it's for 8 space tabs. (e.g., Go.)
  "vmap \f !par T4 'B=.,?_A_a' 71qr<CR>
  "nmap \f <S-v>\f
  "vmap \g !par T4 'B=.,?_A_a' 79qr<CR>
  "nmap \g <S-v>\g
  ""vmap \h !par T8 'B=.,?_A_a' 79qr<CR>
  ""nmap \h <S-v>\h
  vnoremap <Leader>lf !par T4 'B=.,?_A_a' 71qr<CR>
  nmap <Leader>lf <S-v><Leader>f
  vnoremap <Leader>lg !par T4 'B=.,?_A_a' 79qr<CR>
  nmap <Leader>lg <S-v><Leader>g
  "vnoremap <Leader>lh !par T8 'B=.,?_A_a' 79qr<CR>
  "nmap <Leader>lh <S-v><Leader>h
endif

if executable('typos')
  nn <Leader>ty :!typos %<CR>
endif

" >d64 >e64 | conveniences base64 encoding/decoding.
" for encoding: strip trailing newline to make inline base64 encoding work.
vnoremap <Leader>d64 c<C-R>=system('base64 -d', @")<CR><Esc>
vnoremap <Leader>e64 c<C-R>=system('base64 \| head -n 1', @")<CR><Esc>
" }}}
" fzf {{{
" NOTE: `:call fzf#run(fzf#wrap())`
let $FZF_DEFAULT_COMMAND = 'rg --follow --hidden --smart-case --files'
"let $FZF_DEFAULT_COMMAND = 'rg --files --hidden --no-ignore --glob "!.git/*"'
let $FZF_DEFAULT_OPTS="--color=light,16 --reverse --wrap --preview-window='right:60%:wrap'
  \ --border=none --padding=1 --margin=0,0,1,0
  \ --bind ctrl-space:toggle,tab:down,btab:up,
  \shift-down:toggle+down,shift-up:toggle+up,ctrl-f:replace-query,
  \alt-enter:toggle-preview,alt--:first,alt-=:last,
  \alt-a:select-all,alt-d:deselect-all,alt-x:clear-multi,
  \alt-n:preview-half-page-down,alt-p:preview-half-page-up,
  \alt-w:toggle-preview-wrap"

"let g:fzf_layout = {'window': 'new', 'down': '40%'}
let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.6, 'relative': v:true, 'yoffset': 1.0 } }
"let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.9, 'relative': v:true } }
"let g:fzf_layout = {'up':'~90%', 'window': { 'width': 0.8, 'height': 0.8, 'yoffset':0.5, 'xoffset': 0.5 } }
let g:fzf_preview_window = ['right:60%']

" alt-a ctrl-q => to select all and build quickfix list
" see: https://github.com/junegunn/fzf.vim/issues/185
"call setqflist(map(copy(a:lines), '{ "filename": v:val, "lnum": 1 }'))
function! s:build_quickfix_list(lines)
  call setqflist(map(copy(a:lines), '{ "filename": v:val }'))
  copen
  cc
endfunction
" build a quickfix list when multiple files are selected
let g:fzf_action = {
  \ 'ctrl-q': function('s:build_quickfix_list'),
  \ 'ctrl-t': 'tab split',
  \ 'ctrl-x': 'split',
  \ 'ctrl-v': 'vsplit' }

function s:OpenInBuffer(lines) abort
  exe 'e +'.split(a:lines[0], ':')[1].' '.split(a:lines[0], ':')[0]
endfunction

" :MoveBack | use with fzf
com! -bar MoveBack if &buftype == 'nofile' && (winwidth(0) < &columns / 3 || winheight(0) < &lines / 3) | exe "normal! \<C-w>\<C-p>" | endif
nn <Leader><Enter> :MoveBack<Bar>FZF<CR>

" <alt-g> | handle navigation with z.sh
nn <A-G> :call fzf#run({'source': 'z-history', 'sink': 'cd', 'down': '40%', 'options': '--tac'})<CR>

" shortcuts for fzf
"nmap <Leader>n :call fzf#run({'sink': 'tabedit'})<CR>
"nmap <Leader>g :call fzf#run({'source': 'git ls-files', 'sink': 'e', 'options': '--tac'})<CR>
"nmap <Leader>g :call fzf#run({'source': 'git ls-files', 'sink': 'e', 'options': '--tac'})<CR>
"nn <silent> <C-p> :exe 'Files' system('git rev-parse --show-toplevel 2>/dev/null')[:-2]<CR>

"com! -nargs=* Rg call RG(<q-args>)
" >f to ripgrep selected text when in visual mode
"vnoremap <Leader>f "sy:Rg <C-R>s<CR>
" >F to ripgrep word under cursor when in normal mode
"nn <Leader>F viw"sy:RG <C-R>s<CR>
"nn <Leader>ff :F<CR>
"vnoremap <Leader>ff :F <C-R><C-w><CR>
"nn <Leader>/ :call Ripgrep("")<CR>
"nmap <Leader>? :exe ':R ' . expand('<cword>')<CR>
"nn <Leader>? :call Ripgrep("")<CR>
"vnoremap <Leader>/ :call Rg(<SID>GetSelection())<CR>
"vnoremap <Leader>f <Esc>:FZF -q <C-R>=<SID>GetSelectedText()<CR><CR>

" fzf-commands
" :F
com! -bang -range -nargs=* F call fzf#run(fzf#wrap({
  \ 'sink*': function('s:OpenInBuffer'),
  \ 'source': 'rg --column --line-number --no-heading --fixed-strings --smart-case --no-ignore --hidden --follow -g "!.git/*" '.shellescape(<q-args>), 'options': '--wrap'}))
", <bang>0)
" nn <Leader>ff :F<CR>
vnoremap <Leader>ff :F <C-R><C-w><CR>

" :Files
com! -bang -nargs=? -complete=dir Files call fzf#run(fzf#wrap({
  \ 'source': "rg --files --hidden --no-ignore -g '!.git/*'",
  \ 'sink': 'e',
  \ 'dir': <q-args>,
  \ 'options': ['--multi', '--preview', 'bat -f {}']}), <bang>0)

" :FindInProject
com! -bang -range -nargs=* FindInProject call fzf#run({
  \ 'source': 'rg --vimgrep --hidden --follow --glob "!.git/*" '.shellescape(<q-args>),
  \ 'sink*': function('s:OpenInBuffer'),
  \ 'down': '50%',
  \ 'options': ['--delimiter', ':', '--preview', 'bat --color always --theme ansi {1} --highlight-line {2}','--preview-window', '+{2}-'.winheight('%')/3, '--color', 'light,16']})
"(winheight('%')/2, winwidth('%')/4*3)
nn <Leader>F :FindInProject<Space>
vnoremap <Leader>F :FindInProject <C-R><C-w><CR>

" :Lines
function! s:line_handler(l)
  let keys = split(a:l, ':\t')
  exec 'buf' keys[0]
  exec keys[1]
  normal! ^zz
endfunction
function! s:buffer_lines()
  let res = []
  for b in filter(range(1, bufnr('$')), 'buflisted(v:val)')
    call extend(res, map(getbufline(b,0,"$"), 'b . ":\t" . (v:key + 1) . ":\t" . v:val '))
  endfor
  return res
endfunction
com! Lines call fzf#run({
  \ 'source':  <sid>buffer_lines(),
  \ 'sink':    function('<sid>line_handler'),
  \ 'options': '--extended --nth=3..',
  \ 'down':    '60%'
  \})

" :Opener
com! -bang -nargs=? -complete=dir Opener call
  \ fzf#run({
  \ 'source': 'rg --files --follow --hidden --glob "!.git/*"', 'sink': 'e', 'down': '40%', 'options': '--preview "codepreview {}"'
  \ })

" :Snippets
" >sn
function! s:read_snippet_into_buffer(snippet)
  exe 'r ~/.dotfiles/snippets/'.a:snippet
endfunction
com! -bang -nargs=* Snippets call fzf#run(fzf#wrap({
   \ 'source': 'lr -t "type == f" -1 -s -oM ~/.dotfiles/snippets',
   \ 'sink': function('<SID>read_snippet_into_buffer'),
   \ 'options': ['--preview', 'bat ~/.dotfiles/snippets/{}']
   \ }))
nn <Leader>sn :Snippets<CR>

" :Tags
function! s:tags_sink(line)
  let parts = split(a:line, '\t\zs')
  let excmd = matchstr(parts[2:], '^.*\ze;"\t')
  execute 'silent e' parts[1][:-2]
  let [magic, &magic] = [&magic, 0]
  execute excmd
  let &magic = magic
endfunction
function! s:tags()
  if empty(tagfiles())
    echohl WarningMsg
    echom 'Preparing tags'
    echohl None
    call system('ctags -R')
  endif
  call fzf#run({
    \ 'source':  'cat '.join(map(tagfiles(), 'fnamemodify(v:val, ":S")')).
    \            '| grep -v -a ^!',
    \ 'options': '+m -d "\t" --with-nth 1,4.. -n 1 --tiebreak=index',
    \ 'down':    '40%',
    \ 'sink':    function('s:tags_sink')
    \ })
endfunction
com! Tags call s:tags()

" :Templates
" has to be a function to avoid the extra space fzf#run inserts otherwise
function! s:read_template_into_buffer(template)
  exe '0r ~/.vim/templates/'.a:template
endfunction
com! -bang -nargs=* Templates call fzf#run({
  \ 'source': 'ls -1 ~/.config/vim/templates',
  \ 'down': 20,
  \ 'sink': function('<SID>read_template_into_buffer')
  \ })

" :URLs | fuzzy finder & launcher.
com! URLs call fzf#run(fzf#wrap({
  \ 'source': getline(1,'$')->join(' ')->split(' ')->map({_,v -> matchstr(v,'\chttp\(s\)\?:\/\/[a-z.@:?=&]\+')})->filter('!empty(v:val)')->sort()->uniq(),
  \ 'sink': executable('open') ? '!open' : '!xdg-open', 'options': '--multi --prompt=URLs\>\ '
  \ }))

" }}}
" fzy {{{
" fuzzy-find files under the current directory and open in window/split/tab etc.
function! FzyFind()
  return <SID>SysR('', "flr -t 'type = f || type = l' \| fzy")
endfu
nn <Leader>ff :call FzyFind() ->split("\n") ->map({i, x -> x ->M('edit ') ->execute()})<CR>
nn <Leader>ft :call FzyFind() ->split("\n") ->map({i, x -> x ->M('tabe ') ->execute()})<CR>
nn <Leader>fh :call FzyFind() ->split("\n") ->map({i, x -> x ->M('aboveleft vsplit ') ->execute()})<CR>
nn <Leader>fl :call FzyFind() ->split("\n") ->map({i, x -> x ->M('belowright vsplit ') ->execute()})<CR>
nn <Leader>fj :call FzyFind() ->split("\n") ->map({i, x -> x ->M('belowright split ') ->execute()})<CR>
nn <Leader>fk :call FzyFind() ->split("\n") ->map({i, x -> x ->M('aboveleft split ') ->execute()})<CR>

" MRU mappings
" fuzzy-find and open a file from the most-recently-used buffer list.
nnoremap <Leader>fe :call copy(v:oldfiles)
    \ ->map({idx, val -> {'idx': idx + 1, 'path': val}})
    \ ->filter({idx, val -> filereadable(expand(val['path']))
        \ && val['path'] !~ '__Tagbar__'
        \ && val['path'] !~ '__Gundo_'
        \ && val['path'] !~ '.git/'
        \ && val['path'] !~ 'vim/vim81/doc/'
        \ && val['path'] !~ '/dev/fd'
        \ && val['path'] !~ '/var/folders'
    \ })
    \ ->map({idx, val -> val.idx ."\t". val.path})[:20]
    \ -><SID>SysR('fzy') ->matchstr('[0-9]\+')
    \ ->M('e #<') ->execute()<cr>

" Highlight text under the cursor (separate from searching); accepts an
" optional count and whether to perform a case insensitive search. Available
" match colors defined in the Colors section below.
fu! UserMatch(count, icase)
  " Count from 1-8, then wrap around and start again unless overridden.
  let w:user_match_count = a:count != 0
      \ ? a:count
      \ : (winnr() ->getwinvar('user_match_count', 0) % 8) + 1

  let l:str = (a:icase == 1 ? '\c' : ''). expand('<cword>')

  call winnr()
      \ ->getwinvar('user_match_count')
      \ ->M('Match')
      \ ->matchadd(l:str, w:user_match_count)
endfu

" Usage: \hh or 1\hh or 2\hh or \HH or 3\HH, etc.
nn <leader>hh :<c-u>call UserMatch(v:count, 1)<cr>
nn <leader>HH :<c-u>call UserMatch(v:count, 0)<cr>
" Clear individual matches via a fuzzy-finder:
nn <leader>hn :<c-u> call getmatches()
    \ ->map({i, x -> x.id .' - '. x.pattern})
    \ -><SID>SysR('fzy -p "Clear matches > "') ->split("\n")
    \ ->map({i, x -> matchstr(x, '^[0-9]\+') ->matchdelete()})<cr>
" Clear all matches:
nn <leader>HN :unlet w:user_match_count \| call clearmatches()<cr>
" }}}
" autocmd
" s:c_highlight {{{
" -- vim-braceless -------------------------------------------------------- --
function! s:c_highlight() abort
  let s:priority = 30
  call matchadd('Conceal', '\v\{\s*$', s:priority)
  call matchadd('Conceal', '\v\s*\}\s*;?\s*$|\}\s*\zeelse', s:priority)
  call matchadd('Conceal', '\v\;$', s:priority)
endfunction
" }}}
" s:c_mappings {{{
function! s:c_mappings() abort
  nmap <buffer> gca A //|
  nmap <buffer> gco o//|
  nmap <buffer> gcO O//|
  nn <buffer> ss- o#endif<Esc><up>O#if 0
  vnoremap <buffer> S- <Esc>`>o#endif<Esc>`<O#if 0<Esc>

  nmap <buffer> <Leader>i m':0/^#include <<CR>:nohlsearch<CR>O#include <
  " ff jump to next C function
  nn <buffer> <Leader>ff :call
    \ search('\(\(if\\|for\\|while\\|switch\\|catch\)\_s*\)\@64<!(\_[^)]*)\_[^;{}()]*\zs{', "w")<CR>zt

  " {<CR> always opens a block
  inoremap <buffer> {<CR> {<CR>}<Esc>O
  vnoremap <buffer> {<CR> S{<CR>}<Esc>Pk=iB
  " complete a classical C comment: '/*' => '/* | */'
  inoremap <buffer> /* /*<Space><Space>*/<left><left><left>
  vnoremap <buffer> /* s/*<Space><Space>*/<left><left><left><Esc>p
  " complete a classical C multi-line comment:
  inoremap <buffer> /*<CR>  /*<CR><CR><Esc>A*/<Esc>kA<Space>

  "inoremap <buffer> ;# #include <><Esc>i
  inoremap <buffer> ;in #include <><left>
  inoremap <buffer> ;de #define
  inoremap <buffer> ;id #ifdef <CR><CR>#endif<up><up><C-o>$
  inoremap <buffer> ;if if () {<CR><CR>}<up><up><C-o>$<left><left><left>
  inoremap <buffer> ;ie if () {<CR>} else {<CR>}<up><up><C-o>$<left><left><left>
  inoremap <buffer> ;ii if () {<CR>} else if () {<CR>} else {<CR>}<up><up><up><C-o>$<left><left><left>
  inoremap <buffer> ;sw switch () {<CR>case:<CR>break;<CR>default:<CR>break;<CR>}<up><up><up><up><up><C-o>$<left><left><left>
  inoremap <buffer> ;wh while () {<CR><CR>break;<CR>}<up><up><up><C-o>$<left><left><left>

  inoremap <buffer> ;fo int i;<CR>for (i = 0; i < ; i++) {<CR><CR>}<up><up><C-o>$<left><left><left><left><left><left><left><left>
  " c/cpp |  for loop snippet
  inoremap <buffer> ;fi for(int i = <++> ; i < <++>; i++){<CR><++><CR>} <Esc>/<++><CR>"_c4l
  inoremap <buffer> ;fj for(int j = <++> ; j < <++>; j++){<CR><++><CR>} <Esc>/<++><CR>"_c4l
  inoremap <buffer> ;fk for(int k = <++> ; k < <++>; k++){<CR><++><CR>} <Esc>/<++><CR>"_c4l

  inoremap <buffer> ;st struct  {<CR><CR>}<up><up><C-o>$<left><left>
  inoremap <buffer> ;en enum  {<CR><CR>}<up><up><C-o>$<left><left>
  inoremap <buffer> ;fu int function_name (int arguments) {<CR><CR>return 0;<CR>}<up><up><Tab>
  inoremap <buffer> ;ma /* #include <stdio.h> */<CR><CR>int main (int argc, char *argv[]) {<CR><CR>return 0;<CR>}<up><up><Tab>

  iabbrev <buffer> #i #include
  iabbrev <buffer> #d #define
  iabbrev <buffer> main() int main(int argc, char **argv)
endfunction
" }}}
" s:html_mappings {{{
" html#url#Anchor | make a bare URL into a link to itself
function! s:html_url_anchor() abort
  " Yank this whole whitespace-separated word
  normal! yiW
  " Open a link tag
  normal! i<a href="">
  " Paste the URL into the quotes
  normal! hP
  " Move to the end of the link text URL
  normal! E
  " Close the link tag
  normal! a</a>
endfunction

function! s:html_mappings() abort
  nnoremap <buffer> <Leader>r :<C-U>call <SID>html_url_anchor()<CR>
  "let @k = 'ysiw<kbd>'
  let b:surround_{char2nr('H')} = "<span class=\"hl-\1index: \1\">\r</span>"
  let b:surround_{char2nr('!')} = "<!-- \r -->"
  "nnoremap <buffer> <Leader>ssH <span class="hl-">
  "vnoremap <buffer> <Leader>SH <Esc>`>a<span class="hl-"><Esc>`<i</span><Esc>

  inoremap <buffer> ;bang <Esc>:0read !cat ~/.config/datafiles/html_starter<CR>gg
  inoremap <buffer> ;fa <i class="fas fa-"></i><Esc>F"i
  inoremap <buffer> ;css <link rel="stylesheet" href="index.css" type="text/css" /><Esc>?index.css<CR>vi"
  inoremap <buffer> ;js <script src="index.js"></script><Esc>?index.js<CR>vi"
  inoremap <buffer> ;cl class=""<left>

  xnoremap <buffer> bb A</sub><Esc>gvI<sub><Esc>gv11l
  xnoremap <buffer> cc A</code><Esc>gvI<code><Esc>gv13l
  xnoremap <buffer> ee A</em><Esc>gvI<em><Esc>gv9l
  xnoremap <buffer> pp A</sup><Esc>gvI<sup><Esc>gv11l
  xnoremap <buffer> qq "qda<blockquote><em><CR></em></blockquote><CR><Esc>k"qP
  xnoremap <buffer> ss A</strong><Esc>gvI<strong><Esc>gv17l
  xnoremap <buffer> tt A</tt><Esc>gvI<tt><Esc>gv9l
endfunction
" }}}
" s:json_mappings {{{
function! s:json_mappings() abort
  " >jm | minify with jq
  nn <buffer> <Leader>jm <Cmd>%!jq --compact-output<CR>
  " >jq | json prettifying
  nn <buffer> <Leader>jq :%!jq .<CR>
  " >jq | this is line oriented and wont respect more precise selections
  vnoremap <buffer> <Leader>jq !jq .<CR>
endfunction
" }}}
" s:markdown_mappings {{{
"todo(2026-02-27): implement surround
" word -> *word*
"map ** viw<esc>`>a*<esc>`<i*<esc>
"
"" use  ** to put stars around the selected text
"" vmap ** <esc>`>a*<esc>`<i*<esc>
"  nnoremap ** ciW**<esc>P
"  vnoremap ** c**<esc>P
""
"" use  __ to put underscores around the selected text
"  nmap __ ciW__<esc>P
"  vmap __ c__<esc>P
function! s:markdown_mappings() abort
  " toc | jump
  nn <buffer> ge vi["0y/<C-R>0<CR>
  " > blockquote
  nor <buffer> ,q :norm 0i> <Esc>$
  nn <buffer> ,w yiWi[<Esc>Ea](#<Esc>pa)

  " qq | quote around a selected block of text
  vnoremap <buffer>qq <Esc>`>a`<Esc>`<i`<Esc>
  " >l | linkify selected text inline to contents of pasteboard.
  vnoremap <buffer> <Leader>l <Esc>`>a]<Esc>`<i[<Esc>`>lla()<Esc>"+P

  " >h1 >h2 | shortcuts for creating markdown "title" lines and others.
  map <buffer> <Leader>h1 <Esc>"0yy"0p:keeppatterns s/./=/g<CR>o<CR>
  map <buffer> <Leader>h2 <Esc>"0yy"0p:keeppatterns s/./-/g<CR>o<CR>

  " include snippet
  nmap <buffer> <Leader>i a--8<-- "includes/"<Esc>i

  " place selected contents or word under cursor into a hyperlink
  nmap <buffer> <Leader><S-l> viWS]%a()<Esc>
  vmap <buffer> <Leader><S-l> S]%a()<Esc>
  "nmap <buffer> <Leader>l viWS]%a()<Esc>"+P
  "vmap <buffer> <Leader>l S]%a()<Esc>"+PT[Bdt[

  " bold
  "imap <C-b> ****<Esc>hi
  "nmap <Leader>b ysiW*ysE*
  "vmap <Leader>b S*gv2lS*
  nn <buffer> <Leader>mq o```<Esc><up>O```
  nn <buffer> <Leader>toc :w<CR>:.!toc-markdown %:p<CR>

  vnoremap <buffer> ``` <Esc>`<O<Esc>S```<Esc>`>o<Esc>S```<Esc>k$
  vnoremap <buffer> <Leader>qi :s/`/*/g<CR>

  let b:surround_{char2nr('b')} = "**\r**"
  "au FileType markdown let b:surround_{char2nr('c')} = "`\r`"
  let b:surround_{char2nr('i')} = "_\r_"
  let b:surround_{char2nr('l')} = "```\1language: \1\r```"
  "let b:surround_{char2nr('u')} = "[](\r)"
  " see: https://github.com/tpope/vim-surround/issues/213
  " code block for markdown | surround 45 -
  let b:surround_{char2nr('-')} = "```\n\r\n```"

  " vim-surround | markdown formatting
  nmap <buffer> <Leader>mi ysiW_
  nmap <buffer> <Leader>mb ysiW*.
  nmap <buffer> <Leader>mm ysiW`
  nmap <buffer> <Leader>ml ysiW]%a()<left>
  nmap <buffer> <Leader>mc yss-
  xmap <buffer> <Leader>mi S_
  xmap <buffer> <Leader>mb S*gvS*
  xmap <buffer> <Leader>ml S]%a()<left>
  xmap <buffer> <Leader>mm S`

  inoremap <buffer> <C-e> <Esc>/<++><CR>:noh<CR>"_c4l
  inoremap <buffer> ** ****<left><left>
  inoremap <buffer> ,a [](<++>)<++><Esc>F[a
  inoremap <buffer> ,b **** <++><Esc>F*hi
  inoremap <buffer> ,c ```<Enter><++><Enter>```<Enter><Enter><++><Esc>4kA
  inoremap <buffer> ,d `` <++><Esc>F`i
  "inoremap <buffer> ,f <Esc>/<++><CR>:nohls<CR>"_c4l
  inoremap <buffer> ,i ** <++><Esc>F*i
  inoremap <buffer> ,n ---<Enter><Enter>
  inoremap <buffer> ,p ![](<++>)<++><Esc>F[a
  inoremap <buffer> ,w <Esc>/ <++><CR>:noh<CR>"_c5l<CR>

  "vmap <buffer> <Leader>aa <Esc>`>a]()<Esc>`<i[<Esc>f(a
  "imap <buffer> <C-L>aa []()<Esc>F]i
  "vmap <buffer> <Leader>bb <Esc>`>a**<Esc>`<i**<Esc><right>
  "imap <buffer> <C-L>bb ****<Esc>hi
  "vmap <buffer> <Leader>ii <Esc>`>a_<Esc>`<i_<Esc><right>
  "imap <buffer> <C-L>ii **<Esc>i

  inorea  <buffer>.**  <c-o>B<c-o>diW*<c-r>"*<c-o>x
endfunction

function! s:pandoc_mappings()
  "autocmd FileType markdown,vimwiki setl iskeyword+=-|
  inoremap <expr> <right> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
  vnoremap <Leader>si :s/`/*/g<CR>

  "nnoremap <buffer> <F4> !pandoc % --pdf-engine=xelatex -o %:r.pdf
  " NOTE: <F16> => <shift-F4>
  noremap <buffer> <F4> :! pandoc '%:p' -o /tmp/'%:p:t'.html --template=easy_template.html --toc && browser /tmp/'%:p:t'.html &<CR><CR>
  noremap <buffer> <F16> :! pandoc '%:p' -o /tmp/'%:p:t'.pdf --pdf-engine=pdflatex --toc && xdg-open /tmp/'%:p:t'.pdf &<CR><CR>

  "nn <buffer> <Leader>at :!pandoc --from=markdown --to=gfm --standalone --markdown-headings atx --preserve-tabs --tab-stop=2 --output=% %<CR>
  "nn <buffer> <F2> !pandoc % --pdf-engine=xelatex -o %:r.pdf
  "nn <buffer> <F5> :!pandoc<space><C-R>%<space>--pdf-engine=xelatex<space>-o<space><C-R>%.pdf<Enter><Enter>
  " align markdown tables correctly
  "vnoremap <buffer> <Leader>p" !pandoc -t markdown-simple_tables<CR>
endfunction

" md | title
function! OnMdCreate()
  execute 'norm gg'
  let filename = '#' . ' ' . expand('%:t:r')
  call setline(1, filename)
  exe 'norm o'
endfunction
" }}}
" s:text_mappings {{{
function! s:text_mappings() abort
  " =>
  " >td | add a todo comment
  nn <buffer> todo o<CR><Esc>kkA TODO:<Esc>jjA - [ ]<Esc>kk0d^j.j.A
endfunction
" }}}
" s:python_mappings {{{
function! s:python_mappings() abort
  " ff jump to the next function
  nn <buffer> <Leader>ff :call search('^def ', "w")<CR>zt
  " ty | search all TODO comments in .py files
  nn <buffer> <Leader>td :noautocmd vimgrep /TODO/j **/*.py<CR>:cw<CR>

  " python
  nmap <buffer> gca A  #|
  nmap <buffer> gco o#|
  nmap <buffer> gcO O#|
  nn <buffer> gO <Cmd>execute 'lvim /^\(#.*\)\@!\(class\\|\s*def\\|\s*async\sdef\)/ % \| lwindow'<CR>
  "nn <buffer> gO <Cmd>execute 'vimgrep /^\(#.*\)\@!\(class\\|\s*def\\|\s*async\sdef\)/ % \| cwindow'<CR>
  " run code by pressing <ctrl+r> in normal mode
  "nn <buffer> <C-R> <Esc>:w<CR>:!python %<CR>

  inoremap <buffer> <C-l>def def ():<Esc>F(i
  inoremap <buffer> ;def def <++>(<++>):<CR><++><Esc>k$?def<CR>:nohls<CR>
  inoremap <buffer> ;i __import__('ipdb').set_trace()<Esc>
  inoremap <buffer> ;ifn if __name__ == "__main__":<Esc>
  inoremap <buffer> ;dp __import__('pudb').set_trace()<Esc>
  inoremap <buffer> ;fs f""<left>
  inoremap <buffer> ;pr print()<left>
  inoremap <buffer> ;ld logger.debug(f"")<left><left>
  inoremap <buffer> ;li logger.info(f"")<left><left>
  inoremap <buffer> ;lw logger.warning(f"")<left><left>
  inoremap <buffer> ;le logger.error(f"")<left><left>
  inoremap <buffer> ;lc logger.critical(f"")<left><left>
  inoremap <buffer> ;lx logger.exception(f"")<left><left>

  vnoremap <buffer> scw <Esc>`<O<Esc>S"""<Esc>`>o<Esc>S"""<Esc>k$

  inorea <buffer> im import
  inorea <buffer> ipdb __import__('ipdb').set_trace()
  inorea <buffer> pudb __import__('pudb').set_trace()
endfunction
" }}}
" s:rust_mappings {{{
function! s:rust_mappings() abort
  " rust
  nn <buffer> ;a oprintln!("");<Esc>hhi<C-R>=line(".")<CR><Esc>
  inoremap <buffer> ;a println!("");<Esc>hhi<C-R>=line(".")<CR><Esc>
  inorea <buffer> ,. println!("{:?}",);<left><left>
  inorea <buffer> ., println!("{:#?}",);<left><left>
  inorea <buffer> xxx iter().map(\|x\|
endfunction
" }}}
" s:shell_mappings {{{
function! s:shell_mappings() abort
  " >! | execute line with 'shell'
  nn <buffer> <Leader>! ^"zyg_:!<C-R>z<CR>

  " surround with braces
  nmap <buffer> <Leader>} wi{<Esc>ea}<Esc>
  nn <buffer> <Bslash>l i{<Esc>ea}<Esc>
  " enclose any variable within a line in quotes
  "map <buffer> \" :.s/\v(^\|[[:blank:]])(\$[^[:blank:]]*)([[:blank:]]\|$)/\1"\2"\3/g

  " nn <buffer> <Leader>cx :w<CR>:!chmod +x % && ./%<CR>
  " nn sh :!chmod +x % && source %<CR>

  " shfor | write generic sh for loop
  map <buffer> shcase ocase  in<Enter><++>)<Enter>esac<Esc><up><up>whi
  map <buffer> shfor ofor  in <++>; do<Enter><Enter>done<Esc><up><up>a
  map <buffer> shfunc o() {<Enter><Enter>}<Esc><up><up>I

  inoremap <buffer> <C-x>` $()<left>
  inoremap <buffer> (<Tab> () {<CR><CR><Esc>O}<up>
  inoremap <buffer> ;s ;;
  inoremap <buffer> ;ds # shellcheck disable=SC<Esc>a
  inoremap <buffer> ;na ${0##*/}<Esc>a
  inoremap <buffer> ;bn $(basename "$0")<Esc>a

  " use v or $ to get a variable interpolation (inside of a string)}
  " ysiw$   wrap the token under the cursor in ${}
  " v...s$  wrap the selection in ${}
  " 118 v 36 $
  let b:surround_{char2nr('v')} = "${\r}"
  "let b:surround_{char2nr('v')} = "\"${\r}\""
  let b:surround_{char2nr('$')} = "${\r}"
  " shortcuts for common surrounds
  map <buffer> <Leader>y$ ysi"$
  "118 v 115 s
  let b:surround_{char2nr('s')} = "\"$(\r)\""
  "map <buffer> <Leader>y$ ysw"lysw$
  "noremap <buffer> <Leader>"" ysw"lysw$

  inorea <buffer> deps: dependencies:
  inorea <silent><buffer> ifs. IFS=$(printf ' \n\t')<CR><C-R>=<SID>Eatchar('\s')<CR>
  inorea <silent><buffer> sdir. sdir=$(cd "$(dirname "$0")" >/dev/null 2>&1 && pwd)<CR><C-R>=<SID>Eatchar('\s')<CR>
  inorea <silent><buffer> tmpdir. tmpdir=$(mktemp -d "${TMPDIR:-/tmp}"/"$(basename "$0")".XXXXXX) \|\| exit<CR><C-R>=<SID>Eatchar('\s')<CR>
  inorea <silent><buffer> tmpfile. tmpfile="$(mktemp "${TMPDIR:-/tmp}"/"$(basename "$0")".XXXXXX)" \|\| tmpfile=/tmp/test$$<CR><C-R>=<SID>Eatchar('\s')<CR>
  inorea <silent><buffer> OS. os=$(uname -s \| tr '[:upper:]' '[:lower:]')<CR><C-R>=<SID>Eatchar('\s')<CR>
endfunction
" }}}
" s:vim_mappings {{{
function! s:vim_mappings() abort
  " execute line
  " >: | execute line in command mode.
  nnoremap <buffer> <Leader>: ^"zyg_:<C-R>z<CR>
  " >@ | execute line in normal mode.
  nnoremap <buffer> <Leader>@ ^"zyg_@z

  " source line
  " >S | source line.
  nnoremap <buffer> <Leader>S ^vg_y:execute @@<CR>:echo 'Sourced line.'<CR>
  vnoremap <buffer> <Leader>S y:@"<CR>
  "vnoremap <buffer> <Leader>L y:execute @@<CR>
  "vnoremap <buffer> <Leader>S y:execute @@<CR>
  "vnoremap <Leader>S y:@"<CR>

  " >k | run helpgrep on the word under the cursor
  nn <buffer> <Leader>K :<C-U>helpgrep <cword><CR>
endfunction
" }}}
" fin
" augroup functions {{{
" check whether first line was changed and is a shebang,if so re-run ftdetection
" if getline(1) =~# '^#!'
" matchstr(getline(1), '#!\%(/usr/bin/env \+\)\=\zs.*') . ' %:S'
function! s:CheckShebang()
  if line('''[') == 1 && getline(1) =~# '^#!'
    doautocmd filetypedetect BufRead
  endif
endfunction

" open FILENAME:LINE:COL
function! s:goto_line()
  let tokens = split(expand('%'), ':')
  if len(tokens) <= 1 || !filereadable(tokens[0])
    return
  endif
  let file = tokens[0]
  let rest = map(tokens[1:], 'str2nr(v:val)')
  let line = get(rest, 0, 1)
  let col  = get(rest, 1, 1)
  bd!
  silent execute 'e' file
  execute printf('normal! %dG%d|', line, col)
endfunction
"autocmd vimrc BufNewFile * nested call s:goto_line()

function! s:LoadShell(filename)
  execute '0read !cat '.a:filename
endfunction

function! s:templated()
  let s:templates_dir = $VIMCONFIG . "/templates/"
  "let s:ext = expand('%:e')
  let s:filename = s:templates_dir . expand('<afile>:e')
  let s:file = s:filename . ".skeleton"
  execute '0read !cat '.s:file
endfunction

" open multiple arguments in tabs by default
" see: https://overflow.adminforge.de/exchange/vi/questions/310/placeholder
" only play buffer games if we start in a 'normal' disposition, without any
" splits or tabs (i.e. exactly 1 buffer shown, other buffers hidden) -- this
" is to avoid overriding `vimdiff` or `vim -[oO]` or custom startup commands
function! s:want_args_to_tabs()
  let buffers = getbufinfo()
  let shown = filter(copy(l:buffers), {_, v -> !empty(v.windows)})
  let hidden = filter(copy(l:buffers), {_, v -> empty(v.windows)})
  return len(l:shown) == 1 && len(l:hidden) > 0
endfunction
" }}}
" augroup {{{
augroup vimrc
  " standard in | treat buffers from stdin (e.g., echo foo | vim -) as scratch
  au StdinReadPost * set buftype=nofile

  " last-position
  "au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
  au BufReadPost *
    \ if line("'\"") > 0 && line ("'\"") <= line("$") |
    \   exe "normal! g'\"" |
    \ endif

  "au VimEnter * ++nested if s:want_args_to_tabs() | tab all | tabfirst | endif

  " windows | resize windows on terminal size change
  au VimResized * wincmd =

  " autoread
  au FocusGained,VimResume * silent! checktime
  " emit warning if the file changed.
  "au FileChangedShellPost * echohl WarningMsg
  "    \ | echo 'File changed on disk. Buffer reloaded!' | echohl None
  " don't ask to reload buffers changed on disk; you still get error on write
  au FileChangedShell * v:fcs_choice = 0

  " NOTE: BufNewFile starting to edit a file that doesn't exist
  " mkdir | create missing parent directories automatically
  au BufNewFile * autocmd BufWritePre <buffer> ++once call mkdir(expand('%:h'), 'p')
  " open FILENAME:LINE:COL
  "au BufNewFile * nested call s:goto_line()

  " skeleton | template
  " if a ftplugin has defined b:ftskeleton variable, try to load skeleton template.
  au BufNewFile * silent! exe "0r ". b:ftskeleton
  au BufNewFile .gitignore call s:LoadShell('~/.dotfiles/datafiles/templates/gitignore')
  au BufNewFile index.html call s:LoadShell('~/.dotfiles/datafiles/templates/index.html')
  "au BufNewFile *.bash,*.cpp,*.html,*.pl,*.spec call s:templated()
  au BufNewFile $NOUS/*,$NOTE_DIR/* call AddNoteHeader()
  " title as filename for new markdown files
  au BufNewFile *.md :call OnMdCreate()
  " perl | auto insert perl shebang
  au BufNewFile *.pl exe "norm a#!/usr/bin/env perl\<Esc>o\<Esc>ouse strict;\<Esc>ouse warnings;\<Esc>ouse diagnostics;\<Esc>o"
  " sk | skeleton-cli
  "au BufNewFile *.skeleton exe ":call <SID>sk_title()"
  au BufNewFile *.skeleton exe "norm a---\<Esc>ofilename: <++>\<Esc>ogroups: [<++>,<++>]\<Esc>o---\<Esc>o"
  "au BufNewFile *.sh,$HOME/.local/bin/*,$HOME/bin/* exe 'silent! 1s/.*/#!\/bin\/sh -e\r# '| setl ft=sh | :startinsert
  "au BufNewFile * if !empty(&filetype) | exe 'silent! 1s/.*/#!\/usr\/bin\/' . &filetype . '\r\r'| :startinsert | endif
  "au BufNewFile *.sh 0r ~/.vim/templates/skeleton.sh | normal! G
  "au BufNewFile *.sh let b:is_new = 1
  "au BufWritePost *.sh
  "    \  if get(b:, 'is_new', 0)
  "    \|   silent execute '!chmod +x %'
  "    \|   let b:is_new = 0
  "    \| endif

  " don't create undofile for /tmp/
  au BufNewFile,BufReadPre,BufWritePre $TMPDIR/*,/tmp/* setl noundofile
  " don't write swapfile on most commonly used directories for NFS mounts or USB sticks
  au BufNewFile,BufReadPre /media/*,/run/media/*,/mnt/* set dir=~/tmp,/var/tmp,/tmp
  " prevent accidental editing of patch .orig files
  au BufRead *.orig set readonly
  au BufRead,BufNewFile *.patch setl nofen
  "au BufWritePre [:;]* throw 'Forbidden file name: ' . expand('<afile>')

  " indentation | default to two spaces indentation, no tabs.
  " but if there is a line containing a tab, set to 1 space (=8 chars) with tabs.
  "set ts=8 sts=2 sw=2 et
  "au BufRead * silent g/^\t/setl sts=0 sw=8 noet|norm!``

  " autochdir | but not if /tmp.
  "au BufEnter * if expand('%:p:h') !~ '^/tmp' | silent! lcd %:p:h | endif

  " set default file type to text for every new file without a name
  " see: https://overflow.adminforge.de/questions/5487338/#5492283
  "au BufRead,BufNewFile * if &filetype == "" | setl ft=text | endif

  " help | make sure 'list' and 'number' is disabled in help files
  au BufWinEnter *.txt if &filetype == 'help' | setl nolist nonu | endif
  " open help files in a vertical split
  "au BufWinEnter *.txt if &ft == 'help' | wincmd L | endif

  " au BufWinEnter *.py,*.h,*.cc let w:m1=matchadd('Search', '\%>79v', -1)
  " au BufWinEnter *.py,*.h,*.cc let w:m2=matchadd('LineTooLong', '\%>79v.\+', -1)
  " au BufWinEnter *.py,*.h,*.cc let w:m2=matchadd('LineTooLong', '^ +$', -1)

  " file types
  "formal: au BufNewFile,BufReadPost * setf {filetype}
  au BufRead,BufNewFile *.awk set filetype=awk
  au BufRead,BufNewFile *.c,*.cc,*.h set filetype=c
  au BufRead,BufNewFile Caddyfile*,*.Caddyfile set filetype=caddyfile
  au BufRead,BufNewFile *.conf set filetype=conf
  au BufRead,BufNewFile */git/config* set filetype=gitconfig
  au BufRead,BufNewFile Dockerfile* set filetype=dockerfile
  au BufRead,BufNewFile *.janet,*.jdn,*.cgen set filetype=janet
  au BufRead,BufNewFile *.asd set filetype=lisp
  au BufRead,BufNewFile *.less set filetype=less
  au BufRead,BufNewFile *.m set filetype=objc
  au BufRead,BufNewFile *.md set filetype=markdown
  au BufRead,BufNewFile Brewfile* set filetype=ruby
  au BufRead,BufNewFile .envrc,*profile,*.rc,*.sh set filetype=sh
  au BufRead,BufNewFile *.{yaml,yml} set filetype=yaml
  au BufRead,BufNewFile *{.,}justfile\c,*.just set filetype=just
  au BufRead,BufNewFile *.pl set filetype=perl
  au BufRead,BufNewFile *.py set filetype=python
  au BufRead,BufNewFile *exrc set filetype=vim
  " custom hardcoded types
  au BufRead,BufNewFile */bash-completion/* set ft=bash
  "if getline(1) =~# '^#!.*/bin/env\s\+janet\>'
  au BufRead $SNIPPETS_PATH/*
      \ if getline(1) !~ '^#!' && expand('<afile>:e') == ""
      \ |   setf sh
      \ | endif
  au BufRead,BufNewFile *
      \ if getline(1) =~# '\v^#!/%(\w|[-/])*/%(env%(\s+-S)?\s+)?uv\A'
      \ |   setf python
      \ | endif
  au BufRead,BufNewFile */help/* set ft=help

  "call system('chmod +w -- ' . expand('%:S'))
  " au BufReadPre,FileReadPre *.plist,*.sfl3 :silent! exe "!plutil -convert xml1 -- %"
  " au BufWritePre,BufLeave,QuitPre *.plist,*.sfl3 :silent! exe "!plutil -convert binary1 -- %"

  " omnifunc
  " use generic omnicompletion if something more specific isn't already set
  au FileType * if &omnifunc == "" | setl ofu=syntaxcomplete#Complete | endif
  au FileType cmake setl ofu=syntaxcomplete#Complete
  au FileType cpp setl ofu=
  au FileType python setl ofu=pythoncomplete#Complete

  " commentstring
  "if empty(&commentstring) | setl commentstring=#\ %s | endif
  au FileType c setl cms=/*\ %s\ */
  au FileType cpp,go,objc,zig,php,glsl,arduinoremap setl cms=//\ %s
  au FileType cmake,gdb,gitconfig,gnuplot,just,systemd setl cms=#\ %s
  au FileType lua,sql setl cms=--\ %s

  " formatoptions | disable automatic insertion of comment markers | fo=cjql
  "au FileType * setl fo-=o fo-=r fo-=c nolbr
  au FileType * setl fo-=o fo-=r
  " textwidth | fo-=t do not format text as it is typed
  au FileType sh,zsh,csh,tcsh,perl,ruby,tcl setl fo-=t |
      \ if !&tw | setl tw=78 | endif

  " keywordprg
  au FileType markdown,text setl lbr kp=dict
  au FileType man setl kp=:Man
  au FileType vim,help setl kp=:help

  " spell | *.md,*.txt,*.tex
  au BufNewfile *.tex,*.txt setl spell
  au FileType gitcommit setl spell
  au FileType help if &buftype ==# 'help' | setl nospell | endif
  au FileType mail setl spell

  " quit buffers
  " close preview and command windows with q
  au BufWinEnter * if &previewwindow | nn <buffer> q <C-w>q | endif
  au CmdWinEnter * nn <buffer> q <C-w>q
  au CmdwinEnter * noremap <buffer> <C-c> <Esc>:q<CR>
  au FileType diff,git,help,man,netrw,checkhealth nn <buffer> <nowait> q :q<CR>
  au BufReadPost quickfix nn <buffer> <nowait> q :bd<CR>

  " enter in buffers
  au CmdWinEnter * nn <buffer> <CR> <CR>
  " qf | close quickfix after jumping with <enter>.
  au BufReadPost quickfix nmap <silent><buffer> <CR> :.cc\|silent only<CR>
  "au BufReadPost quickfix setl nowrap
  " qf | vimscript is a joke
  "au Filetype qf setl cc=0 nolist nocul nowrap tw=0
  "au Filetype qf nn <buffer> <CR> :execute "normal! \<lt>cr>"<CR>

   "au BufReadPost quickfix setlocal number
   "  \ |  setlocal nowrap
   "  \ |  setlocal modifiable
   "  \ |  silent! %s/^[^|]*\//.../
   "  \ |  setlocal nomodifiable
  "au BufReadPost quickfix set nomodified

  " private | .n
  au BufNewFile,BufReadPre ~/.n setl noswf noudf nobk nowb nostmp hi=0 noml
  au BufNewFile,BufReadPre */journal/* setl noswf noudf nobk nowb nostmp hi=0 noml

  " sh - template | settings for void-linux
  au BufRead,BufNewFile template setl ft=sh noet sw=0 sts=0
  au BufRead,BufNewFile srcpkgs setfiletype sh
  au BufRead,BufNewFile if getline(1) =~# '\<sh\>' | setf sh | endif

  " read pdfs with pdfminer/pdf2txt
  "au BufReadPre *.pdf silent set ro
  "au BufReadPost *.pdf silent %!pdf2txt "%"

  " compiler
  au BufRead *.c compiler gcc
  au BufRead *.cpp compiler gcc
  au BufRead *.php compiler php
  au BufRead *.html compiler tidy
  au FileType awk compiler gawk
  "au FileType c compiler cppcheck
  au FileType html compiler tidy
  au FileType jq compiler jq
  au FileType json compiler jq
  au FileType perl compiler perl
  au FileType python compiler pylint
  au FileType ruby setl mp=ruby\ -c
  au FileType scdoc compiler scdoc

  " awk
  au FileType awk setl com=:# et sw=4 fdm=indent fp=gawk\ -f-\ -o/dev/stdout
  " c | include macros in completion
  " customize indentation for BSD style preferred "Allman" style indentation
  "au FileType c setl cpt-=i cpt+=d cin cino=Ls,:0,l1,t0,(s,U1,W4 kp=man\ -s
  au FileType c setl cpt-=i cpt+=d cin kp=man\ -s
  " :make jump to c assertion errors
  au FileType c setl efm^=%*[^:]:\ %f:%l:\ %m
  " find headers *when we want them*!
  au FileType c setl path+=/usr/local/include,/opt/homebrew/include,/usr/include
  "au FileType c,cpp setl path+=/usr/include include&

  " conf
  au FileType conf if search('^\[\a\+\]') | setf dosini | else | setf conf | endif
  " cron
  au FileType crontab setl nobk nowb tw=0

  " gitcommit | good commit messages. 50 columns title, 72 columns body
  " always start at the top line when writing a commit message.
  au FileType gitcommit exe "normal gg"
  au FileType gitcommit if len(getline(1)) == 0 | startinsert | endif
  au FileType gitcommit setl cc=50,72 fo=cjql tw=72 nofen com+=n:>
  au FileType gitcommit let b:editorconfig = v:false
  au FileType gitcommit let b:EditorConfig_disable = 1
  " F2 | show the changes being committed
  au FileType gitcommit nn <buffer> <F2> :!GIT_PAGER="less -+FX" git diff --cached<CR><CR>
  " F3 | show the log of previous commits
  au FileType gitcommit nn <buffer> <F3> :!GIT_PAGER="less -+FX" git log<CR><CR>
  " F4 | copy tags from previous commit
  au FileType gitcommit nn <buffer> <F4> :.-1r !git show -s --format="\%s" HEAD \| grep -oE "(\[[a-zA-Z0-9_]+\])+ ?" <CR>
  "au FileType gitcommit inoremap <buffer> ;bang <++>: <++>
  au FileType gitconfig setl ts=4 noet
  au FileType git setl nolist

  " fzf | make escape exit fzf
  au FileType fzf tnoremap <buffer> <ESC> <C-C>
  " go
  au FileType go setl noet ts=4 sw=4 fo+=jo
  " help | ai fo=tcq2
  au FileType help nn <buffer> <Leader><CR> <C-]>
  au FileType help nn <buffer> <Leader>K :<C-U>helpgrep <cword><CR>
  au FileType help let &helpheight = (&lines - 10)
  "au FileType help setl tw=78 ai fo+=2n fo-=ro
  "au FileType help if &buftype ==# 'help' | nn <buffer> <Leader>K :<C-U>helpgrep <cword><CR> | endif
  " html/css
  au FileType css setl et sw=2 sts=2 si fp=deno\ fmt\ --ext=css\ -
  au FileType css nn<buffer> <Leader>so viB:sort<CR>
  au FileType html setl et sw=2 sts=2 si fp=tidy\ --quiet\ yes
  " less/css
  au FileType less,css,scss setl isk+=-
  " janet
  au BufRead,BufNewFile *.janet,*.jdn,*.cgen
      \ setl noai nosi sts=2 sw=2 et indk=!,o,O fo-=t cms=#\ %s
  " jq
  au FileType jq setl fo=cqornlj def=^\\s*def sua=.jq,.json
  " jq | auto insert jq shebang
  au BufNewFile *.jq exe "norm a#!/usr/bin/env jq --exit-status --from-file\<Esc>o"

  " json
  au FileType json setl ai sw=2 sts=2 ts=8 et "cole=0
  au FileType json setl tw=0 fp=jq\ .
  " just
  au FileType just
      \ let b:current_compiler = 'just' |
      \ setl mp=just\ --fmt\ --unstable\ --check\ --justfile
      \   errorformat=%f:\ %l:\ %m

  "au FileType lua let &mp="clear; lua %" | let &efm="lua: %f:%l:%m,%-G%.%#"

  " mail
  au FileType mail setl noml tw=72 nojs fo+=aw
  au BufRead,BufNewFile neomutt-*,*.eml setl tw=72 cc=72 fo=awq com+=nb:>
  "au FileType mail match ErrorMsg '\s\+$'
  "au BufRead,BufNewFile *:2\,* setl nobackup ft=mail tw=72

  " make
  au FileType make setl noet

  " man
  au FileType man if !empty(&buftype) | setl bufhidden=delete | endif
  au FileType man setl cc= fdc=0 nolist nonu nornu ls=1 ru scl=no stl=\ %f isk+=\.,-
  au FileType man nn <buffer> <nowait> <Space> <PageDown>
  "au FileType man nn <buffer> K :Man <C-R>=expand('<cword>')<CR><CR>
  "au FileType man nn <buffer> K :bd<CR>

  " markdown | default fo-=tc tw=80 default: fo+=tcqln fo-=ro " ai fo=tcroqn2
  au FileType markdown if !&tw && expand('%:e') =~# '\<\%(md\|markdown\)\>' |
      \ setl tw=78 |
      \ endif
  "formatlistpat=^\\s*\\d\\+\\.\\s\\+\\\|^[-*+]\\s\\+
  au FileType markdown setl et sw=2 ts=4 fo=wcqln fdm=marker isk-=_ cpt+=k sua=.md
  au FileType markdown setl com=fb:*,fb:-,fb:+,n:> com+=nb:> cms=<!--%s-->
  au FileType markdown let &comments = "b:*,b:-,b:+," . &comments
  au FileType markdown
      \ let b:current_compiler = 'mdl' |
      \ setl mp=mdl\ --config\ '~/.config/.mdlrc'\ --warnings
  " don't include _ as markdown error
  " see: https://overflow.adminforge.de/questions/19137601/placeholder#34448277
  au FileType markdown syn match markdownError "\w\@<=\w\@="

  au FileType nroff setl wrap tw=85 cc=+1
  "au FileType org setl ts=2 sw=2 fdm=marker
  au FileType perl setl ep=perltidy fp=perltidy sua=.pm
  " python | ref: <https://peps.python.org/pep-0008/#maximum-line-length>
  au FileType python setl cc=72,80,100 et sw=4 sts=4
  " follow pep-recommended alignment of parentheses
  " 'cinwords' | define keywords that start an extra indent in the next line
  au FileType python setl cino+=(0
      \ | setl cinw=if,elif,else,for,while,try,except,finally,def,class
  " block comment for python | surround 45
  au FileType python let b:surround_{char2nr('-')} = "\"\"\"\n\r\n\"\"\""
  au FileType python setl fp=black\ -q\ -\ 2>/dev/null

  " reStructuredText | surround 83
  au FileType rst let b:surround_{char2nr('S')} = "``\r``"

  " ruby "isk+=@!?&
  au FileType ruby setl et sw=2 sts=2 cc=80 isk+=!
  " inspect the variable on the current line (in Ruby)
  au FileType ruby nmap <buffer> ,i ^"oy$Iputs "<Esc>A: #{<Esc>"opA"<Esc>
  " rust
  au FileType rust setl et sw=4 sts=4 tw=79
  " sed
  au FileType sed setl com=:# fo+=or fdm=indent

  " shell
  au BufNewFile *.sh :norm! i#!/bin/sh
  " sh | nosi noai tw=0 cc=0 indk+=0=&&,0<Bar> isk+=- isi+=- wm=0
  "au BufRead,BufNewFile * if &ft == 'sh' | set sw=2 | endif
  au FileType sh setl et sw=2 sts=2 ts=2 path+=~/bin/
  " fix 'include' for shell files to recognize '.' and 'source' commands
  "include=^\\s*\\.
  au FileType sh,zsh,csh,tcsh setl include=^\\s*\\%(\\.\\\|source\\)\\s
  au FileType sh
      \ let b:current_compiler = 'shellcheck' |
      \ setl mp=shellcheck\ -o\ all\ -e\ 1090\ -x\ -f\ gcc
      \   efm=%f:%l:%c:\ %m\ [SC%n]
  if executable('shfmt')
    au FileType {,ba,da,k,z}sh
        \ setl formatprg=shfmt\ -i=2\ -bn\ -ci\ --filename=%\ 2>/dev/null
  endif

  " tex | surround 99 c
  au FileType tex setl fo+=l
  " toml/yaml
  au FileType toml,yaml setl et sw=2 sts=2 si
  " txt | fo=tcq2
  "au BufEnter *.txt setl cc=80 ve=all
  "au BufEnter *.txt hi ColorColumn ctermbg=1 guibg=red
  au BufRead,BufNewFile *.txt setl et ts=4 tw=78 com+=nb:> cms=>\ %s cc=80
  au BufNewFile *.txt hi ColorColumn ctermbg=1 guibg=red
  " for keyword completion in insert mode
  au FileType text setl inf com=fb:-,fb:*,n:> com+=nb:> cms=>\ %s cc=80 et tw=78

  " xml
  au FileType xml setl et
  au FileType xml
      \ setl ep=xmllint\ --format\ - |
      \ let &fp = "tidy -xml -q -m -w -i --show-warnings 0 --show-errors 0"
  " zig
  au FileType zig setl et sw=4 sts=4 ts=8

  au FileType c,cpp call s:c_mappings()
  au FileType html call s:html_mappings()
  au FileType jq,json call s:json_mappings()
  au FileType markdown call s:markdown_mappings()
  "au FileType markdown call s:pandoc_mappings()
  au FileType python call s:python_mappings()
  au FileType rust call s:rust_mappings()
  au FileType sh,bash,zsh call s:shell_mappings()
  au FileType text call s:text_mappings()
  au FileType vim call s:vim_mappings()

  " maintain cwd
  "au InsertEnter * let save_cwd = getcwd() | set autochdir
  "au InsertLeave * set noautochdir | execute 'cd' fnameescape(save_cwd)
  au InsertLeave * call <SID>CheckShebang()

  " restore path when done.
  au CompleteDone *
      \ if exists('b:oldpwd') |
      \   lcd `=b:oldpwd` |
      \   unlet b:oldpwd |
      \ endif
  " close preview window when completion done.
  au CompleteDone * if pumvisible() == 0 | pclose | endif

  " automatically enter terminal mode when a :terminal opens
  if exists('##TermOpen')
    au TermOpen * startinsert
  endif
  if exists('##TerminalOpen')
    au TerminalOpen * set nobuflisted
  endif

  " quickfix | automatic location/quickfix window
  au QuickFixCmdPost [^l]* nested cwindow
  au QuickFixCmdPost l* nested lwindow

  " tableave | close qf location list
  "au TabLeave * cclose | lclose
  " loclist | close loclist when closing the window it belongs to
  au QuitPre * if empty(&buftype) | lclose | endif
  "if exists('##QuitPre')
  "  au QuitPre * nested if &filetype != 'qf' | silent! lclose | endif
  "endif

  " leave the w mark whenever a file is written
  "au BufWrite * normal mw
  " undo if filter shell command returned an error
  au ShellFilterPost * if v:shell_error | undo | endif

  "" highlight | also match nonascii "[^\x00-\x7F]" ’
  "" '[\x00-\x1F\x7F]'
  ""match SpellRare /\d\{1,3}\ze\%(\d\{6}\)*\d\{3}\>/
  "au BufRead,InsertLeave * :call matchadd('SpecialKey', '[^\x00-\x7F]')
  ""au BufRead,InsertLeave * match InvisibleSpaces /\s\+$/
  ""highlight InvisibleSpaces ctermbg=red guibg=red
  "au BufWinLeave * call clearmatches()

  " disable listchars in prompt buffers
  "au OptionSet buftype if &buftype ==# 'prompt' | setl nolist | endif

  " cursorshape
  au VimLeave * let &t_te.="\e[6 q"
augroup END
" }}}
" local vimrc {{{
let s:local_vimrc = expand('<sfile>') . '.local'
if filereadable(s:local_vimrc)
  execute 'source' s:local_vimrc
endif
" }}}
