#!/usr/bin/env zsh
# vim: ft=sh:fdm=marker:fdl=0:noml:
#
#                 ██
#  ██████  ██████░██
# ░░░░██  ██░░░░ ░██████
#    ██  ░░█████ ░██░░░██
#   ██    ░░░░░██░██  ░██
#  ██████ ██████ ░██  ░██
# ░░░░░░ ░░░░░░  ░░   ░░
#
# shellcheck disable=SC2034,SC3040

# profiling
# [ "${ZPROFRC-}" -ne 1 ] || zmodload zsh/zprof
# alias zprofrc="ZPROFRC=1 zsh"
# zmodload -F zsh/stat b:zstat
# zmodload zsh/datetime
#setopt PROMPT_SUBST
#PS4='+$EPOCHREALTIME %N:%i> '
#logfile=$(mktemp zsh_profile.XXXXXX)
#echo "Logging to $logfile"
#exec 3>&2 2>$logfile
#setopt XTRACE

# eval "$(/opt/homebrew/bin/brew shellenv)"
# if [ -e "/home/linuxbrew/.linuxbrew/bin/brew" ]; then
#   # shellcheck disable=SC2312
#   eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
# elif [ -e "/opt/homebrew/bin/brew" ]; then
#   export PATH="/opt/homebrew/bin:${PATH}"
#   # shellcheck disable=SC2312
#   eval "$(/opt/homebrew/bin/brew shellenv)"
# fi

# gpg cli in the tty
# export GPG_TTY="${TTY-}"

## $CDPATH
# export CDPATH="${CDPATH:+${CDPATH-}:}${HOME%/}"

# raise soft limits to hard limits
# ulimit $(bash --noprofile --norc -c 'diff <(ulimit -Ha) <(ulimit -Sa)' | sed -n 's/^<.*\(-\w\).*\s/\1 /p') >/dev/null

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

# cdpath: subdirs
# test "${PS1+set}"; echo $?
# dev_subdirs=$(printf '%s:' ~/dev/*)
# export CDPATH="${dev_subdirs}${HOME%/}/dev"
case $(uname) in
  Darwin)
    # projects_subdirs=$(printf '%s:' ~/projects/*)
    # projects_subdirs=$(printf '%s:' ~/repo/*)
    # export CDPATH="${projects_subdirs}${HOME%/}/projects"
    CDPATH=".:${HOME%/}:${HOME%/}/repo"
    ;;
  *)
    CDPATH=".:${HOME%/}:${HOME%/}/projects"
    ;;
esac
# CDPATH=.:$HOME:$HOME/.config/:$HOME/.local
# CDPATH=".:${HOME%/}:${HOME%/}/projects"

# shellcheck source=/dev/null
if [ -n "${GHOSTTY_RESOURCES_DIR-}" ]; then
  . "${GHOSTTY_RESOURCES_DIR-}"/shell-integration/zsh/ghostty-integration
fi

# config {{{1
# history
HISTCONTROL=ignoredups
HISTFILE="${XDG_STATE_HOME:-${HOME%/}/.local/state}"'/.sh_history'
SAVEHIST="$(printf -- '2 ^ 10 - 1\n' | command bc)"
HISTSIZE="$((SAVEHIST / 2))"

# note: `echo ${_comp_dumpfile}`
# test -d "${XDG_CACHE_HOME-}"'/zsh' || mkdir -p -- "${XDG_CACHE_HOME-}"'/zsh'
ZSH_COMPDUMP="${XDG_CACHE_HOME:-${HOME%/}/.cache}"'/zsh/zcompdump'
TMPPREFIX="${TMPDIR%/}/zsh"
LISTMAX=1000
# no EOL sign ('%')
PROMPT_EOL_MARK=""
# file to hold private keys
# private=~/.private

# zshoptions(1) {{{1
stty -ixon 2>/dev/null
# stty stop undef 2>/dev/null

set -o noclobber

# note: `echo ${options[correct]}`
set -o always_to_end
set -o complete_in_word
set +o flow_control
set +o hup
set -o autocd
# set -o shwordsplit
# 16.2.4 history
set -o hist_ignore_dups
set -o hist_ignore_space
set -o histverify
# set -o hist_findnodups
# set -o hist_savenodups
set -o printexitvalue
# disable "no match found" message
[ -n "${ZSH_ARGZERO-}" ] && set +o nomatch
# set -o combiningchars
# set -o monitor
# set -o shinstdin

# default:'*?_-.[]~=/&;!#$%^(){}<>'
# rlwrap: '(){}[],’+-=&^%$#@";|\'
# <M-DEL> should stop at -/.
WORDCHARS='*?_[]~=&;!#$%^(){}'
# WORDCHARS="*?_-.[]~&;$%^+"
# when offering typo corrections, do not propose anything which starts
# with an underscore (such as many of zsh's shell functions).
CORRECT_IGNORE='_*'

# fpath {{{1
# $^fpath
# autoload functions from executable files in $fpath
# autoload -U $^fpath/*(.xN:t)

case $(uname) in
  Darwin)
    # if command -v -- brew >/dev/null 2>&1; then
      # PATH="/opt/homebrew/opt/coreutils/libexec/gnubin:${PATH}"
      # placed ahead since it modifies $path and $fpath
      # see: https://docs.brew.sh/Shell-Completion
      # eval "$(command brew shellenv)"
      FPATH="${HOMEBREW_PREFIX-}/share/zsh-completions:${FPATH}"
      FPATH="${HOMEBREW_PREFIX-}/share/zsh/site-functions:${FPATH}"
    # fi
    ;;
  *)
    test -d '/usr/share/zsh/vendor-completions' \
      && FPATH="/usr/share/zsh/vendor-completions:${FPATH}"
    test -d '/usr/share/zsh/site-functions' \
      && FPATH="/usr/share/zsh/site-functions:${FPATH}"
    # plugin: zsh-completions ~/.local/share/zsh-completions/src
    test -d "${XDG_DATA_HOME-}"'/zsh-completions/src' \
      && FPATH="${XDG_DATA_HOME-}"'/zsh-completions/src':${FPATH}
    ;;
esac

test -d "${XDG_CONFIG_HOME-}"'/zsh/completions' \
  && FPATH="${XDG_CONFIG_HOME-}"'/zsh/completions':${FPATH}
test -d "${XDG_CONFIG_HOME-}"'/zsh/.zfunc' \
  && FPATH="${XDG_CONFIG_HOME-}"'/zsh/.zfunc':${FPATH}

# completion {{{1
# complist
# make sure menu-select widget (zsh/complist module) is loaded before compinit
# so that that widget is also re-defined
zmodload -i zsh/complist
# $^fpath/compinit(#qN)

# line editing during completion (man zshmodules: zsh/complist)
# menuselect
bindkey -M menuselect '^Xg' clear-screen
bindkey -M menuselect '^Xi' vi-insert
bindkey -M menuselect '^Xh' accept-and-hold
bindkey -M menuselect '^Xn' accept-and-infer-next-history
bindkey -M menuselect '^Xu' undo
# bindkey -M menuselect '^?' undo
bindkey -M menuselect '/' accept-and-infer-next-history
#bindkey -M menuselect '' send-break
#bindkey -M menuselect ' ' send-break

autoload -Uz compinit
compinit -d "${ZSH_COMPDUMP-}" 2>/dev/null
# [ "${+_comps}" -gt 0 ] && compinit -d "${ZSH_COMPDUMP}"
# automatically load bash completion functions
# autoload -U +X bashcompinit
# bashcompinit

# set -o auto_menu
# set +o menu_complete
# note: `echo ${_comp_options[@]}`
# _comp_options+=(globdots)
setopt dotglob

# zstyle {{{1
# :completion:<function>:<completer>:<command>:<argument>:<tag>
## menu | select completions with arrow keys
zstyle ':completion:*' menu select
# https://zsh.sourceforge.io/Doc/Release/Completion-System.html#Standard-Styles
# zstyle ':completion:*' completer _extensions _complete _approximate
# zstyle ':completion:*' completer _complete _match _approximate
# zstyle ':completion:*' completer _expand_alias _complete _match _prefix _ignored _approximate
zstyle ':completion:*' completer _extensions _complete _match _prefix _ignored _approximate

# zstyle ':completion::prefix:*' completer _complete
# zstyle ':completion::prefix:*' completer _complete _ignored:complete

# makes a particular prefix necessary (non-configurable) to show a set of matches:
# * for command options, need '-', '+' or '--' prefixes (the default)
# * for signal names, need '-' prefix (the default)
# * for job names, need '%' prefix (the default)
# * for function & param names, need '_' or '.' prefix if it starts with one of those
# zstyle ':completion:*' prefix-needed true
## use-cache | apt, dpkg (debian), rpm (redhat), perl
zstyle ':completion:*' use-cache true
zstyle ':completion:*' cache-path "${XDG_CACHE_HOME}"/zsh/zcompcache
# complete alias when _expand_alias is used as a function
zstyle ':completion:*' complete true
## group-name | group results by category (named after the tags)
zstyle ':completion:*' group-name ''
# always offer the original string as a completion choice
# zstyle ':completion:*:match:*' original true
# autocomplete options for cd instead of directory stack
zstyle ':completion:*' complete-options true
# zstyle ':completion:*' rehash true
zstyle ':completion:*:commands' rehash 1
zstyle ':completion:*' file-sort 'modification'
## format
# set descriptions format to enable group support
# zstyle ':completion:*:descriptions' format '[%d]'
zstyle ':completion:*:descriptions' format '-- %d --'
## list
zstyle ':completion:*' list-separator '->'
zstyle ':completion:*' list-colors ''
zstyle ':completion:*' list-colors no=00 fi=00 di=01\;34 pi=33 so=01\;35 bd=00\;35 cd=00\;34 or=00\;41 mi=00\;45 ex=01\;32
## zshcompwid(1) | "completion matching control"
# auto-cap, substr
# zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' 'l:|=* r:|=*'
zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=* l:|=*'
# zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z} r:|=*' 'm:{a-zA-Z}={A-Za-z}  l:|=* r:|=*' 'm:{a-zA-Z}={A-Za-z}'

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

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

# zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'

## case-insensitive (all),partial-word and then substring completion
#zstyle ':completion:*:*:*:*:*' menu ''
# zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={a-zA-Z}' #'r:|[._-]=* r:|=*' 'l:|=* r:|=*'

# in a dir with 'nix' and 'nix-home' directories, makes 'nix' match both, and
# 'nix/' match only 'nix'. does _not_ block partial path completions like '/u/b/foo'.
# zstyle ':completion:*' accept-exact-dirs true
# when corrections needed/triggered, always give ability to select original text
zstyle ':completion:*' original true

# when _approximate completer is active, allow errors based on the size of the text
# NOTE: it is case-sensitive, even if you have a matcher-list cfg to make it insensitive
# shellcheck disable=SC2016
# zstyle -e ':completion:*:approximate:*' max-errors 'reply=( $(( ($#PREFIX + $#SUFFIX) / 3 )) )'
# zstyle ':completion:*:match:*' original only
zstyle -e ':completion:*' max-errors 'reply=( $(( ($#PREFIX+$#SUFFIX)/3 )) numeric )'
# zstyle ':completion:*:approximate:::' max-errors 3 numeric
# allow completion of ..<Tab> to ../ and beyond.
# zstyle -e ':completion:*' special-dirs '[[ $PREFIX = (../)#(..) ]] && reply=(..)'
## /u/l/s<TAB> => /usr/local/share
# ls f/b/b<tab> results in fob/bar/bing/ fob/baz/bing/ foo/bar/bing/ ... vs (fob|foo)/b/b
zstyle ':completion:*' list-suffixes true
zstyle ':completion:*' use-compctl false
zstyle ':completion:*' verbose true
## tag-order
# array/association element sorting | more useful than parameters.
zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters
## tag-order
# disable named-directories autocompletion
zstyle ':completion:*:cd:*' tag-order local-directories path-directories directory-stack
# cd | lax completion for cd.
# zstyle ':completion:*:cd:*' tag-order '*' '*:-case'
# zstyle ':completion:*-case' matcher 'm:{a-zA-Z0-9}={A-Za-z0-9}' 'l:|=* r:|=*'
# zstyle ':completion:*:ls:*' list-dirs-first true
# zstyle ':completion:*' keep-prefix true
# zstyle ':completion:*:expand:*' keep-prefix true
## group-order
zstyle ':completion:*:*:-command-:*:*' group-order \
  aliases builtins functions commands
## ignored-patterns
zstyle ':completion:*:functions' ignored-patterns '(_*|pre(cmd|exec))'
# history | cycle through history completion (M-/, M-,).
zstyle ':completion:history-words:*:history-words' stop yes
zstyle ':completion:history-words:*:history-words' list no
zstyle ':completion:history-words:*' remove-all-dups true
# zstyle ':completion:history-words:*' menu yes
## processes
# kill
zstyle ':completion:*:kill:*' command "ps -u ${LOGNAME} -o pid,%cpu,comm -w"
zstyle ':completion:*:*:*:*:processes' command "ps -u ${LOGNAME} -o pid,uid,comm -w"
zstyle ':completion:*:processes' command "ps -u ${LOGNAME} -o pid,uid,nice,stime,args"
# killall
zstyle ':completion:*:processes-names' command 'ps -e -o comm='
# zstyle ':completion:*:*:*:*:processes' force-list always
## hosts | known_hosts_file too slow.
zstyle ':completion:*' hosts ''
zstyle ':completion:*:hosts' known-hosts-files ''
## man | separate-sections insert-sections | `man strstr` => `man 3 strstr`
zstyle ':completion:*:manuals' separate-sections true
zstyle ':completion:*:manuals.(^1*)' insert-sections true
# disable hosts completion for ssh/scp from `/etc/hosts` and `~/.ssh/known_hosts`
# so that completion only reads aliases from `~/.ssh/config`
zstyle -e ':completion:*:*:(scp|ssh):*:*' hosts 'reply=()'
zstyle -e ':completion:*:*:(scp|ssh):*:*' known-hosts-files 'reply=()'
# make
# zstyle ':completion:*:*:make:*' list-rows-first
zstyle ':completion:*:make:*:targets' call-command true

# # only check for changes to completion once a day.
# # if you need to force a recheck, just delete ~/.zcompdump.
if is-zcompdump-outdated; then
  # compinit
  compinit -d "${ZSH_COMPDUMP-}"
else
  compinit -C -d "${ZSH_COMPDUMP-}"
fi

# share all commands from everywhere
set -o share_history
# permit inline comments
set -o interactive_comments

# compdef {{{1
# must be done *after* compinit was called
command -v -- _bat >/dev/null 2>&1 \
  && compdef -- bats='bat'
command -v -- _which >/dev/null 2>&1 \
  && compdef -- define='which' \
  && compdef -- d='define'
compdef -- diffy='diff' 2>/dev/null || command -p -- true
# `#compdef` instead of `compdef`?
# https://github.com/zph/dotfiles/blob/735c49534e/home/dot_zsh.d/git.zsh
command -v -- _git >/dev/null 2>&1 \
  && compdef -- g='git'

command -v -- _grep >/dev/null 2>&1 \
  && compdef -- gr='rg'
command -v -- _rg >/dev/null 2>&1 \
  && compdef -- rga='rg'
compdef _rg rgc
command -v -- _nslookup >/dev/null 2>&1 \
  && compdef -- nslookup_r='nslookup'

command -v -- _cht >/dev/null 2>&1 \
  && compdef -- _cht cheat

compdef remake=make
#compdef _wtf h
compdef ping6=ping
compdef _directories cf
compdef _directories md
compdef _directories mkcd
compdef _directories rmd
compdef _gnu_generic file
# commands that take commands as arguments
compdef _precommand gdb
compdef _precommand nohup
compdef _precommand rlwrap
compdef _pids pid2name
compdef _run-help zman

compdef "_files -W \"${XDG_CONFIG_HOME:-${HOME%/}/.config}\"" conf
# compdef "_files -W \"${HOME%/}/repo\"" repo
compdef "_files -W \"${PROJECTS-}\" -/'" pj
# compdef "_files -W \"${WORKON_HOME-}\"" workon
compdef "_files -W \"${WORKON_HOME}\" -/ -S '' -F '*/*'" workon
compdef "_files -g \"*.pdf\"" pdfclean
compdef "_files -g '*(^*)'" cx
compdef "_files -g '*(*)'" unx

# bindkey {{{1
# vi | needs to run before compinit installs keybindings
bindkey -v
# vi mode is 0.4s by default, and you can make it shorter (0.05s) with
# allow 50ms btw esc + subsequent character
# 0.05 seconds delay for switching modes
KEYTIMEOUT=5

# readline
# see: https://github.com/sunaku/home/blob/master/.zsh/config/zle.zsh#L15C1-L16C76
#is-linux && eval "$(sed -n 's/^\( *[^#][^:]*\):/bindkey \1/p' /etc/inputrc ~/.config/readline/inputrc)"
# is-mac && eval "$(sed -n 's/^\( *[^#][^:]*\):/bindkey \1/p' ~/.config/readline/inputrc)"

# keys
# del $terminfo[kdch1]
bindkey '\e[3~' delete-char
# bs $terminfo[kbs]
bindkey '^?' backward-delete-char
# ctrl <- ctrl ->
bindkey '\e[1;5D' backward-word
bindkey '\e[1;5C' forward-word
bindkey '\e[5D' backward-word
bindkey '\e[5C' forward-word
# home end
bindkey '\e[1~' beginning-of-line
bindkey '\e[4~' end-of-line
# fix home/end keys (for mosh)
bindkey '\e[7~' beginning-of-line
bindkey '\e[8~' end-of-line
bindkey '\eOH' beginning-of-line
bindkey '\eOF' end-of-line
bindkey '\e[H' beginning-of-line
bindkey '\e[F' end-of-line
# pageup/down
# bindkey '\e[5~' ''
bindkey '\e[6~' end-of-buffer-or-history
# alt <- alt ->
bindkey '\e[1;3C' forward-word
bindkey '\e[1;3D' backward-word
bindkey '\e[A' up-line-or-search
bindkey '\e[B' down-line-or-search
bindkey '\eOA' up-line-or-search
bindkey '\eOB' down-line-or-search

# zle autoload {{{1
unset zle_bracketed_paste

# zshzle | zle_highlight
# https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting
# suffix dont draw trailing / in bold zsh ≥ 4.3.11.
zle_highlight='region:standout special:standout suffix:none isearch:underline paste:none'

## <c-x/a> | alias-expension
# zstyle -s ':completion:expand-alias-word:::' regular yes
zle -C alias-expension complete-word _generic
bindkey '^Xa' alias-expension
zstyle ':completion:alias-expension:*' completer _expand_alias

# 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
# remove original text in matches
zstyle ':completion:expand-param-or-alias:*' tag-order '!original'
bindkey '^Xx' expand-param-or-alias

# escape urls automatically.
# dropped { } | to create multiple URLs, e.g. http://example.org/{1,2,3}.txt
autoload -Uz bracketed-paste-magic url-quote-magic
zle -N bracketed-paste bracketed-paste-magic
zstyle ':url-quote-magic:*' url-metas '*?[]^(|)~#=' # dropped { }
# zstyle ':url-quote-magic:*' url-metas '*?[]^()~#' # remove "=|{}"
zle -N self-insert url-quote-magic

# replace insert-last-word by a smart version
autoload -U smart-insert-last-word
zstyle :insert-last-word match '*([^[:space:]][[:alpha:]/\\]|[[:alpha:]/\\][^[:space:]])*'
zle -N insert-last-word smart-insert-last-word
bindkey -M viins '\e.' insert-last-word
# zle -N insert-last-assignment smart-insert-last-word
# zstyle :insert-last-assignment match '[[:alpha:]][][[:alnum:]]#=*'
# bindkey -M viins '\e=' insert-last-assignment

# select-word-style | make ^W stop at non-alphanumeric characters
# note: before zsh-history-substring-search & zsh-syntax-highlighting.
autoload -Uz select-word-style
select-word-style bash
# also match these additional characters as a "word".
# zstyle ':zle:*' word-chars '-_'

# history
autoload -U up-line-or-beginning-search
zle -N up-line-or-beginning-search
autoload -U down-line-or-beginning-search
zle -N down-line-or-beginning-search
# only search for typed commands, not full history
autoload -U history-search-end
zle -N history-beginning-search-backward-end history-search-end
zle -N history-beginning-search-forward-end history-search-end
bindkey '\e[A' history-beginning-search-backward-end
bindkey '\e[B' history-beginning-search-forward-end
bindkey '^[OA' history-beginning-search-backward-end
bindkey '^[OB' history-beginning-search-forward-end

# vim like completions of previous executed commands (also enter vi-mode).
_vi_history_beginning_search_backward() {
  if [ "${CURSOR-}" -ne 0 ]; then
    not_at_beginning_of_line=yes
  fi
  zle history-beginning-search-backward
  # start Vi-mode and stay at the same position (vi-mode moves one left, this counters it).
  zle vi-cmd-mode
  if [ -n "${not_at_beginning_of_line}" ]; then
    zle vi-forward-char
  fi
}
zle -N vi-history-beginning-search-backward _vi_history_beginning_search_backward
bindkey '^p' vi-history-beginning-search-backward
# binding for Vi-mode
bindkey -a '^p' history-beginning-search-backward
# only vi-mode necessary, as ^P enters vi-mode, ^N only makes sense after calling ^P.
bindkey -a '^n' history-beginning-search-forward

# use current input when pressing <ctrl-r>.
_history_incremental_pattern_search_backward() {
  zle .history-incremental-pattern-search-backward "${BUFFER}"
}
zle -N history-incremental-pattern-search-backward \
  _history_incremental_pattern_search_backward
# enable incremental search | especially useful when string is an argument and not command.
bindkey '^r' history-incremental-pattern-search-backward
# also enable usual use of <ctrl-P/ctrl-N> to get the previous/next matching
# history entry.
bindkey -M isearch '^p' history-incremental-pattern-search-backward
bindkey -M isearch '^n' history-incremental-pattern-search-forward

# sometimes pressing <esc-/> quickly (i.e., to do a reverse-i-search with
# bindkey -v turned on) would not work properly. this fixes it.
# vi_search_fix() {
#   zle vi-cmd-mode
#   zle .vi-history-search-backward
# }
# # autoload vi_search_fix
# zle -N vi_search_fix
# bindkey -M viins '\e/' vi_search_fix

# better than copy-prev-shell-word, can be called repeatedly.
# bindkey '\e=' copy-prev-shell-word
autoload -U copy-earlier-word
zle -N copy-earlier-word
bindkey -M viins '^[m' copy-earlier-word

# bindkey -r '\e/'
# bindkey -r '\e,'
bindkey -r '^q'

# 28oct2025  +house+ TODO
# bindkey -M viins '^S' push-line
# bindkey '^q' push-line-or-edit
# saves the current line and returns to it afterwards.
# bindkey '^P' push-line

# complete in history with M-/, M-,
# bindkey "\e/" _history-complete-older
# bindkey "\e," _history-complete-newer
# <a-tab>
bindkey -M viins '^[^I' _history-complete-older
# <a-s-tab>
bindkey -M viins '^[^[[Z' _history-complete-newer

# autoload -Uz transpose-words-match
# zstyle ':zle:transpose-words' word-style shell
# zle -N transpose-words transpose-words-match

# defaults {{{1
# <alt + bs>
bindkey '^[^?' backward-kill-word
# <alt-del> word ahead of cursor
bindkey '\e[3;3~' delete-word
# <c-del>
bindkey '\e[3;5~' kill-word
# <c-alt-h>
bindkey '^[^H' vi-backward-kill-word
bindkey '\e[Z' reverse-menu-complete

bindkey '^a' beginning-of-line
bindkey '^b' backward-char
bindkey '^d' delete-char-or-list
bindkey '^e' end-of-line
bindkey '^f' forward-char
bindkey '^k' kill-line
bindkey '^u' backward-kill-line
bindkey '^v' vi-quoted-insert
bindkey '^w' backward-kill-word
bindkey '^y' yank

# dont do history expansion
bindkey ' ' magic-space
bindkey -M isearch ' ' magic-space
# bindkey '^Xa' _expand_alias
bindkey '^Xe' _expand_word
bindkey '^Xg' list-expand
bindkey '^Xh' _complete_help
bindkey '^Xm' _most_recent_file
bindkey '^X^b' vi-match-bracket
# bindkey '^X^h' _complete_debug
bindkey '^X^j' vi-join
bindkey '^X^k' kill-buffer
bindkey '^X^o' overwrite-mode
bindkey '^X^u' undo
bindkey '^X^x' exchange-point-and-mark

# jump to char (vim f/F), or use ^x^v f ...
bindkey '^Xf' .vi-find-prev-char
bindkey '^X^f' .vi-find-next-char

# bindkey -M viins '' vi-cmd-mode
bindkey -M viins '\eb' vi-backward-word
bindkey -M viins '\eB' vi-backward-blank-word
bindkey -M viins '\ef' vi-forward-word
bindkey -M viins '\eF' vi-forward-blank-word

bindkey -M viins '\eK' describe-key-briefly
bindkey -M vicmd 'K' describe-key-briefly

bindkey -M viins '\eu' undo
bindkey -M viins '\eU' redo

# edit-command-line
# a-v | c-v
autoload -Uz edit-command-line
zle -N edit-command-line
# allow vv to edit the command line (standard behaviour)
bindkey -M vicmd 'vv' edit-command-line
# <ctrl-v> for edit => v is used for visual mode
bindkey -M vicmd '^v' edit-command-line

_vi_yank() {
  zle vi-yank
  echo "${CUTBUFFER-}" | pbcopy
}
zle -N _vi_yank
bindkey -M viins '\ey' _vi_yank
bindkey -M vicmd 'y' _vi_yank

# quote-line
# apply quotes to the current line/region
bindkey -M viins '\eq' quote-line
bindkey -M vicmd '\eq' quote-line
# quote-region
bindkey -M viins '\eQ' quote-region
bindkey -M vicmd '\eQ' quote-region
# bindkey -M vicmd '""'  quote-line

# zap
zmodload zsh/deltochar
bindkey -M viins '\ez' zap-to-char
bindkey -M viins '\eZ' delete-to-char

# option(alt) + ←→
bindkey -M vicmd '\e[1;3C' forward-word
bindkey -M vicmd '\e[1;3D' backward-word

# run command without clearing commandline
bindkey -M viins 'x' execute-named-cmd
bindkey -M vicmd ':' execute-named-cmd
bindkey -M vicmd 'gg' beginning-of-history
bindkey -M vicmd 'G' end-of-history

# vicmd {{{1
# incarg - increment digit
autoload -U incarg
zle -N incarg
bindkey -M vicmd '^a' incarg
# bindkey -M vicmd ga what-cursor-position

# pipe a text selected by a motion through another command
autoload -Uz vi-pipe
zle -N vi-pipe
bindkey -a '!' vi-pipe

bindkey -M vicmd '|' send-break
bindkey -M vicmd '_' vi-first-non-blank
# sensible
bindkey -M vicmd 'H' beginning-of-line
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
# whole-line
bindkey -M vicmd 'y.' vi-yank-whole-line
bindkey -M vicmd 'c.' vi-change-whole-line
bindkey -M vicmd 'd.' kill-whole-line
bindkey -M vicmd '^u' vi-kill-line

# 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

# vi-custom-widgets
# -----------------

_vi_kill_eol() {
  clip="$(pbpaste)"
  zle .vi-kill-eol
  print -rn "${clip}" | pbcopy
}
zle -N _vi_kill_eol
bindkey -M vicmd 'D' _vi_kill_eol

# yy | copy text, display message
_copymsg() {
  print -rn "${BUFFER}" | pbcopy
  zle -M "copied: ${BUFFER}"
}
zle -N _copymsg
bindkey -M vicmd 'yy' _copymsg

# x | cut text in visual mode and copy
_vi_delete_visual() {
  zle .vi-delete
  print -rn "${CUTBUFFER-}" | pbcopy
}
zle -N _vi_delete_visual
bindkey -M visual 'x' _vi_delete_visual

# surround text under cursor
bindkey -M vicmd -s 'y;' "viwS"
# avoid issue where escape in command mode will eat next character
# bindkey -M vicmd -s '\e' ''

# zle-custom-widgets {{{1
# <c-@> | expand everything under cursor with ^space
_expand_all() {
  zle _expand_alias
  zle expand-word
  # zle expand-history
  # zle self-insert
}
zle -N _expand_all
bindkey '^ ' _expand_all
# bindkey ' ' _expand_all
# bindkey -M vicmd '\$' _expand_all
# bindkey -M viins '\t' _expand_all

# # <`c-x--`> <`c-x-=`>
# # toggle predict-on/off
# _predict_on() {
#   autoload -U +X predict-on
#   zstyle ':completion:*' completer _expand _complete _ignored
#   predict-on
# }
# _predict_off() {
#   autoload -U +X predict-off
#   zstyle ':completion:*' completer _expand _complete _ignored _approximate
#   predict-off
# }
# zle -N _predict_on
# bindkey '^X-' _predict_on
# zle -N _predict_off
# bindkey '^X=' _predict_off

# <c-l> | clear_scrollback_buffer
_clear_screen() {
  # clear && printf '\e[3J'
  clear && printf '\E[H\E[2J'
  # clear && printf "\e[H\e[3J"
  zle && builtin zle .reset-prompt
  builtin zle -R
}
zle -N _clear_screen
bindkey '^l' _clear_screen

# <c-o> | copy the active line from the command line buffer
_copybuffer() {
  printf '%s' "${BUFFER}" | pbcopy
}
zle -N _copybuffer
# bind for all, incl. VIM mode
bindkey '^o' _copybuffer
bindkey -a '^o' _copybuffer
# bindkey '^X^y' _copybuffer
# bindkey '^Xy' _copybuffer

# <c-v> | paste
_pastebuffer() {
  LBUFFER="${LBUFFER}$(pbpaste)"
  zle redisplay
}
zle -N _pastebuffer
bindkey '^[p' _pastebuffer
bindkey -M viins '^Xv' _pastebuffer
bindkey -M viins '^X^v' _pastebuffer
# bindkey -s '^[p' "printf %s \"$(pbpaste)\""

# <c-z> | fg-bg
# https://ao.bloat.cat/exchange/superuser.com/questions/378018/placeholder#378045
_fg_bg() {
  if test -z "${BUFFER}"; 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
bindkey -M viins '^z' _fg_bg
bindkey -M vicmd '^z' _fg_bg

# <c-x-L> | replace first command with pager
_run_with_pager() {
  command="${PAGER-} ${BUFFER#* }"
  zle push-line
  BUFFER=${command}
  zle accept-line
}
zle -N _run_with_pager
bindkey '^XL' _run_with_pager

# <c-x-o> | new command
_new_command() {
  zle push-input
  BUFFER=""
}
zle -N _new_command
bindkey '^Xo' _new_command

# <alt-up/down> | 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
zle -N _physical_down_line
#bindkey '\e\e[A' _physical_up_line
#bindkey '\e\e[B' _physical_down_line
bindkey '\e[1;3A' _physical_up_line
bindkey '\e[1;3B' _physical_down_line

# # <m-space>
# _prepend_space() {
#   LBUFFER=" ${LBUFFER## #}"
#   if [ "${BUFFER%% #} " != "${BUFFER} " ]; then
#     # trim the trailing whitespace unless it's a single space
#     BUFFER="${BUFFER%% #} "
#   fi
# }
# zle -N _prepend_space
# bindkey '\e ' _prepend_space

edit_command_line_in_shell_mode() {
  # based on edit-command-line widget
  tmpfile=${TMPPREFIX:-/tmp/zsh}ecls$$
  # tmpfile=${TMPPREFIX:-${TMPDIR%/}/zsh}$$
  print -R - "${PREBUFFER-}${BUFFER-}" >"${tmpfile}"
  # added emacs mode specification
  print "# Local Variables:\n# mode: shell-script\n# End:" >>"${tmpfile}"
  ${VISUAL:-${EDITOR:-vi}} "${tmpfile}"
  exec </dev/tty
  # added deletion of comment lines
  # shellcheck disable=SC2312
  print -Rz - "$(sed '/^#/d' <"${tmpfile}")"
  command rm -f "${tmpfile}"
  zle send-break
}
zle -N edit_command_line_in_shell_mode
bindkey '^X^e' edit_command_line_in_shell_mode

# <m-D>
# see: https://git.madduck.net/etc/zsh.git/blob/HEAD:/.zsh/zshrc/20-tempfile+dir_functions
# cdt() {
#   emulate -L zsh
#   dirname="$(date +'%F-%H%M%S')${1:+-$1}"
#   REPLY="${TMPDIR:-/tmp}/${dirname}"
#   mkdir -m700 "${REPLY}"
#   if [ -n "$1" ]; then
#     link="${TMPDIR:-/tmp}/${1:-cdt}"
#     ln -Tnsf "${dirname}" "${link}"
#     builtin cd "${link}" || return
#   else
#     builtin cd "${REPLY}" || return
#   fi
#   echo "${REPLY}"
#   print -s cd "${REPLY}"
# }
# _cdt() {
#   cdt "$@" >/dev/null
#   zle reset-prompt
#   zle -M "${REPLY}"
# }
# zle -N _cdt
# bindkey '\eD' _cdt

# # <m-l> | insert separator ---
# zle_insert_line() {
#   printf '%b' "\e[0G\e[K"
#   perl -Mutf8 -CS -e 'print "\N{U+2500}" x $ARGV[0], "\n"' "${COLUMNS}"
#   zle redisplay
# }
# zle -N zle_insert_line
# bindkey '\el' zle_insert_line

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

# bindkey -s {{{1
# TODO(2025-08-16): bindkeys
# # ed                                   :: e, E
# "\C-xe": "printf '%s\\n' H \e  wq | 'ed' -s "
# "\C-xE": "printf '%s\\n' H 0i \e  . wq | 'ed' -s "
# ^xe ed
# bindkey -s '^Xe' "printf '%s\\\n' H ^@ wq | 'ed' -s "
# bindkey -s '^XE' "printf '%s\\\n' H 0i ^@ . wq | 'ed' -s "
# # loops                                :: f, F, u, w
# "\C-xf": "for i in \e ; do  \"$i\"; done\e2\eb\e3\C-b"
# "\C-xF": "for ((i = 0; i < \e ; i++)); do  \"$i\"; done\e2\eb\e3\C-b"
# "\C-xu": "until \e ; do ; done\eb\e2\C-b"
# "\C-xw": "while \e ; do ; done\eb\e2\C-b"
# bindkey -s '^X?' '\eb=\ef\C-x*'
# bindkey -s '^X^e' rlwrap-call-editor
# bindkey -s '^Xv' '|& vim -'
# bindkey -s '^X=' "bc <<< 'scale=20; '^b"            # bc

# grep prefix
# grep -r "" ./ # and avoid svn/git
bindkey -s -M viins '\C-x\C-r' "\C-e\C-ufind . -path \"./.svn\" -prune -o -path \"./.git\" -prune -o -type f -print0|xargs -0 grep --color=auto -s \"\"\C-b"
# " grep "" *
bindkey -s -M viins '\C-x\C-g' "\C-e\C-ugrep -I *\C-b\C-b \"\"\C-b"
# find ./
bindkey -s -M viins '\C-x\C-f' "\C-e\C-ufind . -path \"./.svn\" -prune -o -path \"./.git\" -prune -o -name \"**\" -print\eb\C-b\C-b\C-b\C-b"
# grep uniq
# bindkey -s -M viins '\C-g\C-u' "\C-e\C-ufind . -path \"./.svn\" -prune -o -path \"./.git\" -prune -o -type f -print0|xargs -0 grep -l \"\"\C-b"
# # grep uniq and open with vi
# bindkey -s -M viins '\C-g\C-v' "\C-e\C-uvi $(find . -path \"./.svn\" -prune -o -path \"./.git\" -prune -o -type f -print0|xargs -0 grep -l \"\")\C-b\C-b"

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

bindkey -s -M viins '^X/' '; echo $?'
# shellcheck disable=SC1003
bindkey -s -M viins "^X\'" ''\''\\'\'\'                      # escaped single-quote
bindkey -s -M viins '^X\|' ' | column -t'                    # output in columns
bindkey -s -M viins '^X\`' '\$\(\)\C-b'                      # put in $()
bindkey -s -M viins '^X1' '\C-a\ef'                          # go to 1st arg
bindkey -s -M viins '^Xb' '\$\{\}\C-b'                       # put in ${}
bindkey -s -M viins '^Xd' 'bindkey -L | grep "bindkey -s"\n' # dump-macros ala bash
bindkey -s -M viins '^Xk' '\e[A\n'                           # run-again
bindkey -s -M viins '^Xl' '\C-e | less\n'                    # pipe to less
bindkey -s -M viins '^X^l' '\C-e | tee /dev/tty | less'      # peek while piping to less
bindkey -s -M viins '^Xn' '*(om[1]D)^i'                      # newest
bindkey -s -M viins '^Xp' '\eBi\printf '\''%s\\n'\'' \ef'    # printf
bindkey -s -M viins '^X^s' '\C-asudo \C-e'
bindkey -s -M viins '^Xt' ' && echo ok'

## ^xw ^x^w | awk
bindkey -s '^Xw' '\C-e | awk '\''^@{print $}'\''\C-b\C-b'
bindkey -s '^X^w' "awk '{sum += $1} END {print sum}' "

## ^x^z | job
# bindkey -s '^X^z' '%-^M'
# ^xg | detached
# bindkey -s '\C-xg' '\C-anohup \C-e >/dev/null 2>&1 </dev/null &'

# <a-c-b> | <^[^b> send command into background silently
bindkey -s -M viins '\e\C-b' '\C-e >/dev/null 2>&1 &\C-m'

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

# quote/bracket
# bindkey -s '\eq' '\e[1;3D"\C-e"'
bindkey -s -M viins '^[;' '\C-a\ef\"\C-e\"'
bindkey -s '\e\"' '\eb\"\ef\"'
bindkey -s '\e'\' "\eb\'\ef\'"
bindkey -s '\e\]' '\eb\[\ef\]'
bindkey -s '\e\}' '\eb\{\ef\}'
bindkey -s '\e\)' '\eb\(\ef\)'

bindkey -s '^[-' '^Vcd -^M'
bindkey -s '^[=' '^V..^M'
# bindkey -s '^[>' '^Q..^M' # alt-s-.
# <m-a> | change 1st word
bindkey -s '\ea' '\C-a\e[3;5~'
# <m-d> | define
bindkey -s -M viins '^[d' '\C-ad \C-e'
# <m-s> | lt
bindkey -s '\el' '\C-uls -ltr\C-m'
# <m-v> | editor
bindkey -s '^[v' "\e\$a | \$EDITOR\n"

# <m-L> | jq less
bindkey -s '\eL' '\C-e\|(jq -C . | less -RSX)'
bindkey -s '^[H' ' --help'
# <m-S> | wrap in (set -x; ..)
bindkey -s '\eS' '\C-a(set -x; \C-e)\C-b'
bindkey -s '^[V' ' --version'
#bindkey -s '^[X' "\"\$(!! | tail -n1)\""

# <a-[1-9]> | quick jumping to n-th arguments by pressing <alt-number>
bindkey '^[1' beginning-of-line
bindkey -s '^[2' '^A^[f'
bindkey -s '^[3' '^A^[f^[f'
bindkey -s '^[4' '^A^[f^[f^[f'
bindkey -s '^[5' '^A^[f^[f^[f^[f'
bindkey -s '^[6' '^A^[f^[f^[f^[f^[f'
bindkey -s '^[7' '^A^[f^[f^[f^[f^[f^[f'
bindkey -s '^[8' '^A^[f^[f^[f^[f^[f^[f^[f'
bindkey -s '^[9' '^A^[f^[f^[f^[f^[f^[f^[f^[f'

# <a-[1-9]> | print previous command with Alt-N, where N is the number of arguments
# bindkey -s '\e1' "!:0 \t"
# bindkey -s '\e2' "!:0-1 \t"
# bindkey -s '\e3' "!:0-2 \t"
# bindkey -s '\e4' "!:0-3 \t"
# bindkey -s '\e5' "!:0-4 \t"
# all but the last word
bindkey -s '\e`' "!:0- \t"

# bindkey -s -M viins '^X2' '!-2\t ; !-1\t' # expand to 2 last commands

# ghostty | see: https://github.com/ghostty-org/ghostty/discussions/5071
# bindkey -M viins '^[[91;5u' vi-cmd-mode
# bindkey -s '^[[91;5u' '^['
# bindkey -s -M vicmd '^[[91;5u' '^['

if [ -d '/usr/share/zsh/help' ]; then
  HELPDIR=/usr/share/zsh/help
else
  HELPDIR=/usr/share/zsh/"${ZSH_VERSION-}"/help
fi
unalias run-help 2>/dev/null && autoload -U run-help
# <m-h> | run-help
bindkey '^[h' run-help

# cursor {{{1
# autoload -U promptinit
# promptinit
# printf "\e[6 q" > "${TTY:-}"

# add-zsh-hook add-zle-hook-widget
case "${TERM-}" in
  xterm* | rxvt* | screen* | konsole* | alacritty* | st* | foot*)
    _z_cursor() {
      case ${KEYMAP-} in
        # block
        vicmd | visual) printf '\033[2 q' ;;
        # bar
        *) printf '\033[6 q' ;;
      esac
    }
    # set cursor shape to beam
    printf "\033[6 q"
    # zle -N zle-line-init _z_line_init
    zle -N zle-line-finish _z_cursor
    zle -N zle-keymap-select _z_cursor
    ;;
  *) ;;
esac

# hook {{{1
# prompt
# PS1="%m%(?.. %??)%(1j. %j&.) %${NDIRS:-2}~%#${SSH_CLIENT:+%#} "
# PS1="%(?.. %??)%(1j. %j&.) %${NDIRS:-2}~ "${PS1}
# PROMPT='%2~ %# '
PS1='%2~ $ '
# env | grep -qw 'SSH_CLIENT\|SSH_TTY'
if [ -n "${SSH_CLIENT:-}" ] || [ -n "${SSH_CONNECTION:-}" ]; then
  # PS1='%m:%~%(!.#.$) '
  PS1='%m:%1d $ '
fi

# only in response to user-initiated `cd`, not indirectly. e.g. via a function
_auto_ls_after_cd() {
  emulate -L zsh
  if [ "${ZSH_EVAL_CONTEXT:-}" = "toplevel:shfunc" ]; then
    ls -AF
  fi
}
autoload -U add-zsh-hook
add-zsh-hook chpwd _auto_ls_after_cd

# }}}1

# ^x^w to save, ^c to abort.
# zz accept
autoload -U zed

for zdir in \
  /usr/share/zsh/"${ZSH_VERSION}" \
  /usr/share/zsh; do
  [ -d "${zdir}" ] && break
  alias zdir='cd ${zdir:-}'
done

# shell rc.d
if [ -d "${HOME%/}/.config/shell" ]; then

  for file in "${HOME%/}"/.config/shell/*sh; do
    # shellcheck disable=SC1090
    . "${file-}"
  done

  # fzf {{{1
  if command -v fzf >/dev/null 2>&1; then
    # shellcheck disable=SC2312
    eval "$(fzf --zsh)"
    # export FZF_COMPLETION_TRIGGER='??'
    # export FZF_COMPLETION_DIR_COMMANDS="cd pushd rmdir tree ls"
    # . "${XDG_CONFIG_HOME:-${HOME%/}/.config}"'/shell/libfzf.sh'

    # fzf_completion {{{2
    # _fzf_compgen_path() {
    #   rg --files --follow --hidden --glob "!.git" "$1"
    # }
    # _fzf_compgen_dir() {
    #   fd --type d --hidden --follow --exclude ".git" . "$1"
    # }
    #
    # _fzf_comprun() {
    #   command="$1"
    #   shift
    #   case "${command}" in
    #     cd) # cd **<TAB>
    #       fzf "$@" --preview 'eza --tree --color {} | head -200'
    #       # fzf --preview 'eza --tree --color=always {} | head -200' "$@"
    #       ;;
    #     lt) # llt **<TAB>
    #       fd --type d --hidden | fzf --preview 'eza --tree --color=always {} | head -200' "$@"
    #       ;;
    #     v | vi | vim | nvim | open)
    #       fzf "$@" --preview 'bat --color=always --style=numbers --line-range :500 {}'
    #       ;;
    #     export | unset)
    #       fzf --preview "eval 'echo \$'{}" "$@"
    #       ;;
    #     *)
    #       fzf --preview 'fzf-preview-file {}' "$@"
    #       ;;
    #   esac
    # }

    # fzf_bind {{{2
    _execute_command() {
      zmodload -Fa zsh/zleparameter p:widgets
      # selected=$(printf '%s\n' "$(zle -al)" \
      selected=$(zle -al \
        | fzf-tmux --reverse --prompt='cmd> ' --height=10 --border=none)
      zle redisplay
      [ -n "${selected}" ] && zle "${selected}"
    }
    zle -N _execute_command
    # bindkey '\ex' _execute_command
    bindkey -M vicmd ':' _execute_command
    bindkey -M viins 'x' _execute_command
    if is-tmux; then
      bindkey -s '\C-xu' 'turls\n'
    fi
    # bindkey -s '^Xx' ',se\n'
    bindkey -s '^X.' 'si^M'
    bindkey -s '^[e' 've^M'
    # bindkey -s '^[E' 'edi^M'
    # bindkey -s '^[g' 'Rg^M'
    bindkey -s '^[g' 'rfv^M'
  fi
  # }}}1
  # z: https://github.com/rupa/z {{{
  if [ -r "${HOME%/}"'/repo/bin/z.sh' ]; then
    case "$(uname)" in
      Darwin) _Z_EXCLUDE_DIRS='/private' ;;
      *) _Z_EXCLUDE_DIRS='/tmp' ;;
    esac
    _Z_DATA="${XDG_DATA_HOME-}/z"
    # shellcheck source=/dev/null
    . "${HOME%/}"'/repo/bin/z.sh'
    unalias z 2>/dev/null
    z() {
      [ $# -gt 0 ] && _z "$*" && return
      dir=$(
        _z -l 2>&1 \
          | fzf --height 40% --reverse --inline-info -n 2.. --tac --no-sort \
            --query "${*:-}" | sed 's/^[0-9,.]* *//'
      ) && cd "${dir}" || return
    }
    # ctrl-g: complete the current word with z
    _bind_z() {
      # shellcheck disable=SC2250
      res=$(
        z-history | fzf --tac --reverse --height 40% --prompt 'z> ' \
          | sed "s|^~/|$HOME/|"
      )
      if [ -n "${res}" ]; then
        if [ -n "${LBUFFER}" ]; then
          # LBUFFER="${LBUFFER}${(q)res} "
          LBUFFER="${LBUFFER}$(res | sed 's/ /\\ /g') "
        else
          res=$(printf '%b' "${res}")
          cd "${res}" || return
        fi
      fi
      zle reset-prompt
    }
    zle -N _bind_z
    bindkey '^g' _bind_z
    # bindkey '^[z' _bind_z
  fi
# }}}
fi

# complete on tab, leave expansion to _expand
# bindkey '^I' complete-word
bindkey '^I' complete-word

# https://github.com/sigoden/aichat/blob/main/scripts/shell-integration/integration.zsh
_aichat_zsh() {
  if [ -n "${BUFFER}" ]; then
    _old=${BUFFER}
    # BUFFER+="⌛"
    BUFFER="${BUFFER}⌛"
    zle -I && zle redisplay
    BUFFER=$(aichat -e "${_old}")
    zle end-of-line
  fi
}
zle -N _aichat_zsh
# original: bindkey '\ee' _aichat_zsh
bindkey -M viins '^[o' _aichat_zsh

# tmux
# __is_available() {
#   prog="${1}"
#   os="${2}"
#   if [ "${os}" != "" ] && [ "${os}" != "${OS}" ]; then
#     return 1
#   fi
#   type "${prog}" >/dev/null
#   return "$?"
# }
# __is_available tmux linux true \
#   && [ -n "${SSH_CONNECTION}" ] \
#   && [ -z "${TMUX}" ] \
#   && [ "${USER}" != "root" ] \
#   && tmux new-session -A -s ssh && exit

# execute tmux if available and if we have some configuration for it
# [ -t 1 ] && command -v tmux >/dev/null && [ -f ~/.config/tmux/tmux.conf ] \
#   && ${PPID} != 1 \
#   && $$ != 1 \
#   && "${TERM-}" != dumb \
#   && "${TERM-}" != linux \
#   && "${TERM-}" != screen* \
#   && [ -z "${TMUX-}" ] \
#   && exec tmux

# direnv
# shellcheck disable=SC2312
# command -v direnv >/dev/null 2>&1 \
#   && eval "$(direnv hook zsh)"

## shell options
export set_hyphen="${--}" \
  && set_o="$(set +o)" \
  && export set_o

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

# export ENV_ZSHRC=$((ENV_ZSHRC+1))

# finish profiling by calling zprof.
# [ "${ZPROFRC-}" -eq 1 ] && zprof
# [ -n "${ZPROFRC+x}" ] && unset -- ZPROFRC
#unsetopt XTRACE
#exec 2>&3 3>&-

true
# ensure good return code
