I would like to know what a command would look like if I entered a substring of this command. I'm not interested in the result, but in the history expansion.

The purpose of this is to show in an interactive way, how the expansion works in zsh.

For example, let's say I want to illustrate the usage of zsh history modifiers:

mv /Volumes/hdd1/path/to/a/file.foo !#$:r:s/foo/bar/ # moves and renames at the same time

(The line above is a rule for referencing substrings in this question)

Some of the substrings are valid, some are not.

I would like for each substring ending at [0..f], to execute the history expansion, as if I typed TAB after each character in [0..f].


I don't think you can get trigger a history expansion and get back the result from within zsh.

Here's a proof-of-concept to use the zpty module to interact with an inferior zsh process, have it expand history strings and study the outcome (which could be to report an error or execute a command). Put the initial history that you want before each expansion attempt in a file called prior_history.

setopt extended_glob
zmodload zsh/zpty
zpty -b inferior_zsh 'PS1=%% PS2=\> TERM=dumb strace -eread,write -o zsh.strace zsh -f'
zpty -r inferior_zsh out $'*\r%'
zpty -w inferior_zsh 'stty -echo'
zpty -r inferior_zsh out $'*\r%'
start='mv /Volumes/hdd1/path/to/a/file.foo'
for ((i=1; i <= $#history_string; i++)) {
  zpty -w inferior_zsh "fc -R prior_history"
  zpty -r inferior_zsh out $'*\r%'
  zpty -w inferior_zsh "print -r expansion: ${(q)start} ${history_string[1,$i]}"
  zpty -r inferior_zsh out $'*\r[%>]'
  out=${${out#*$'\r\r\n'}%$'\r\n'% ##$'\r\r%'}
  print -r "$i ${(qqqq)out}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.