Saving current directory to zsh history
Question
I wanted to achieve the same as asked here Saving current directory to bash history but within zsh shell. I haven't done any zsh trickry before but so far I have:
function precmd {
hpwd=$history[$((HISTCMD-1))]
if [[ $hpwd == "cd" ]]; then
cwd=$OLDPWD
else
cwd=$PWD
fi
hpwd="${hpwd% ### *} ### $cwd"
echo "$hpwd" >>~/.hist_log
}
Right now I save the command annotated with the directory name to a log file. This works fine for me. Just thought there might be a way to make replacement in the history buffer itself.
Solution
function _-accept-line() {
[[ -z "${BUFFER" ]] || [[ "${BUFFER}" =~ "### ${(q)PWD}\$" ]] || BUFFER="${BUFFER} ### ${PWD}"
zle .accept-line
}
zle -N accept-line _-accept-line
Will add ### ${PWD}
to your command line. Not the best solution you could use, but it works.
UPD: Answer based on @Dennis Williamson's comment:
function zshaddhistory() {
print -sr "${1%%$'\n'} ### ${PWD}"
fc -p
}
OTHER TIPS
Rather than store it on every command I added the following to the beginging of my precmd() function to store it when I change directories:
if [ "$LAST_DIR" != "$PWD" ]
then
print -s "##dir## $PWD"
LAST_DIR=$PWD
fi
Adds a '##dir## dir name' standalone line to the history each time a command is run from a new directory.