Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Perform history expansion on the current word only



> On 13/06/2023 14:14 Marlon Richert <marlon.richert@xxxxxxxxx> wrote:
> All built-in widgets that perform history expansion seem to perform it
> on the entire line. However, I would like to have keybinding that
> performs history expansion on the current word only. How do I make
> this happen?

This is !-history, right?  Someone may have sneakier ideas than I do, but
I don't think this can be done simply because the history mechanism itself
just reads through a line from left to right.

It's possible to write a widget that divides a line into shell
words and only applies history to that word, however.  It would get
a bit confused if you were trying to extract words from the current line,
but I suspect that isn't the point here.  match-words-by-style can
help with this --- it's documented in zshcontrib.

The second problem is that the only existing !-history expansion
functions, as you noted, expand the whole line, so we need to shrink
the line temporarily.

Somewhat to my surprise, the following initial go does in fact seem to
be in roughly the right area.  This is expanding strictly the word
*before* the cursor --- match-words-by-style is written to allow
the caller to be clever about context, hence the long array of
returned line portions, but I've skipped that here.

Save as a function, autoload, and "zle -N" as usual.

pws


emulate -L zsh
setopt extendedglob

autoload -Uz match-words-by-style

local curcontext=":zle:$WIDGET"
local -a matched_words

match-words-by-style

BUFFER="${matched_words[2]}"
zle expand-history
LBUFFER="${matched_words[1]}$BUFFER" RBUFFER="${matched_words[3,7]}"




Messages sorted by: Reverse Date, Date, Thread, Author