# Liho shell integration for zsh — the file that installs the marks.
#
# See bash.sh for what the sequences mean. zsh is reached through ZDOTDIR
# rather than an rc-file argument, which it has none of: the editor points
# ZDOTDIR at a directory of its own, and each file there reads the person's
# counterpart before adding anything.

# The person's own configuration first: a shell opened from the editor must
# behave like every other shell on the machine.
__liho_integration_zdotdir="$ZDOTDIR"
ZDOTDIR="${LIHO_USER_ZDOTDIR:-$HOME}"
if [[ -f "$ZDOTDIR/.zshrc" ]]; then
  source "$ZDOTDIR/.zshrc"
fi
LIHO_USER_ZDOTDIR="${ZDOTDIR:-$HOME}"
export LIHO_USER_ZDOTDIR

# History belongs to the person, not to the directory we were read from.
#
# macOS ships /etc/zshrc with `HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history`, and it
# runs one file before this one — while ZDOTDIR is still ours. Left alone, every
# command typed in the editor's terminal would be saved beside our scripts
# instead of in the person's own history, and would disappear with that
# directory. A path they chose themselves is never touched: only one that points
# inside our directory moves back to theirs.
if [[ -n "${HISTFILE-}" && "$HISTFILE" == "$__liho_integration_zdotdir"/* ]]; then
  HISTFILE="${LIHO_USER_ZDOTDIR:-$HOME}/${HISTFILE:t}"
fi

autoload -Uz add-zsh-hook 2>/dev/null

# The last in-memory history event at a prompt, and the line that occupied it.
# Both are needed to tell whether the shell kept the next command: zsh reuses an
# event number, so the number alone does not say (see __liho_preexec).
typeset -gi __liho_history_event=0
typeset -g __liho_history_event_line=
typeset -g __liho_history_hook_command=
typeset -g __liho_history_hook_decision=

# Preserve history policy installed by the user's .zshrc, but route it through
# one dispatcher so its first non-zero result can be projected without calling
# any hook twice. Status 2 is zsh's native memory-only contract; other non-zero
# statuses mean do not store. The direct special function runs before the hook
# array in native zsh, so keep that order here as well.
typeset -ga __liho_user_zshaddhistory_functions
__liho_user_zshaddhistory_functions=()
if (( $+functions[zshaddhistory] )); then
  functions[__liho_user_zshaddhistory_direct]="${functions[zshaddhistory]}"
  unfunction zshaddhistory
  __liho_user_zshaddhistory_functions+=(__liho_user_zshaddhistory_direct)
fi
if (( ${+zshaddhistory_functions} )); then
  __liho_user_zshaddhistory_functions+=("${zshaddhistory_functions[@]}")
fi

__liho_capture_zshaddhistory() {
  local __liho_hook __liho_status
  __liho_history_hook_command="${1%$'\n'}"
  __liho_history_hook_decision=persist
  for __liho_hook in "${__liho_user_zshaddhistory_functions[@]}"; do
    "$__liho_hook" "$@"
    __liho_status=$?
    if (( __liho_status != 0 )); then
      if (( __liho_status == 2 )); then
        __liho_history_hook_decision=private
      else
        __liho_history_hook_decision=skip
      fi
      return $__liho_status
    fi
  done
  return 0
}
zshaddhistory_functions=(__liho_capture_zshaddhistory)

__liho_capture_precmd() {
  # Before anything else in this function: $? still belongs to the command that
  # has just finished.
  __liho_exit_code=$?
  __liho_control_event finish "$__liho_exit_code"
  return $__liho_exit_code
}

__liho_precmd() {
  __liho_control_event cwd "$PWD"
  __liho_control_event prompt-start
  local previous_suffix="${__liho_prompt_ready_suffix-}"
  if [[ -n "$previous_suffix" && "$PS1" == *"$previous_suffix" ]]; then
    PS1="${PS1%$previous_suffix}"
  fi
  local ready_marker="$(__liho_control_event prompt-ready)"
  __liho_prompt_ready_suffix="%{${ready_marker}%}"
  PS1="${PS1}${__liho_prompt_ready_suffix}"
  __liho_history_event=$(( HISTCMD - 1 ))
  __liho_history_event_line="${history[$__liho_history_event]-}"
  return $__liho_exit_code
}

__liho_preexec() {
  # $1 is the line as the person typed it, before alias and history expansion —
  # which is the line worth showing back to them.
  local __liho_command="$1"
  local __liho_history_decision=skip
  # zsh exposes the event after built-in history options have run. A leading
  # space under HIST_IGNORE_SPACE is deliberately private.
  if [[ "$__liho_history_hook_command" == "$__liho_command"
      && "$__liho_history_hook_decision" == (private|skip) ]]; then
    __liho_history_decision="$__liho_history_hook_decision"
  elif [[ -o HIST_IGNORE_SPACE && "$__liho_command" == [[:space:]]* ]]; then
    __liho_history_decision=skip
  elif [[ "${history[$HISTCMD]-}" == "$__liho_command" ]]; then
    # The line is in the list, and the question is whether the shell put it
    # there. A number past the one the prompt saw means it did. So does the same
    # number holding a different line than it held at the prompt: a command a
    # hook refused stays in the list until the next one arrives, and that next
    # one is given the refused command's number. Comparing numbers alone read
    # that as «not kept» and reported an ordinary command as skipped — every
    # command typed after one the shell refused to keep.
    #
    # Only an identical line already sitting at that number means nothing new
    # was kept, which is HIST_IGNORE_DUPS doing its work.
    if (( HISTCMD > __liho_history_event )) || [[ "$__liho_history_event_line" != "$__liho_command" ]]; then
      __liho_history_decision=persist
    fi
  fi
  __liho_history_hook_command=
  __liho_history_hook_decision=
  __liho_command="${__liho_command//$'\n'/ }"
  __liho_command="${__liho_command//$'\r'/ }"
  __liho_control_event preexec "$__liho_history_decision" zsh-history "$__liho_command"
}

if (( $+functions[add-zsh-hook] )); then
  add-zsh-hook precmd __liho_capture_precmd
  add-zsh-hook precmd __liho_precmd
  add-zsh-hook preexec __liho_preexec
else
  # A zsh too old for add-zsh-hook still has the hook functions themselves.
  precmd_functions+=(__liho_capture_precmd __liho_precmd)
  preexec_functions+=(__liho_preexec)
fi
# add-zsh-hook appends. Put protocol boundaries before user hooks so their own
# output and status-changing work cannot be mistaken for command output.
precmd_functions=(__liho_capture_precmd ${precmd_functions:#__liho_capture_precmd})
precmd_functions=(${precmd_functions:#__liho_precmd} __liho_precmd)
preexec_functions=(__liho_preexec ${preexec_functions:#__liho_preexec})

# Handed back so anything that reads ZDOTDIR during the session — a plugin
# manager, a nested shell — sees the person's directory and not ours.
if [[ -n "${LIHO_USER_ZDOTDIR-}" ]]; then
  ZDOTDIR="$LIHO_USER_ZDOTDIR"
else
  unset ZDOTDIR
fi
unset __liho_integration_zdotdir
