ANSI escape sequences: save and restore a row position
Asked Answered
U

1

6

I'm writing a very simple little console application and I'm playing around with some ANSI escape sequences to get some nicer output.

What I'm trying to do is something like this. There's a header with a name, and then underneath, as the program runs, several lines are printed. As each line is printed, I'd like to update the header row with a progress meter. eg:

My header row                 [ 0/5 ]
-------------------------------------

then after some processing

My header row                 [ 1/5 ]
-------------------------------------
here is some output

...

My header row                 [ 2/5 ]
-------------------------------------
here is some output
the output could
be over several
lines

I've tried using the save cursor position code (ESC + [s) and then restoring that position with ESC + [u, however that only restores the column, not the row.

for some background, this is a Node.JS program. I've looked at node-ncurses briefly, however it seems like a bit of overkill for this task(?)

Unwholesome answered 19/9, 2011 at 1:45 Comment(3)
Have you tried manually moving the cursor rather than using store/restore?Booted
@lordscarlet I can't remember now. I guess probably? I think the issue may have been that I didn't know how many rows to move upwards, since the output could go across multiple lines.Unwholesome
I recommend always using ncurses or whatever the corresponding library is for your context. It isn’t overkill, it’s correct. :-) More importantly, it will save you a bunch of headaches trying to figure out what codes to use in what sequence to achieve a desired effect. And it’s portable. Never hard-code terminal control sequences unless you can’t avoid it—prefer to use terminfo via ncurses.Disarming
H
5

This is a problem arising when you are printing in the last row of the screen and it has to scroll down. The scroll of the text do not update the saved cursor position. You need to detect that some scroll happend (I don't know how) and take the corresponding action like send sequences moving the cursor up after the Esc[u sequence in order to go to the original position.

Bye.-

Hachure answered 15/3, 2012 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.