How to use ESC sequences to make terminal region scrollable

ansi-termescape-charactersterminal

I have a stm32f1 controlled device that uses USART/USB port to implement a user control interface. Using a standard terminal software (putty/minicom) a user has an ability to enter simple command in device shell.

There is a problem. In case of many incoming info packets, they print over shell prompt making entering new commands hard.

I plan to split a terminal screen on two areas: a one line prompt and a scrollable area for incoming packets.

I have tried to use the following escape sequence:

162 72 r * DECSTBM - Set top and bottom margins (scroll region on VT100)
        [4;20r = Set top margin at line 4 and bottom at line 20

but still can not find a good tutorial which is described a right way that will help me to solve my problem.

Best Answer

Reading source code is helpful, but the suggested examples are complicated. Most useful programs like the one OP is asking about use escape sequences via termcap or curses interfaces. Doing it with curses would be much simpler. Here are the steps needed with termcap:

  • get the terminal description (including the cursor-movement, scrolling region, erase-line, index)
  • initialize the terminal to "cbreak" (semi-raw) mode to allow keeping the prompt on a single line.
  • move the cursor to the line where the prompt should be
  • erase the line
  • write the prompt
  • get the input command

Meanwhile (the reference to packets makes it appear that OP wants to display them concurrently with reading input)

  • move the cursor to the bottom line of the scrolling region
  • set the scrolling region
  • write a line of the package (ending with newline, or using the index escape sequence)
  • reset the scrolling region to its default (full-screen)
  • move the cursor back to the command-line, continue reading commands

Best practice does not attempt to use cursor-addressing outside the scrolling region, so there will be a lot of setting/resetting of the scrolling region, each time the program switches between the two sections of the screen.

Further reading: