views:

789

answers:

9

How do some programs edit whats being displayed on the terminal (to pick a random example, the program 'sl')? I'm thinking of the Linux terminal here, it may happen in other OS's too, I don't know. I've always thought once some text was displayed, it stayed there. How do you change it without redrawing the entire screen?

+1  A: 

There are characters that can be sent to the terminal that move the cursor back. Then text can be overwritten.

There is a list here. Note the "move cursor something" lines.

Corporal Touchy
+2  A: 

If you terminate a line sent to the terminal with a carriage return ('\r') instead of a linefeed ('\n'), it will move the cursor to the beginning of the current line, allowing the program to print more text over top of what it printed before. I use this occasionally for progress messages for long tasks.

If you ever need to do more terminal editing than that, use ncurses or a variant thereof.

deemer
A: 

To build on @Corporal Touchy's answer, there are libraries available that will handle some of this functionality for you such as curses/ncurses

pix0r
+3  A: 

try this shellscript

#!/bin/bash
i=1
while [ true ]
    do
            echo -e -n "\r $i"
            i=$((i+1))
    done

the -n options prevents the newline ... and the \r does the carriage return ... you write again and again into the same line - no scroling or what so ever

mana
+1  A: 

Corporal Touchy has answered how this is done at the lowest level. For easier development the curses library gives a higher level of control than simply sending characters to the terminal.

danio
+2  A: 

Many applications make use of the curses library, or some language binding to it.

For rewriting on a single line, such as updating progress information, the special character "carriage return", often specified by the escape sequence "\r", can return the cursor to the start of the current line allowing subsequent output to overwrite what was previously written there.

fd
+1  A: 

NCurses is a cross-platform library that lets you draw user interfaces on smart terminals.

Jacob
A: 

I agree with danio, ncurses is the way to go. Here's a good tutorial:

http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/

Adam Pierce
+2  A: 

Depending on the terminal you send control seuqences. Common sequences are for example esc[;H to send the cursor to a specific position (e.g. on Ansi, Xterm, Linux, VT100). However, this will vary with the type or terminal the user has ... curses (in conjunction with the terminfo files) will wrap that information for you.

Shimodax