To automatically open output in a pager when it exceeds the screen height in Zsh, you can use a shell function that wraps commands and pipes their output to a pager if necessary. Here’s how you can implement this:
- Add the following function to your
.zshrc
file:
auto_pager() {
local cmd="$1"
shift
$cmd "$@" | {
if [ $(tput lines) -lt $(/usr/bin/env wc -l) ]; then
$PAGER
else
cat
fi
}
}
- Create aliases for commands you want to automatically page:
alias ls='auto_pager ls'
alias grep='auto_pager grep'
alias tree='auto_pager tree'
# Add more aliases as needed
This solution works as follows:
- The
auto_pager
function takes a command and its arguments. - It runs the command and pipes its output to a subshell.
- Inside the subshell, it compares the number of lines in the output to the terminal height.
- If the output exceeds the terminal height, it uses the pager defined in the
$PAGER
environment variable (usuallyless
). - If the output fits within the terminal, it simply uses
cat
to display it.
To ensure the pager behaves correctly, you can set the following options in your .zshrc
:
export LESS="-FXR"
This configures less
to:
- Exit if the entire file fits on one screen (-F)
- Not clear the screen when exiting (-X)
- Display ANSI colors (-R)
By using this approach, you can automatically page output that exceeds the screen height while still displaying shorter output directly[1][2]. Remember to restart your Zsh session or source your .zshrc
file after making these changes.
Citations: [1] https://stackoverflow.com/questions/15453394/would-it-be-possible-to-automatically-page-the-output-in-zsh/15488779 [2] https://www.reddit.com/r/bash/comments/jbcp5x/how_to_automatically_display_the_output_in_a/ [3] https://github.com/ohmyzsh/ohmyzsh/issues/3016 [4] https://github.com/sharkdp/bat/issues/749