Reverse scrolling through the last argument of command in zsh?

When I want to see the last argument of a command in zsh, I can just press Alt+. However, sometimes I press it too much, and I would prefer to scroll back, like I can in fish with the keyboard shortcuts Alt+Up and Alt+Down. How can I do that in zsh?


Solution 1:

# Create a function.
insert-next-word() { 
  # Tell `insert-last-word` to go forward (1), instead of backward (-1).
  zle insert-last-word -- 1 
}

# Create a widget that calls the function above.
zle -N insert-next-word

# Bind this widget to a keyboard shortcut.
bindkey '^[;' insert-next-word

Now, after you've pressed alt. one or more times, you can then press alt; to cycle in the opposite direction.

Documentation: http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#index-insert_002dlast_002dword

If you want, you can bind these commands to alt and alt instead:

# alt-↑
bindkey '^[^[OA' insert-last-word
bindkey '^[^[[A' insert-last-word

# alt-↓
bindkey '^[^[OB' insert-next-word
bindkey '^[^[[B' insert-next-word

In the key codes above, whether the second to last character should be O or [ depends on how you've set up your terminal, but it doesn't hurt to bind both.

If neither version of the codes above work for you, then press ctrlV, followed by the key combo you want to use, to see what key code your terminal actually outputs.