[[ -n "${ZSH_VERSION:-}" ]] || return 0
[[ -o interactive ]] || return 0
: ${DIRGE_BIN:=dirge}
typeset -g _DIRGE_BIN="$DIRGE_BIN"
typeset -g _DIRGE_SESSION_ID=""
function _dirge_gen_id() {
if command -v uuidgen >/dev/null 2>&1; then
print -r -- "dirge-shell-$(uuidgen | tr 'A-Z' 'a-z')"
else
print -r -- "dirge-shell-${EPOCHSECONDS:-$(date +%s)}-$$-${RANDOM}"
fi
}
function _dirge_ensure_session() {
[[ -z "$_DIRGE_SESSION_ID" ]] && _DIRGE_SESSION_ID="$(_dirge_gen_id)"
}
function _dirge_new_session() {
_DIRGE_SESSION_ID="$(_dirge_gen_id)"
print -r -- "dirge: new session ${_DIRGE_SESSION_ID}"
}
function _dirge_send() {
local prompt="$1"
[[ -z "$prompt" ]] && return 0
_dirge_ensure_session
command "$_DIRGE_BIN" -p --session "$_DIRGE_SESSION_ID" -- "$prompt" </dev/tty >/dev/tty 2>&1
}
function _dirge_resume_tui() {
_dirge_ensure_session
command "$_DIRGE_BIN" --session "$_DIRGE_SESSION_ID" </dev/tty >/dev/tty 2>&1
}
function _dirge_plugin_help() {
print -r -- "dirge shell plugin — the ':' prefix"
print -r -- " :<prompt> send a prompt to dirge (headless, shares this shell's session)"
print -r -- " :new [p] start a fresh session (optionally send a first prompt)"
print -r -- " :resume open the full dirge TUI on this shell's session"
print -r -- " :help this help"
print -r --
print -r -- "session: ${_DIRGE_SESSION_ID:-<none yet>} binary: ${_DIRGE_BIN}"
}
function dirge-accept-line() {
emulate -L zsh
if [[ "$BUFFER" != :* ]]; then
zle accept-line
return
fi
local original="$BUFFER"
local rest="${BUFFER#:}" rest="${rest# }"
print -s -- "$original" BUFFER=""
zle -I
zle reset-prompt
print ""
local action="${rest%% *}" local args="${rest#"$action"}"
args="${args# }"
case "$action" in
new|n) _dirge_new_session; [[ -n "$args" ]] && _dirge_send "$args" ;;
resume|tui) _dirge_resume_tui ;;
help|"") _dirge_plugin_help ;;
*) _dirge_send "$rest" ;; esac
zle reset-prompt
}
zle -N dirge-accept-line
function _dirge_apply_keybindings() {
bindkey '^M' dirge-accept-line bindkey '^J' dirge-accept-line }
_dirge_apply_keybindings
typeset -ga zvm_after_init_commands
zvm_after_init_commands+=('_dirge_apply_keybindings')