fix(per-directory-history): save to both history files and only push stack in directory mode

The addhistory hook previously had two bugs when inc_append_history
or share_history was not set:

1. Commands were only saved to one history file (HISTFILE or per-dir)
   depending on when fc -AI was called, resulting in lost history.

2. fc -p was called unconditionally after every command, corrupting
   the zsh history stack even in global mode. This caused the per-dir
   hook to push a new history frame on every command, breaking the
   global history state.

Fix: always write both history files via fc -AI before any mode
check, and only call fc -p (to push into per-directory history)
when actually in directory mode.
This commit is contained in:
Codebuff Contributor 2026-05-16 09:00:35 +06:00
commit 99486342e5

View file

@ -121,14 +121,22 @@ function _per-directory-history-addhistory() {
true
else
print -Sr -- "${1%%$'\n'}"
# instantly write history if set options require it.
# always write to both history files so history is always
# preserved regardless of which mode the user is in.
fc -AI $HISTFILE
fc -AI $_per_directory_history_directory
if [[ -o share_history ]] || \
[[ -o inc_append_history ]] || \
[[ -o inc_append_history_time ]]; then
fc -AI $HISTFILE
fc -AI $_per_directory_history_directory
: # already saved via fc -AI above
fi
# When in directory mode, push the current history stack so
# subsequent searches use the per-directory history file.
# In global mode, skip the push so the global history remains
# active — the command was already saved to both files above.
if [[ $_per_directory_history_is_global == false ]]; then
fc -p $_per_directory_history_directory
fi
fc -p $_per_directory_history_directory
fi
}