Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can certain programs set background and font colors, write characters to the same location on screen (e.g. to the third row, fifth column) more than once?

Some examples are the progress bar displayed by curl google.com > a, some installation screens and nearly any text editor.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

What you're asking about isn't really a graphics API, it's just terminal control characters.

There's a lot of history behind it, but terminals back in the day were Teletype machines. Basically a typewriter with track-fed paper connected to the computer with a serial connection. Typing a character would send that binary value to the computer (as well as type it on the page). The computer would print characters back as the output of whatever you requested.

Special characters were used for controlling the terminal (which is where the control key comes from, it was for producing those characters). For example, ^H or ^? would be a backspace. ^M is a carriage return (moves the cursor to the beginning of the line). ^J is a line feed (move the page up one line). Each control code has an escape sequence in C (which is shared by almost all programming languages) to generate the control characters. The controls listed previously would be \b, \r, \n respectively.

The terminal emulator you use today is just what that sounds like, it's software that is pretending to be an old teletype machine. In a way, it's almost as if Unix still thinks you're using a typewriter to communicate with it.

In the case of curl, it writes an entire line then sends \r (carriage return) taking the cursor to the beginning of the line then writes another line. Since a line feed isn't sent it keeps writing over the same line on the screen.

Here's something you can try to demonstrate this:

echo -n  "First" ; sleep 5 ; echo -en "\rSecond\n"

You will see the word "First" printed (but no new line is sent). 5 seconds later it will be replaced with the word "Second" and a new line is sent. You can repeat this pattern indefinitely. Try adding "Third" yourself, you'll see something that you probably didn't expect ;-)

For more information about these and other control characters see the ascii(7) manual.

share|improve this answer
add comment

Are you looking for something like curses?

share|improve this answer
1  
These days, you'll want the new curses, or ncurses. –  Steven Monday Jul 5 '12 at 19:23
    
Exactly. Thanks for corrections. I forgot they different. –  Boris Ivanov Jul 6 '12 at 9:08
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.