Skip to content

Instantly share code, notes, and snippets.

@laggardkernel
Created September 10, 2020 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laggardkernel/f319b1baf1065e5d990f11616a1d02b0 to your computer and use it in GitHub Desktop.
Save laggardkernel/f319b1baf1065e5d990f11616a1d02b0 to your computer and use it in GitHub Desktop.
Clear Scrollback Buffer #zsh #bash #shell

Clear Scrollback Buffer

Crtl + L doesn't ensure scrollback buffer is cleared.

# https://unix.stackexchange.com/a/531178/246718

# Common function
function clear-scrollback {
  # https://invisible-island.net/ncurses/man/clear.1.html
  # https://unix.stackexchange.com/a/375784/246718
  # Behavior of clear: 
  # 1. clear scrollback if E3 cap is supported (terminal, platform specific)
  # 2. then clear visible screen
  # For some terminal 'e[3J' need to be sent explicitly to clear scrollback
  # printf '\e[3J' && clear  # scrollback is kept by `clear`
  clear && printf '\e[3J'
}

# Shell specific keybinding

if [[ -n $BASH_VERSION ]]; then
# no -x to re-render prompt
bind '"\e\C-l":"clear-scrollback\n"'
# readline func clear-screen doesn't provide empty line before multiline prompt
# run /usr/bin/clear instead
bind '"\C-l":"clear\n"'
fi

if [[ -n $ZSH_VERSION ]]; then
function clear-scrollback-widget {
  clear-scrollback
  # .reset-prompt: bypass the zsh-syntax-highlighting wrapper
  # https://github.com/sorin-ionescu/prezto/issues/1026
  # https://github.com/zsh-users/zsh-autosuggestions/issues/107#issuecomment-183824034
  # -R: redisplay the prompt to avoid old prompts being eaten up
  # https://github.com/Powerlevel9k/powerlevel9k/pull/1176#discussion_r299303453
  zle && zle .reset-prompt && zle -R
}

zle -N clear-scrollback-widget
bindkey '^[^L' clear-scrollback-widget
fi

Now Ctrl + Option + L ensures scrollback buffer is always cleared.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment