Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one scroll through multi-line commands in the Zsh history without selecting each line of each command?

Tags:

zsh

If one runs the following commands in succession in Zsh (on macOS or Ubuntu):

date +%s
echo \
a\
b\
c

One can then scroll back to the first command by pressing the up-arrow 5 times.

Is there a way to scroll back to the first command with just 2 key presses (i.e. the first key press selects the echo command and the 2nd key press selects the date command)?

When the history contains several long multi-line commands, scrolling back through them with the up-arrow key is a pain.

I was hoping to find some Zsh key shortcuts that would scroll up and down through the command history without stopping en-route to edit multi-line commands, but I haven't yet managed to find any.

like image 773
David Avatar asked Sep 14 '25 09:09

David


1 Answers

Add the following to your .zshrc file:

bindkey '^P' up-history
bindkey '^N' down-history

Now you can press ControlP to go up in history and ControlN to go down in history, regardless of how many lines the current editing buffer has or which line you are on.

If you don't mind adding a bit more code, then you can bind these to Alt/EscapeUp and Alt/EscapeDown, too:

() {
  local -a prefix=( '^['{\[,O} )
  local -a key_up=(   ${^prefix}A )
  local -a key_down=( ${^prefix}B )
  local -a key_alt_up=(   '^['$^key_up   '^[[1;3A' )
  local -a key_alt_down=( '^['$^key_down '^[[1;3B' )
  local widget

  widget=up-history
  bindkey "${(@)key_alt_up:^^up-history}"

  widget=down-history
  bindkey "${(@)key_alt_down:^^down-history}"
}

For more history widgets, see https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#History-Control


Alternatively, my zsh-autocomplete plugin contains a history menu that lets you step up and down through history items with the arrow keys.

like image 87
Marlon Richert Avatar answered Sep 17 '25 20:09

Marlon Richert