phuang07
phuang07

Reputation: 981

Terminal - clear half screen

I know that using cmd + K can clear the entire screen buffer. I am wondering is there a way to just clear half of the screen buffer?

Upvotes: 4

Views: 1358

Answers (2)

Libin Varghese
Libin Varghese

Reputation: 1740

Refering answer

# Get ceiling eg: 7/2 = 4
ceiling_divide() {
  ceiling_result=$((($1+$2-1)/$2))
}

clear_rows() {
  POS=$1
  # Insert Empty Rows to push & preserve the content of screen
  for i in {1..$((LINES-POS-1))}; echo
  # Move to POS, after clearing content from POS to end of screen
  tput cup $((POS-1)) 0
}

# Clear quarter
alias ptop='ceiling_divide $LINES 4; clear_rows $ceiling_result'
# Clear half
alias pmid='ceiling_divide $LINES 2; clear_rows $ceiling_result'
# Clear 3/4th
alias pdown='ceiling_divide $((3*LINES)) 4; clear_rows $ceiling_result'

Upvotes: 0

Thomas Dickey
Thomas Dickey

Reputation: 54583

cmd+K maps to the menu item for clearing the visible screen (the screen buffer). That does not include the scrollback (it is a similar question, but different).

iTerm2's preferences and menu do not show any direct way to clear half of the screen.

However, iTerm2 emulates (like Terminal.app) most of the VT100 control sequences. You could add a binding in your shell which (given a suitable key of your choice) tells the shell to echo a control sequence which clears from the current cursor position (a) until the beginning of the screen or (b) to the end of the screen. Since it honors the save/restore cursor controls, you could even make it clear exactly half of the screen if you know the size, e.g.,

  • save the cursor position
  • jump to the middle of the screen
  • clear (which half?) half of the screen
  • restore the cursor position

Since it would use your shell, I called that indirect.

As noted, Terminal.app implements most of the VT100 control sequences. In ncurses, the appropriate TERM would be nsterm which is known to provide the VT100-style save/restore cursor. You can use tput to extract the corresponding strings for sc, rc and cup from the terminal database. However (if you wanted to erase to the beginning of the screen), you would provide your own string, since that particular flavor is not part of termcap/terminfo.

You can find the relevant VT100 control sequences documented in XTerm Control Sequences:

ESC 7     Save Cursor (DECSC).
ESC 8     Restore Cursor (DECRC).

CSI Ps ; Ps H
          Cursor Position [row;column] (default = [1,1]) (CUP).

CSI Ps J  Erase in Display (ED).
            Ps = 0  -> Erase Below (default).
            Ps = 1  -> Erase Above.
            Ps = 2  -> Erase All.
            Ps = 3  -> Erase Saved Lines (xterm).

Upvotes: 2

Related Questions