#!/usr/bin/env zsh

# shellcheck shell=sh disable=SC2034,SC3041

# zmodload zsh/zprof

# shellcheck source=.profile
[ -n "${ENV:-}" ] || . "${HOME%/}"'/.profile'
# shellcheck source=.rc
[ -f "${HOME%/}"'/.rc' ] && . "${HOME%/}"'/.rc'

CDPATH=".:${HOME%/}"
# prompt
if [ "${TERM-}" = "xterm-256color" ]; then
  # called before prompt is printed. %m: %~
  precmd() { [ -t 1 ] && print -Pn "\e]0;%~\a"; }
fi
PROMPT_EOL_MARK=""
cprompt() {
  setopt nopromptsubst
  PS1='%B%(?.. %??)%(1j. %j&.)%b%2~$ '
  PS2='> '
  PS4='+ '
  if [ -n "${SSH_CONNECTION:-}" ]; then
    # PS1="%m%(?.. %??)%(1j. %j&.) %2~%#${SSH_CONNECTION:+%#} "
    # PS1='%m:%1d$ '
    PS1='%m%(?.. %??)%(1j. %j&.) %2~%# '
  fi
  RPROMPT=''
  unset RPS1 RPS2 RPROMPT RPROMPT2
}
cprompt

stty -ixon 2>/dev/null
# zshoptions(1) test: print -raC2 -- "${(kv@)options}"
# +6 -3BCQJY appendcreate
setopt nonomatch nobgnice nobeep noclobber pathdirs shnullcmd
setopt autocd listpacked menucomplete
setopt histignoredups histignorespace incappendhistory
HISTFILE="${HOME%/}"'/.sh_eternal_history'
SAVEHIST=3000
HISTSIZE=3000
LISTMAX=0
TMPPREFIX="${TMPDIR%/}/zsh"
WORDCHARS='*?[]~&;$%^+\|'

# $^fpath
# test: for d in $fpath; do echo "$(find -L "$d" -maxdepth 1 -name '_*' 2>/dev/null | wc -l) $d"; done | sort -nr
# FPATH="${XDG_DATA_HOME-}"'/zsh-completions/src':${FPATH}
FPATH=${XDG_CONFIG_HOME:-${HOME%/}/.config}/zsh/completions:${XDG_CONFIG_HOME:-${HOME%/}/.config}/zsh/.zfunc:${FPATH}
bindkey -v
KEYTIMEOUT=5

# completion {{{
# setopt completeinword globcomplete
# setopt noalwayslastprompt alwaystoend
## zshmodules(1) zsh/complist line editing during completion
zmodload -i zsh/complist
## zstyle
# test: zstyle -L '*'
# :completion:<function-name>:<completer>:<command>:<argument>:<tag>
# q.v. https://zsh.sourceforge.io/Doc/Release/Completion-System.html#Standard-Styles
# zstyle ':completion:*' completer _extensions _expand _complete _prefix _approximate
zstyle ':completion:*' completer _extensions _complete _prefix _approximate _ignored
# zstyle ':completion:::::' completer _complete _correct _approximate
# zstyle ':completion:*:correct:::' max-errors 2 not-numeric
# zstyle ':completion:*:approximate:::' max-errors 3 numeric
# zstyle ':completion:*' completer _complete ... _prefix
# zstyle ':completion::prefix:*' completer _complete
# zstyle -e ':completion:*:approximate:' max-errors 'reply=( $(( ($#PREFIX+$#SUFFIX)/3 )) numeric )'
# zstyle ':completion:*:approximate:' max-errors 'reply=( $((($#PREFIX+$#SUFFIX)/3 )) numeric )'
# zstyle ':completion:*:approximate:*' max-errors 1 numeric
zstyle ':completion:*' file-sort 'time'
zstyle ':completion:*:descriptions' format '-- %d --'
zstyle ':completion:*' group-name ''
# zstyle ':completion::*' insert-tab true
# pi=33 bd=00\;35 mi=00\;45 cd=00\;34
zstyle ':completion:*' list-colors no=00 fi=00 di=01\;34 so=01\;35 or=00\;41 ex=01\;32
zstyle ':completion:*' list-prompt ''
# ls f/b/b<TAB> => fob/bar/bing/ fob/baz/bing/ foo/bar/bing/ .. vs (fob|foo)/b/b
zstyle ':completion:*' list-suffixes yes
# foo<TAB> => foo foo-bar .. foo/<TAB> => foo
zstyle ':completion:*' accept-exact-dirs true
zstyle ':completion:*' menu select
# zshcompwid(1) completion matching control
# normal filter, then try partial word expansion, then case change
# zstyle ':completion:*' matcher-list '' 'r:|[._-]=* r:|=*' 'm:{[:lower:][:upper:]}={[:upper:][:lower:]}'

zstyle ':completion:*' matcher-list '' 'm:{[:lower:][:upper:]}={[:upper:][:lower:]}' '+r:|[._-]=* r:|=*' '+l:|=* r:|=*'

# regular => case-hypen insensitive (all) => partial-word => substring completion
# - normal filter.
# - case-insensitive. hypen-insensitive. (i.e. foo-bar -> FOO_BAR)
# - partial word around any in []. (i.e. f.b -> foo.bar and -f-b -> -foo-bar)
# - substring complete. (i.e. bar -> foobar) (i.e. fb -> foobar)
# zstyle ':completion:*' matcher-list '' 'm:{[:lower:][:upper:]-_}={[:upper:][:lower:]_-}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'

# zstyle ':completion:*' matcher-list '' 'm:{[:lower:][:upper:]-_}={[:upper:][:lower:]_-}' 'r:|[._-]=** r:|=*' 'l:|=* r:|=*'

# zstyle ':completion:*' matcher-list \
#   '' \
#   'm:{[:lower:][:upper:]-_}={[:upper:][:lower:]_-}' \
#   '+r:|[._-]=** r:|=*' \
#   '+l:|=* r:|=*'

# zstyle ':completion:*' matcher-list 'm:{[:lower:][:upper:]-_}={[:upper:][:lower:]_-}' 'r:|=*' 'l:|=* r:|=*'
# - fuzzy completion
# 2. '+r:|[-_:./]=**' -> [1.] + allow '-_:./' chars to act similar to glob patterns,
#   meaning that writing 'ni-h' then TAB would match 'nix-home' & 'nix-foo-home-bar'
#   (note that writing 'ni-o' would not have worked in that example)
# => it's _really_ powerful with `git ch TAB`, a 'kind' of structured fuzzy matcher!!
# zstyle ':completion:*' matcher-list 'm:{[:lower:]}={[:upper:]}' '+r:|[-_:./]=**'

# make completion case insensitive, not distinguish between hyphens and underscore, and complete as prefix or suffix
# zstyle ':completion:*' matcher-list 'm:{a-zA-Z-_}={A-Za-z_-} l:|=* r:|=*'

# use _complete and _prefix, but allow case-insensitive completion only with _complete
# zstyle ':completion:*:complete:*:*:*' matcher-list '' 'm:{[:lower][:upper]}={[:upper:][:lower:]}'

# zstyle ':completion::complete:*' matcher-list 'm:{[:lower:][:upper:]}={[:upper:][:lower:]}' '+r:|[._-/]=* r:|=* l:|[._-/]=* l:|=*'

# zstyle -e ':completion:*' max-errors 'reply=( $(( ($#PREFIX+$#SUFFIX)/3 )) numeric )'
zstyle ':completion:*' original true
# /u/l/l/p/libpk<TAB> => /usr/local/lib/pkgconfig/libpkgconf.pc
zstyle ':completion:*' expand 'yes'
# $HOME/<TAB> doesn't expand $HOME, $HOME<TAB> does
zstyle ':completion:*' keep-prefix true
# zstyle ':completion:*:expand:*' keep-prefix true
# zstyle ':completion:*' preserve-prefix '//[^/]##/'
# zstyle ':completion:*' rehash true
zstyle ':completion:*' special-dirs ..
zstyle ':completion:*' squeeze-slashes true
# test: zstyle -L ':completion:*' use-cache
# zstyle ':completion:*' use-cache off
# zstyle ':completion:*' use-compctl false
zstyle ':completion:*' verbose true
zstyle ':completion:*:commands' rehash true
# it's not exactly fast - for commands
zstyle ':completion:*:-command-:*:' verbose false
# zstyle ':completion:*:*:-command-:*:*' group-order aliases builtins functions commands
# zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters
# ignore: kill/diff/rm: don't complete the same twice for kill/diff.
zstyle ':completion:*:functions' ignored-patterns '_*'
# ignore completion functions for commands you don't have:
# zstyle ':completion::(^approximate*):*:functions' ignored-patterns '_*'
zstyle ':completion:*:rm:*' ignore-line yes
zstyle ':completion:*:(kill|diff):*' ignore-line true
# don't complete backup files as commands, nor xbuild.
# zstyle ':completion:*:complete:-command-::*' ignored-patterns '*~' 'xbuild'
zstyle ':completion:*:ls:*' list-dirs-first true
# lax completion for cd fix uppercase completion - use explicit tag-order
# zstyle ':completion:*:cd:*' tag-order '*' '*:-case'
# zstyle ':completion:*-case' matcher 'm:{[:lower:][:upper:][:digit:]}={[:upper:][:lower:][:digit:]}' 'l:|=* r:|=*'
# history: cycle through history completion (M-/, M-,).
zstyle ':completion:*:history-words' stop yes
zstyle ':completion:*:history-words' remove-all-dups yes
zstyle ':completion:*:history-words' list false
zstyle ':completion:*:manuals' separate-sections true
zstyle ':completion:*:*:*:*:processes' force-list always
zstyle ':completion:*:kill:*:processes' command 'ps x'
# zstyle ':completion:*:kill:*' command 'ps -u $USER -o pid,%cpu,tty,cputime,command'
# sh/rc: don't complete from PATH for sh and rc.
# zstyle ':completion:*:(sh|rc):*' tag-order '! commands builtins' -
zstyle -e ':completion:*:*:(scp|ssh):*:*' hosts 'reply=()'
zstyle ':completion:*:*:(scp|ssh):*:*' tag-order '! users'
# zstyle ':completion:*:*:make:*' tag-order 'targets variables'
# git
# zstyle ':completion:*:*:git:*' script ~/.local/share/bash-completion/completions/git
# git: installed as common-commands, makes it hard to get to aliases in completion
# zstyle ':completion:*:*:git:*' tag-order all-commands
# zstyle ':completion:*:*:g:*' tag-order all-commands
# zstyle ':completion:*:*:git:*' user-commands $(git --list-cmds=others)
# test: zstyle -L ':completion:*:*:g:*' user-commands
# zstyle ':completion:*:*:g:*' user-commands $(git --list-cmds=others)
# zstyle ':completion:*:*:g:*' user-commands ${${(M)${(k)commands}:#git-*}/git-/}
zstyle ':completion:*:*:git:*' user-commands attic cm conflicts contains get
# git checkout: skip remotes, working-tree files, and commit hashes.
# `git co` only needs local branches; remotes alone can exceed LISTMAX.
# git-* complete custom git subcommands path.
zstyle ':completion:*:*:git-checkout:*' tag-order 'recent-branches' 'heads-local' 'branch-names' '-remote-branch-names-noprefix' '-modified-files' '-commits'
# avoid verbose _describe listing for large branch sets
zstyle ':completion:*:git-checkout:*' max-verbose 0
# zstyle ':completion:*:*:git-diff:*' tag-order 'files' 'revisions'
# zstyle ':completion:*:*:git-push:argument-1:' tag-order '!hosts' -

# zstyle ':completion:*:*:(v|vi|vim):*' file-sort 'time'
# zstyle ':completion:*:*:(v|vi|vim):*:*files' ignored-patterns '*.(a|dylib|so|o|pyc|lock|resolved)'
# zstyle ':completion::*:(v|vi|vim):*' ignore-line true
# zstyle ':completion:*:evince::' file-patterns '*.(#i)(dvi|djvu|tiff|pdf|ps|xps)(|.bz2|.gz|.xz|.z) *(-/)' '*'
# zstyle ':completion:*:*:mpg123:*' file-patterns '*.(mp3|MP3):mp3\ files *(-/):directories'
# zstyle ':completion:*:*:ogg123:*' file-patterns '*.(ogg|OGG):ogg\ files *(-/):directories'
# zstyle ':completion:*:c:*' file-patterns '*~*(.7z|.zip|.bz2|.tgz|.pkg|.deb|.gz|.xz|.z)'

## custom completers
# provide a fallback completer which always completes files.
# zle -C complete-files menu-complete _generic
# zstyle ':completion:complete-files:*' completer _files _match
# bindkey '\C-x\C-f' complete-files # Force complete file names
# complete words from history
zle -C complete-words-from-history menu-complete _generic
zstyle ':completion:complete-words-from-history:*' completer _history _match _approximate
zstyle ':completion:complete-words-from-history:*' remove-all-dups true
zstyle ':completion:complete-words-from-history:*' accept-exact false
bindkey '\C-x\C-h' complete-words-from-history
# force expand current parameter ($foo, ~foo, foo*, ...)
zle -C expand-param-or-alias complete-word _generic
zstyle ':completion:expand-param-or-alias:*' completer _expand _expand_alias
zstyle ':completion:expand-param-or-alias:*' tag-order '!original'
bindkey '\C-xx' expand-param-or-alias
bindkey '^ ' expand-param-or-alias

autoload -Uz compinit
compinit -C -d ~/.cache/zsh/zcompdump
# compinit -d "${XDG_CACHE_HOME:-${HOME}/.cache}"/zsh/zcompdump

# }}}
# zle {{{

bindkey -M menuselect '^[[5~' backward-word
bindkey -M menuselect '^[[6~' forward-word
bindkey -M menuselect '\e' undo
bindkey -M menuselect '+' accept-and-hold
bindkey -M menuselect '/' accept-and-infer-next-history
bindkey -M menuselect '^N' accept-and-infer-next-history
bindkey -M menuselect '^E' send-break
bindkey -M menuselect '\C-xi' vi-insert
bindkey -M menuselect '^F' history-incremental-search-forward

bindkey '\C-xa' _expand_alias
bindkey '\C-xe' _expand_word
bindkey '\C-xh' _complete_help
bindkey '\C-xm' _most_recent_file
bindkey '\C-x\C-b' vi-match-bracket
bindkey '\C-x\C-j' vi-join
bindkey '\C-x\C-k' kill-buffer
bindkey '\C-x\C-o' overwrite-mode
bindkey '\C-x\C-u' undo
bindkey '\C-x\C-x' exchange-point-and-mark

unset zle_bracketed_paste
# escape urls automatically: remove "={}"
autoload -U url-quote-magic
zle -N self-insert url-quote-magic
zstyle ':url-quote-magic:*' url-metas '*?[]^(|)~#'

# replace insert-last-word by a smart version
autoload -Uz smart-insert-last-word
zle -N insert-last-word smart-insert-last-word
zstyle :insert-last-word match '*([[:digit:]]?|[[:alpha:]/\\])*'
# zstyle :insert-last-word match '*([^[:space:]][[:alpha:]/\\]|[[:alpha:]/\\][^[:space:]])*'
# zstyle :insert-last-word match '*([[:alpha:]/\\]?|?[[:alpha:]/\\])*'
# zstyle :insert-last-word match '*[[:alnum:]/\\]*'
bindkey '\e.' insert-last-word
# cycle through history completion <M-/> <M-,>
bindkey '\e,' _history-complete-newer
bindkey '\e/' _history-complete-older

# better than copy-prev-shell-word, can be called repeatedly.
autoload -Uz copy-earlier-word
zle -N copy-earlier-word
bindkey '^[m' copy-earlier-word

# autoload -Uz select-word-style
# select-word-style bash

# history - only search for typed commands, not full history.
autoload -Uz history-search-end
zle -N history-beginning-search-backward-end history-search-end
zle -N history-beginning-search-forward-end history-search-end
bindkey '^[OA' history-beginning-search-backward-end
bindkey '^[OB' history-beginning-search-forward-end
bindkey '^[[A' history-beginning-search-backward-end
bindkey '^[[B' history-beginning-search-forward-end

# search history with wildcards? no problem..
# history search with globs. and keeping the rest of the line. space for *
autoload -Uz narrow-to-region
_history-incremental-preserving-pattern-search-backward() {
  # local state
  MARK=CURSOR  # magick, else multiple ^R dont work
  narrow-to-region -p "$LBUFFER${BUFFER:+>>}" -P "${BUFFER:+<<}$RBUFFER" -S state
  zle end-of-history
  zle history-incremental-pattern-search-backward
  narrow-to-region -R state
}
zle -N _history-incremental-preserving-pattern-search-backward
bindkey "^R" _history-incremental-preserving-pattern-search-backward
bindkey -M isearch "^R" history-incremental-pattern-search-backward
bindkey -M isearch -s ' ' '*'
bindkey -M isearch -s '  ' '[[:blank:]]'
bindkey "^S" history-incremental-pattern-search-forward

## bindkey
# see: https://www.leonerd.org.uk/hacks/fixterms/
# `ctrl-[` sends `ESC [91;5u`
# bindkey '^[[91;5u' vi-cmd-mode
bindkey '^[[H' beginning-of-line
bindkey '^[[F' end-of-line
bindkey '^[[3~' delete-char
bindkey '^[[3;5~' kill-word
bindkey '^[[5~' backward-word
bindkey '^[[6~' forward-word
# bindkey '^I' complete-word
# bindkey -M viins '^I' complete-word
bindkey '^[[Z' reverse-menu-complete
# <m-tab> <m-shift-tab>
# bindkey '^[^[[Z' _history-complete-older
# bindkey '^[^I' _history-complete-newer
# dont do history expansion
bindkey ' ' magic-space
bindkey -r '^Q'
bindkey '^?' backward-delete-char
bindkey '^A' beginning-of-line
bindkey '^B' backward-char
bindkey '^D' kill-buffer
bindkey '^E' end-of-line
bindkey '^F' forward-char
bindkey '^K' kill-line
bindkey '^U' backward-kill-line
bindkey '^W' backward-kill-word
bindkey '^Y' yank

bindkey '^[e' expand-cmd-path
bindkey '^[b' backward-word
bindkey '^[B' vi-backward-blank-word
bindkey '^[f' forward-word
bindkey '^[F' vi-forward-blank-word
bindkey '^[K' describe-key-briefly
bindkey '^[q' push-line
bindkey '^[u' undo
bindkey '^[U' redo

## vicmd
autoload -Uz edit-command-line
zle -N edit-command-line
# <ctrl-v> for edit => v is used for visual mode
bindkey -M vicmd '^v' edit-command-line
bindkey -M viins '^[v' edit-command-line
# sensible
bindkey -M vicmd '_' vi-first-non-blank
bindkey -M vicmd 'gg' beginning-of-history
bindkey -M vicmd 'G' end-of-history
bindkey -M vicmd 'H' beginning-of-line
bindkey -M vicmd 'K' describe-key-briefly
bindkey -M vicmd 'L' end-of-line
bindkey -M vicmd 'u' undo
bindkey -M vicmd 'U' redo
bindkey -M vicmd 'yy' vi-yank-whole-line
bindkey -M vicmd 'Y' vi-yank-eol
# vim-surround
autoload -Uz surround
zle -N delete-surround surround
zle -N add-surround surround
zle -N change-surround surround
bindkey -a cs change-surround
bindkey -a ds delete-surround
bindkey -a ys add-surround
bindkey -M visual S add-surround
# surround text under cursor
bindkey -M vicmd -s 'q' "viwS"

_visual_copy() {
  # copy region to kill buffer
  zle vi-yank
  content="${CUTBUFFER-}"
  printf '%s' "${content}" | pbcopy
  zle -M "copied to clipboard!"
}
zle -N visual-copy _visual_copy
bindkey -M visual '^[c' visual-copy

## custom-widgets
# clear-screen-and-scrollback
_ctrll() {
  printf "\e[H\e[3J"
  builtin zle .reset-prompt
  builtin zle -R
}
zle -N clear-scrollback _ctrll
bindkey '^L' clear-scrollback

# fg-bg
_fgbg() {
  if expr $#BUFFER \< 1 >/dev/null; then
    if jobs %- >/dev/null 2>&1; then
      BUFFER='fg %-'
    else
      BUFFER='fg'
    fi
    zle accept-line
  else
    zle push-input
    zle clear-screen
  fi
}
zle -N fg-bg _fgbg
bindkey '^Z' fg-bg
bindkey -M vicmd '^Z' fg-bg

# copy the active line from the command line buffer
_copybuffer() {
  printf '%b' "${BUFFER}" | { pbcopy <"${1:-/dev/stdin}"; }
}
zle -N copy-buffer _copybuffer
bindkey '^O' copy-buffer
bindkey -a '^O' copy-buffer

# paste
_pastebuffer() {
  LBUFFER="${LBUFFER}$(pbpaste)"
  zle redisplay
}
zle -N paste-buffer _pastebuffer
bindkey '^[p' paste-buffer

# move by physical lines, like gj/gk in vim
_physical_up_line() { zle backward-char -n "${COLUMNS}"; }
_physical_down_line() { zle forward-char -n "${COLUMNS}"; }
zle -N physical-up-line _physical_up_line
zle -N physical-down-line _physical_down_line
bindkey '\e\e[A' physical-up-line
bindkey '\e\e[B' physical-down-line

# change 1st word: bindkey -M viins -s '\ea' '\C-a\e[3;5~'
_change_first_word() {
  zle beginning-of-line -N
  zle kill-word
}
zle -N change-first-word _change_first_word
bindkey -M viins '\ea' change-first-word

# replace first command with pager
# _run_with_pager() {
#   command="${PAGER-} ${BUFFER#* }"
#   zle push-line
#   BUFFER=${command}
#   zle accept-line
# }
# zle -N run-with-pager _run_with_pager
# bindkey '\C-x\C-l' run-with-pager

# }}}
# bindkey -s {{{
# auto-quote
# bindkey -s "\C-x\'" "'' \e[D\e[D"
# bindkey -s "\C-x\"" "\"\" \e[D\e[D"

# <c-x-..>
bindkey -s '^x=' '>/dev/null 2>&1'
bindkey -s '^x.' '\C-aeb \C-e^M'
# output in columns
bindkey -s '^x|' ' | column -t'
# put in $()
bindkey -s '^x\`' "\$()\C-b"
# put in ${}
bindkey -s '^xb' "\${}\C-b"
# dump-macros ala bash
bindkey -s '^xd' 'bindkey -L | grep "bindkey -s"^M'
# pipe to less
bindkey -s '^xl' '\C-e | less^M'
bindkey -s '^xp' '\eBprintf '\''%s\\n'\'' \eF'
bindkey -s '^xw' '\C-e | awk '\''^@{ print $ }'\''\C-b\C-b\C-b'
# bindkey -s '^x^d' '\eadift\C-e'
bindkey -s '^x^w' "\C-e | while read -r l; do  \$l; done\eB\eB\C-b"
bindkey -s '^x^z' '%-^M'

bindkey -s '^x1' '^A^[F'
bindkey -s '^x2' '^A^[F'
bindkey -s '^x2' '^A^[F^[F'
bindkey -s '^x3' '^A^[F^[F^[F'
bindkey -s '^x4' '^A^[F^[F^[F^[F'
bindkey -s '^x5' '^A^[F^[F^[F^[F^[F'

# <m-;> | >/dev/null
# bindkey -s '\e;' '>/dev/null 2>&1\C-m'
# bindkey -s '\e;' '2>&1 |tee log\C-m'

# <m-x> | insert last command result
# _insert_last_command_output() {
#   zmodload -i zsh/parameter
#   LBUFFER="$LBUFFER$(eval "$(fc -ln -1)" | tail -n 1)"
# }
# zle -N _insert_last_command_output
# bindkey '^[x' _insert_last_command_output
bindkey -s '^[x' "\$\(!-1 \| tail -n 1\)\t"
bindkey -s '^[X' "\$\(!-1 \| tail -n 1\)\C-xx"

bindkey -s '\e'\' "'\\\''"
bindkey -s '\e\"' '^[B"^[F"'
# <alt-bs> history undo
# bindkey -s '^[^?' '\C-u hundo\C-m'
bindkey -s '^[=' '; echo \$?'
bindkey -s '^[r' '^[Isudo ^[A'
# wrap in (set -x; ..)
bindkey -s '^[s' '\C-a(set -x; \C-e)\C-b'
bindkey -s '^[w' '\C-atype -f \C-e\C-m'
# bindkey -s '^[W' '\C-u status\C-m'
# <m-shift..>
bindkey -s '^[E' '^[Iv ^[A'
bindkey -s '^[H' ' --help'
bindkey -s '^[L' '\C-e\| (jq -C . | less -RSX)'
bindkey -s '^[V' ' --version'

# <f1> | append man
bindkey -s '^[OP' '\C-a\man \C-e\C-m'

# bindkey -L | grep '\^\[[.0-9]'
# expand to 2 last commands
# bindkey -s '^X2' '!-2\t ; !-1\t'
bindkey -s '\e`' "!:0- "  # all but last argument
bindkey -s '\e0' "!:1* "  # all but 1st argument (after 1st word)
# gets nth argument from last command
bindkey -s '\e1' "!:0-0 "
bindkey -s '\e2' "!:1-1 "
bindkey -s '\e3' "!:2-2 "
bindkey -s '\e4' "!:3-3 "
bindkey -s '\e5' "!:4-4 "
bindkey -s '\e6' "!:5-5 "
# bindkey -s '\e4' "!:$ " # last argument
# previous command with alt-N, where N is the number of arguments
# bindkey -s '\e2' "!:0-1 \t"
# bindkey -s '\e3' "!:0-2 \t"
# bindkey -s '\e4' "!:0-3 \t"
# bindkey -s '\e5' "!:0-4 \t"

## find ./
bindkey -s '^xf' '\C-e\C-ufind . -path "./.git" -prune -o -name "**" -print\eb\C-b\C-b\C-b'

## grep -r "" ./ # and avoid svn/git
bindkey -s '^xg' '\C-e\C-ufind . -path "./.git" -prune -o -type f -print0|xargs -0 grep --color=auto -s ""\C-b'
bindkey -s '^[g' '\C-e\C-ufind -L -- . -path "./.git" -prune -o -type f -print0|xargs -0 grep -E --color=auto -s ""\C-b'

## grep "" *
# bindkey -s '^[G' '\C-e\C-ugrep -I *\C-b\C-b ""\C-b'

## grep uniq
bindkey -s '^xu' '\C-e\C-ufind . -path "./.git" -prune -o -type f -print0|xargs -0 grep -l ""\C-b'

## grep uniq and open with vi
# bindkey -s '^xv' '\C-e\C-uvi \$(find . -path "./.git" -prune -o -type f -print0|xargs -0 grep -l "")\C-b\C-b'

# }}}

# rc.d
# if [ -d "${HOME%/}/.config/shell" ]; then
#   for file in "${HOME%/}"/.config/shell/*sh; do
#     . "${file}"
#   done
#   unset -v -- file
# fi
. "${HOME%/}"/.config/shell/aliases.sh
. "${HOME%/}"/.config/shell/lib.sh
. "${HOME%/}"/.config/shell/darwin.sh
. "${HOME%/}"/.config/shell/linux.sh

# test: for cmd fn in ${(kv)_comps}; print -r -- "$cmd -> $fn"
# zsh -ic 'for cmd fn in ${(kv)_comps}; do printf "%s %s\n" "$cmd" "$fn"; done'
# compdef: after compinit was called
# command -v -- _git >/dev/null 2>&1 && compdef _git gd='git-diff' >/dev/null 2>&1
compdef d=which
compdef define=which
compdef g=git
compdef gall=git
compdef gr=grep
compdef http-stats=curl
compdef ports=lsof
compdef pkgcat=pkg-config
compdef pkill=killall
compdef remake=make
compdef diffy=diff
compdef _gnu_generic file
compdef _parameters cat_env
compdef _path_files filesu
compdef _pids after pid2name
compdef _process_names filesp filespu
compdef _time_zone timein tz
# commands that take commands as arguments
compdef _precommand debug nh
case "$(uname)" in
  Darwin)
    # compdef nslookup_r=nslookup
    compdef _macapps app_anchors appdomain open-app
    compdef _pgrep pidof psargs
    ;;
  *)
    compdef _pids dumpenv
    compdef _precommand rlwrap
    _log() { _files -W /var/log -g "*~*.(gz|old|*[0-9])(-.)"; }
    compdef _log logview
    ;;
esac
_mkcd() { _path_files -/; }
compdef _mkcd mkcd cf md rmd
_conf() { _files -W ~/.config; }
compdef _conf conf
_indir() { _arguments '1:directory:_path_files -/' '*::args:_precommand'; }
compdef _indir ind indir in-dir
_bins() { _path_files -W ~/bin -g "**/*(*:t)"; }
compdef _bins si sausage
_projects() { _path_files -W ~/projects -/; }
compdef _projects jo

# fzy
if command -v fzy >/dev/null 2>&1; then
  # wrap current command in $( .... | fzy)
  bindkey -s '^[z' "\C-e | fzy)\C-a \$(\C-a"
  # pipe last command to fzy and pass the output to a new command
  # bindkey -s '^[Z' "\$\(!! \| fzy\)\C-a \C-m\C-m"
  # bindkey -s '^[E' "v \$\(!! \| fzy\)\C-a\C-m\C-m"
  # bindkey -s '\C-xu' 'turls^M'
  # LBUFFER="$(fc -ln 1 | cut -c 8- | tac | fzy)"
  # zle redisplay
  _fuzzy_history_widget() {
    BUFFER=$(fc -ln 1 | tail -r | fzy --query "${LBUFFER}")
    CURSOR=$#BUFFER
    zle reset-prompt
  }
  zle -N fuzzy_history_widget _fuzzy_history_widget
  bindkey '^R' fuzzy_history_widget
fi

# ~/bin/zshi
# interactive zsh, but automatically execute given command.
# zsh -is eval $COMMAND
# c.f. https://www.zsh.org/mla/users/2005/msg00599.html
# if [ "$1" = eval ]; then
#   shift
#   ICMD="$@"
#   set --
#   zle-line-init() {
#     BUFFER="$ICMD"
#     zle accept-line
#     zle -D zle-line-init
#   }
#   zle -N zle-line-init
# fi

# local zshrc | load machine-specific customization
test -f "${HOME%/}"'/.zshrc.local' && . "${HOME%/}"'/.zshrc.local' || :

# zprof
# eof
