Search code examples
c++cterminalinteractive

Writing a "real" interactive terminal program like vim, htop, ... in C/C++ without ncurses


No, I don't want to use ncurses, because I want to learn how the terminal works and have fun programming it on my own. :) It doesn't have to be portable, it has to work on linux xterm-based terminal emulators only.

What I want to do is programming an interactive terminal application like htop and vim are. What I mean is not the output of characters which look like boxes or setting colors, this is trivial; also to make the content fit to the window size. What I need is

  1. how to get mouse interactions like clicking on a character and scrolling the mouse wheel (when the mouse is at a specific character) to implement scrolling [EDIT: in a terminal emulator of course], and

  2. how to completely save and restore the output of the parent process and seperate my printing from its output, so after leaving my application nothing but the command I entered in the shell should be there, like when running htop and quitting it again: nothing is visible from this application anymore.

I really don't want to use ncurses. But of course, if you know which part of ncurses is responsible for these tasks, you're welcome to tell me where in the source code I can find it, so I will study it.


Solution

  • I'm a bit confused. You speak of a “terminal application”, like vim; terminal applications don't get mouse events, and don't respond to the mouse.

    If you're talking about real terminal applications, which run in an xterm, the important thing to note is that many of the portability issues concern the terminal, and not the OS. The terminal is controlled by sending different escape sequences. Which ones do what depend on the terminal; the ANSI escape codes are now fairly widespread, however, see http://en.wikipedia.org/wiki/ANSI_escape_code. These are generally understood by xterm, for example.

    You may have to output an additional sequence at the start and at the end to enter and leave “full screen” mode; this is necessary for xterm.

    Finally, you'll have to do something special at the input/output level to ensure that your output driver doesn't add any characters (e.g. convert a simple LF into a CRLF), and ensure that input doesn't echo, is transparent, and returns immediately. Under Linux, this is done using ioctl. (Again, don't forget to restore it when you finish.)