Writing a “real” interactive terminal program like vim, htop, … in C/C++ without ncurses

前端 未结 3 385
一整个雨季
一整个雨季 2021-01-30 02:34

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 t

3条回答
  •  孤独总比滥情好
    2021-01-30 02:56

    In order to manipulate the terminal you have to use control sequences. Unfortunately, those codes depend on the particular terminal you are using. That's why terminfo (previously termcap) exists in the first place.

    You don't say if you want to use terminfo or not. So:

    • If you will use terminfo, it will give you the correct control sequence for each action your terminal supports.
    • If you won't use terminfo... well, you have to manually code every action in every terminal type you want to support.

    As you want this for learning purposes, I'll elaborate in the second.

    You can discover the terminal type you are using from the environment variable $TERM. In linux the most usual are xterm for terminal emulators (XTerm, gnome-terminal, konsole), and linux for virtual terminals (those when X is not running).

    You can discover the control sequences easily with command tput. But as tput prints them on the console, they will apply immediately, so if you want to really see them, use:

    $ TERM=xterm tput clear | hd
    00000000  1b 5b 48 1b 5b 32 4a                              |.[H.[2J|
    
    $ TERM=linux tput clear | hd
    00000000  1b 5b 48 1b 5b 4a                                 |.[H.[J|
    

    That is, to clear the screen in a xterm you have to output ESC [ H ESC [ 2J in an xterm but ESC [ H ESC [ J in a linux terminal.

    About the particular commands you ask about, you should read carefully man 5 terminfo. There is a lot of information there.

提交回复
热议问题