Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full screen terminal application with ruby (or other languages)

Have you ever used cli tools like vim or htop? All these will maximize inside the terminal and have no scrollback but when you exit, they disappear and you can see what you typed in before.

Example:

terminal window with scrollback (terminal window with scrollback)

maximized vim without scrollback

(maximized vim without scrollback)

back in shell with scrollback and vim gone

(back in shell with scrollback and vim gone)

How can I do this in my own application, preferably ruby?

like image 258
x3ro Avatar asked Sep 15 '13 10:09

x3ro


1 Answers

This is a mode supported by most terminals through the XTerm control sequence specifications.

The specific screen-switching mode that can be activated using those specs is called the alternate screen buffer.

When you send the correct XTerm control sequence to the terminal then the terminal will switch into an alternate screen buffer. Once whatever program exits, it usually sends the commands to switch back to the original screen buffer. This way you get the effect of the application restoring your original terminal display.

The sequence for activating the alternate buffer is CSI ? 47 h. CSI stands for Control Sequence Initiator, and it's usually ESC + [. So by sending ESC [ ? 47 h (without spaces) to the terminal it will switch to the alternate buffer.

You can test this by running the cat command in your shell, hitting ESC and typing [?47h and hitting enter. You should see the screen clear (or switch to the other buffer).

The sequence to switch back to the normal screen buffer is CSI ? 47 l, and you can test this the same way running the cat command and typing the keys ESC [ ? 47 l and hitting enter.

When programming complex terminal screen-based applications however, most people tend to use a library like curses or ncurses, which will take care of all the terminal handling stuff for you. See these for example:

Learning Ruby Curses
http://www.ruby-doc.org/stdlib-2.0.0/libdoc/curses/rdoc/Curses.html

I suspect a program like htop probably uses curses or ncurses too.

like image 166
Casper Avatar answered Nov 15 '22 22:11

Casper