4

In vim and many other text editors, you can scroll up the end of the file to the top of your screen while showing the rest of the lines as blank. But in terminal, by default, the end of line is fixed to the end of the terminal screen so your current line is always appearing at the bottom. How can I scroll up the current line while adding blank lines between the last line and the bottom of screen?

Thanks

1 Answer 1

6

The escape sequences \e[B and \e[A move the cursor down and up, respectively, constraining within the viewport. The escape sequences \eD (called "index") and \eM ("reverse index") move down and up too, but also scroll the viewport if necessary. (Note the lack of the [ character in the latter ones.)

I recommend you to print a couple of "index" characters, followed by the same number of "cursor up" (or "reverse index"). E.g.:

echo -ne '\eD\eD\eD\e[A\e[A\e[A'

moves the cursor down by 3 rows, scrolling the entire viewport if necessary, and then moves it back up. Effectively it makes sure that there are at least 3 empty lines at the bottom of the screen.

You can hook it up to your $PS1 (primary shell prompt), just make sure it's enclosed between \[ and \] so that the shell knows these characters do not horizontally advance the cursor, e.g.:

PS1='\[\eD\eD\eD\e[A\e[A\e[A\]prompt$ '

You can also choose to print it from $PROMPT_COMMAND, in which case if I remember correctly it needs to be enclosed between a 0x01 (^A) and a 0x02 (^B) byte.

Note: the shortcuts \e[3A and \e[3B move the cursor up/down by 3 rows (and obviously you can replace 3 by any number). The "index" and "reverse index" sequences don't have such shortcuts.

I'd leave it up to you as an exercise to programatically figure out your preferred number of rows based on the terminal's height.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .