Zsh keybinding: ignore given command in insert-last-word

keyboard shortcutszsh

In zsh, I have alt+. bound to insert-last-word.

When I press alt+., I can list through the last word of previous commands.

How can I exclude some words from being shown when I cycle through ?

ie, if this is my history:

echo
foo
ls

and I want to ignore foo, then alt+. should skip foo.

Best Answer

I’ve tested this and it works:

setopt EXTENDED_GLOB
bindkey '^[.' insert-last-word
autoload smart-insert-last-word
zle -N insert-last-word smart-insert-last-word
zstyle :insert-last-word match '*~(*last*|match)'

What this does:

  1. Replaces insert-last-word implementation with the function smart-insert-last-word, which is distributed with Zsh, but not loaded by default.
  2. Says that we want our new insert-last-word widget to match any word (*), but not any word that contains the word last or the literal word match.
  3. EXTENDED_GLOB is required to be able to use the ~ ("but not") operator.

Of course, it's up to you to replace that pattern in the last line with something that excludes all the words or patterns that you never want to be inserted. ?

Related Question