How does vi restore terminal content after quitting it?

后端 未结 2 1965
名媛妹妹
名媛妹妹 2020-12-01 18:55

How does a program like vi or man or any other program replace the terminal content with the program\'s own contents then after quitting those programs they bring back the o

相关标签:
2条回答
  • 2020-12-01 19:47

    Vi flips to the alternate screen buffer, supported by terminals. This is achieved using escape sequences. See this link for full details.

    The termcap entry for these are 'ti' to enter, and 'te' to exit full-screen mode.

    As @Celada points out below, hardcoding xterm escape sequences is not a Good Idea™, because the sequences vary according to $TERM, for example:

    xterm-color
      ti: <Esc> 7 <Esc> [ ? 47 h
      te: <Esc> [ 2 J <Esc> [ ? 4 7 l <Esc> 8
    
    xterm-256color
      ti: <Esc> [ ? 1 0 4 9 h
      te: <Esc> [ ? 1 0 4 9 l
    

    On the other hand, xterm support is very broad these days among non-xterm terminals. Supporting only xterm is unlikely to cause problems, except for users with exotic or obsolete $TERM settings. Source: I support products that do this.

    0 讨论(0)
  • 2020-12-01 19:48

    By sending control sequences to the terminal (xterm, vt-220) or using ncurses (like mc).

    A ANSI Escape Sequence starts with ESC (\033 octal) [. ; separates Numbers.

    C Example that clears the Screen and moves the cursor to 1,1.

    #include <stdio.h>
    
    int main()
    {
        // clear the terminal
        printf("\033[2J\033[1;1H");
        printf("hello");
    
    }
    

    Example of switchting to alternate Buffer and back (xterm).

    #include <stdio.h>
    #include <unistd.h>
    
    int main()
    {
        printf("\033[?1049h\033[H");
        printf("hello\n");
        sleep(1);
        printf("bye");
        sleep(1);
        printf("\033[?1049l");
    }
    
    0 讨论(0)
提交回复
热议问题