Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Program taking control of terminal window

When using vim in the terminal, it essentially blanks out the terminal's window and gives you a new one to start coding in, yet when you exit vim the terminal's previous output is still listed. How do you clear the terminal so that it only outputs your program's output, but returns to its normal state once the process has ended? (In linux, fedora)

like image 286
kjh Avatar asked Dec 27 '22 16:12

kjh


1 Answers

At the low level, you send the terminal program a set of control characters that tell it what to do. This can be a bit too complex to to manage manually.

So instead, you might want to look at a console library like ncurses, which can manage all this complexity for you.

With respect specifically to the previous content magically appearing after the program exits, that's actually an xterm feature which vim is taking advantage of and which most modern terminals support. It's called "alternate screen" or simply "altscreen". Essentially you tell the terminal program "Ok, now switch to a completely new screen, we'll come back to the other one later".

The command to switch to the alternate screen is typically \E[?47h, while the command to switch back is \E[?47l For fun try this:

echo -e "\033[?47h"

and then to switch back:

echo -e "\033[?47l"

Or for a more more complete solution which relies a bit less on your shell to set things right (these are the sequences vim normally uses):

echo -e "\0337\033[?47h" # Save cursor position & switch to alternate screen
# do whatever

#Clear alternate screen, switch back to primary, restore cursor
echo -e "\033[2J\033[?47l\0338" 
like image 52
tylerl Avatar answered Jan 05 '23 16:01

tylerl