~/blog/terminal/02-escape-sequences.md

Escape Sequences [Part 1]

2026-11-25#terminal#libterm#c22 min read


In the previous part, we saw that applications communicate with a terminal by writing a stream of bytes, and that 0x1B introduces instructions the terminal emulator interprets. In this part, we look closely at how those escape sequences work. We will trace how the terminal tracks cursor position and parser state across a single byte stream, inspect the raw bytes from small C programs with xxd, see how \r and \n interact with the operating system’s terminal driver, and build a simple output buffer so we can measure both bytes sent and system calls made.

Cozy Escape Sequence Night Study

how a terminal reads your output

A terminal might display “Hi”, but the program produces that result by sending bytes. For example, “\x1b[1;1HHi” represents an escape sequence that moves the cursor to row 1, column 1, followed by the bytes for H and i. The terminal interprets those bytes, updates its internal state, and renders the result.

The important detail is that ordinary text and terminal instructions share the same stream. A program can send a word, a cursor movement, and another word through the same output connection. The terminal must distinguish them by examining the bytes themselves.

To understand how that works, we need to separate three things: the bytes a program sends, the state the terminal maintains, and the characters we see on the screen.

A byte is a number from 0 to 255. Writing that number in hexadecimal makes its bit pattern easier to recognize. For example, the ASCII letter H is 0x48, the letter i is 0x69, and the control character ESC is 0x1B, these are numerical values, whether a byte produces a visible character depends on how the terminal interprets it.

For our first examples, we will use ASCII text. In ASCII, each ordinary printable character fits in one byte. That lets us examine the stream without also having to explain how several bytes can encode one Unicode character.

Suppose a program sends these two bytes:

Hexadecimal:  48 69
ASCII:         H  i

The bytes do not contain a row or column. The terminal needs to know where to put them, so it maintains a cursor position. The cursor is the terminal’s current writing position. It has a row and a column, and it exists whether or not the terminal draws a visible cursor on the screen. Hiding the blinking cursor does not remove this position.

Assume the cursor starts at row 1, column 1. Also assume there is enough room before the right edge of the screen.

             Column
             1 2 3 4

Start        ▮ . . .
Read H       H ▮ . .
Read i       H i ▮ .

Here, ▮ represents the cursor and each dot represents an empty cell, after drawing H, the terminal advances the cursor. After drawing i, it advances again. The cursor now points at column 3. This means writing text has two effects, it changes the contents of the screen, and it changes where the next character will appear, it also means that writing does not necessarily insert anything, if a cell already contains a character, writing another character at that position normally replaces it. The surrounding text does not automatically move aside.

You can see this with carriage return:

$ printf 'ABCDE\rxy\r\n'
xyCDE # the result

The program first writes ABCDE. The \r produces a carriage return byte, 0x0D, which moves the cursor back to the beginning of the current line, then x and y replace the first two characters, the remaining CDE stays on the screen, moving the cursor did not erase it. The final \r\n returns to the beginning of the line and advances to the next line.

Carriage return is one example of a control character. ASCII reserves the values below 0x20 for control characters rather than ordinary printable text. Newline, tab, and ESC belong to this range. Their effects differ, and some may be ignored or affected by terminal settings.

So the first useful distinction is between printable text and control characters. But individual control bytes provide only a small set of actions. A terminal also needs a way to express instructions with parameters, such as “move to row 3, column 4.”

That is where escape sequences enter the picture.

ESC is the byte 0x1B, or decimal 27. When the terminal encounters it, it changes how it interprets the bytes that follow. Those bytes can form an escape sequence instead of appearing as text, one common sequence looks like this:

ESC [ 3 ; 4 H

The spaces above separate the parts for reading, they are not part of the sequence, the actual bytes are:

Hexadecimal:  1B 5B 33 3B 34 48
Meaning:     ESC [  3  ;  4  H

This sequence moves the cursor to row 3, column 4. The coordinates in this command start at 1.

Each part contributes to the instruction:

  • ESC [ introduces a Control Sequence Introducer, usually shortened to CSI.
  • 3 and 4 are numeric parameters written as ASCII digits.
  • ; separates the parameters.
  • H finishes the sequence and selects the cursor-position operation.

The parameter 3 is therefore the byte for the character 3, which is 0x33. It is not the numerical byte value 0x03, the terminal reads the digits and interprets them as a number. The final H also deserves attention. It has exactly the same byte value as the H in Hi. Its role changes because the terminal is interpreting a control sequence.

Outside the sequence, H is text to draw. Here, it completes an instruction. This is why the terminal must maintain parsing state as well as cursor state, it needs to remember whether it is reading ordinary text, has just encountered ESC, or is collecting the parameters of a control sequence.

For a CSI sequence, the terminal recognizes a final byte that completes the instruction. It does not wait for a newline, a space, or the end of a program’s write operation.

Consider this complete stream:

H i ESC [ 1 ; 1 H !

Starting at row 1, column 1, the terminal processes it like this:

Input consumed       Screen       Cursor position

H                    H            Row 1, column 2
Hi                   Hi           Row 1, column 3
Hi ESC[1;1H          Hi           Row 1, column 1
Hi ESC[1;1H !        !i           Row 1, column 2

The cursor-position command changes where the next character goes, it does not change the characters already displayed. Only when the terminal receives ! does it overwrite the H, you can try the same idea on the current line using a relative cursor movement:

$ printf 'Hi\033[2D!\r\n'
!i # result

Here, \033 tells printf to emit the ESC byte. The sequence ESC[2D moves the cursor two columns left. After writing Hi, that brings the cursor back over the H, where ! replaces it. The terminal does not receive the four literal characters \033. The shell passes the quoted format string to printf, and printf interprets that notation to produce one byte.

There is another boundary worth understanding: the boundaries between output operations do not define terminal commands.

A program might send ESC[2D in one write. It might send ESC first and [2D later. As long as the same bytes arrive in the same order, with no intervening bytes, the terminal can interpret the same sequence. It retains its parsing state while waiting for the rest.

A write is a way to deliver bytes. An escape sequence is a structure within those bytes. They are different things.

Anatomy of the CSI escape sequence ESC[3;4H and a step-by-step trace of H i ESC[1;1H ! showing parser state, cursor coordinates, and cell overwrite producing !i.

Finally, the ASCII examples have a deliberate limit. With UTF-8, one character can require several bytes. A displayed character may occupy one column, two columns, or combine with another character without advancing the cursor. Line wrapping introduces further rules at the right edge.

Those details build on the same foundation: the terminal interprets an ordered byte stream while maintaining state. Printable text affects the screen and usually advances the cursor. Control characters affect terminal behavior. ESC introduces sequences whose following bytes describe an instruction, what appears on the screen is the result of that interpretation, together with everything the terminal already remembers.

Watching a byte stream draw

An escape sequence is easier to understand when you can connect its bytes to a visible change. A small program can show both sides: what the terminal displays and the exact bytes that produce it.

The following C program clears the screen, writes Hi, and replaces the H with !, it then moves the cursor below the result so the shell prompt has somewhere to appear.

#include <stdio.h>

int main(void) {
    printf("\x1b[2J");
    printf("\x1b[1;1H");
    printf("Hi");
    printf("\x1b[1;1H");
    printf("!");
    printf("\x1b[3;1H");
    fflush(stdout);
    return 0;
}

With this code saved as ex1.c, compile and run it:

$ cc -std=c11 -Wall -o ex1 ex1.c
$ ./ex1
!i # result

To understand that result, follow the output in order.

The first sequence, ESC[2J, clears the screen. Clearing the screen and moving the cursor are separate operations, so the next sequence, ESC[1;1H, places the cursor at row 1, column 1.

The program then writes Hi. The terminal draws H in the first column and i in the second, after those two characters, the cursor sits at column 3.

The next ESC[1;1H returns the cursor to the first column. It does not erase anything. When ! arrives, the terminal draws it at that position, replacing the H. The i remains beside it.

Finally, ESC[3;1H moves the cursor to row 3, column 1. When the program exits, the shell can print its prompt there without covering the result on row 1.

Although the program makes several calls to printf, those calls do not become separate terminal messages. They contribute bytes to the same output stream. The terminal receives no marker saying where one printf ended and another began.

There is also a buffer between printf and the output destination. The C standard I/O library can hold output in memory before passing it onward. The call to fflush(stdout) explicitly passes any pending output from that buffer to the underlying destination.

Returning normally from main also flushes standard output, so the explicit flush is not required for this particular program to display its result. Including it makes the point at which the program releases its buffered output visible in the code.

A flush does not make the terminal display every intermediate screen state as a separate frame. You may see only the final !i. The terminal still interprets the bytes in order, but its drawing and your display’s refresh timing determine which intermediate states become visible.

To inspect the stream itself, run the program again with its output connected to xxd:

./ex1 | xxd

This time, the program’s bytes go through a pipe to the hex dump tool. They do not go directly to the terminal for interpretation.

The output should look like this:

00000000: 1b5b 324a 1b5b 313b 3148 4869 1b5b 313b  .[2J.[1;1HHi.[1;
00000010: 3148 211b 5b33 3b31 48                   1H!.[3;1H

The left column gives the byte offset, written in hexadecimal. The middle shows the byte values. The right shows printable ASCII characters, with dots standing in for bytes that xxd does not display as printable characters.

Each pair of hexadecimal digits represents one byte. The grouping 1b5b therefore contains two bytes:

1b  = ESC
5b  = [

The opening four bytes are:

1b 5b 32 4a

Read as a terminal sequence, they are ESC[2J, the clear-screen instruction, immediately after them come:

1b 5b 31 3b 31 48

These form ESC[1;1H, the instruction that positions the cursor.

Now look at the bytes around the first Hi:

... 31 48 48 69 ...
        H  H  i

The two adjacent 48 bytes have the same numerical value, but different roles, the first finishes the cursor-position sequence, the second is the printable H in Hi. The following 69 is the printable i.

Nothing inside the byte 48 identifies which role it has. The terminal determines its meaning from the parsing state established by the preceding bytes.

The hex dump also wraps onto a second line, but that line break belongs to the dump’s formatting. The program did not send a newline there. Its output is one continuous stream of 25 bytes.

Running the program directly shows the result of interpreting that stream. Piping it into xxd exposes the stream before the terminal interprets it. Together, the two views connect the visible screen to the bytes that produced it.

Six printf calls in ex1.c merging into one 25-byte stream with two adjacent 0x48 bytes serving different roles, compared across direct terminal rendering and piping to xxd.

Moving the cursor with a single byte

An escape sequence can move the cursor to a specific row and column, but some movements need only one control byte.

Carriage return is one example. Written as \r in a C string, it produces the byte 0x0D. The terminal interprets it as an instruction to move the cursor to the beginning of the current line, compare these two ways of moving back to column 1:

ESC[1;1H    Six bytes: move to row 1, column 1
\r         One byte: move to column 1 of the current row

If the cursor is already on row 1, both leave it at the same position. Their meaning differs, however. The escape sequence names an absolute position. Carriage return keeps the current row and changes only the column.

The distinction matters whenever we choose which bytes to send. A shorter instruction is useful when it expresses the movement we actually need. Consider this program:

#include <stdio.h>

int main(void) {
    printf("\x1b[2J\x1b[1;1H");
    printf("Hello");
    printf("\r");
    printf("J");
    printf("\n");
    printf("world");
    printf("\x1b[4;1H");
    fflush(stdout);
    return 0;
}

With the code saved as ex2.c, compile and run it:

$ cc -std=c11 -Wall -o ex2 ex2.c
$ ./ex2
Jello # output
world # output

The opening escape sequences clear the screen and position the cursor at row 1, column 1. Writing Hello fills five cells and leaves the cursor at column 6, then carriage return moves it back to column 1. It does not erase the line. The next character, J, replaces the H, leaving Jello on screen.

After writing J, the cursor advances to column 2. Keep that position in mind, because it reveals something important about the following newline.

In a C string, \n represents newline. On the Unix systems considered here, it produces the line feed byte, 0x0A. With the usual terminal behavior, line feed moves the cursor down one row while preserving its column.

Carriage return and line feed therefore perform different movements:

Carriage return, 0D: return to column 1
Line feed,       0A: move down one row

Why, then, does world appear at column 1 in the example?

Between the program and the terminal emulator sits the operating system’s terminal driver. Its output settings commonly translate a newline into a carriage return followed by a line feed.

The program writes:

0a

The terminal emulator receives:

0d 0a

Together, those two bytes move the cursor to the beginning of the next line. The terminal driver performs this translation, rather than the shell itself, if that output translation is disabled, and line feed preserves the column, the result changes:

Jello
 world

There is one space before world. The cursor was at column 2 after writing J, so the line feed leaves it at column 2 on the next row. The earlier position after Hello no longer matters because carriage return and J have already changed it.

To express both movements explicitly, write:

printf("\r\n");

This sends a carriage return followed by a line feed. Understanding the two operations separately helps explain output that appears correctly under one terminal configuration but shifts sideways under another.

Now inspect the bytes the program produces:

./ex2 | xxd

The dump should look like this:

00000000: 1b5b 324a 1b5b 313b 3148 4865 6c6c 6f0d  .[2J.[1;1HHello.
00000010: 4a0a 776f 726c 641b 5b34 3b31 48         J.world.[4;1H

The pipe connects the program’s standard output to xxd. Because those bytes go through a pipe rather than the terminal driver, the dump contains the single 0a that the program wrote. It does not contain the extra carriage return that terminal output processing may introduce during a direct run.

This distinction separates two useful questions: what bytes did the program produce, and what bytes ultimately reached the terminal emulator?

How carriage return 0x0D and line feed 0x0A behave in ex2.c across default OS terminal driver translation to 0D 0A, disabled translation leaving world shifted to column 2, and piping to xxd.

The dump has three columns. On the left is the offset of the first byte on each line, written in hexadecimal. The second line starts at 00000010, which means byte offset 16. The middle column contains the bytes themselves. Each pair of hexadecimal digits represents one byte. By default, xxd groups two bytes together, so:

1b5b 324a

means:

1b 5b 32 4a

The spaces belong to the dump’s formatting. They are not bytes in the program’s output.

The right column shows printable ASCII characters. Nonprinting bytes, including ESC, carriage return, and line feed, appear as dots. A dot in that column is only a display convention, so use the hexadecimal column to identify the actual byte.

The complete output contains 29 bytes:

Bytes in hexadecimal Interpretation
1b 5b 32 4a Clear the screen
1b 5b 31 3b 31 48 Move to row 1, column 1
48 65 6c 6c 6f Write Hello
0d Return to column 1
4a Write J
0a Send line feed
77 6f 72 6c 64 Write world
1b 5b 34 3b 31 48 Move to row 4, column 1

A few byte values soon become familiar:

Hexadecimal Meaning
1b ESC
5b [
3b ;
30 through 39 ASCII digits 0 through 9
0d Carriage return
0a Line feed

On systems that provide it, man ascii gives a reference for the remaining ASCII values.

Reading the dump connects each visible effect to its representation in the stream. It also shows why cursor movement requires attention to context: the current position, the meaning of each control byte, and any translation applied between the program and the terminal.

Buffering and Counting Bytes

In the previous section, we learned that printable characters and control instructions travel through the same stream of bytes. We also learned how the terminal interprets those bytes to display text and manipulate the cursor.

So far, we have been sending instructions directly to the terminal. But what if, instead of sending each instruction individually, we collect all the instructions into a buffer and send them together?

This technique is known as output buffering, and it is one of the fundamental techniques used in efficient terminal programming.

Why Do We Need a Buffer?

Consider the following example:

write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[1;1H", 6);
write(STDOUT_FILENO, "Hi", 2);

Every call to write() involves a system call. Although individual system calls are relatively inexpensive, their overhead can accumulate when we perform thousands of operations while rendering a complex terminal interface.

Instead of calling write() every time we want to send an instruction, we can append those instructions to a memory buffer and send the entire buffer at once.

From the terminal’s perspective, the resulting stream of bytes is the same. The terminal does not care whether those bytes arrive through one system call or several.

Building a Simple Output Buffer

Let’s create a simple program that demonstrates this technique.

Create a file called buffer.c:

#include <stdio.h>
#include <string.h>
#include <unistd.h>

static char buf[256];
static size_t len = 0;

static void put(const char *s) {
    size_t n = strlen(s);

    memcpy(buf + len, s, n);
    len += n;
}

int main(void) {
    put("\x1b[2J");
    put("\x1b[1;1H");
    put("Hi");
    put("\x1b[1;1H");
    put("!");
    put("\x1b[3;1H");

    ssize_t w = write(STDOUT_FILENO, buf, len);

    fprintf(stderr,
        "buffered %zu bytes, write sent %zd\n",
        len, w
    );

    return 0;
}

There are two important variables in this program:

  • buf is a fixed-size memory buffer that stores our outgoing bytes.
  • len keeps track of how many bytes are currently stored in the buffer.

The put() function does not communicate with the terminal. It simply copies the given string into the buffer and updates its length.

Only when we call write() do we actually send the accumulated bytes to the terminal.

This example intentionally omits buffer overflow checks and partial write handling to keep the implementation simple. A production implementation must handle both.

Understanding How the Buffer Works

Every time we call put(), we append more bytes to the end of the existing buffer.

put("\x1b[2J")

[ ESC [ 2 J ]
  len = 4

put("\x1b[1;1H")

[ ESC [ 2 J | ESC [ 1 ; 1 H ]
  len = 10

put("Hi")

[ ESC [ 2 J | ESC [ 1 ; 1 H | H i ]
  len = 12

This process continues until all our instructions and printable characters have been appended.

At this point, everything exists in memory. Nothing has been sent to the terminal yet.

Once we call write(), the entire stream is submitted to the operating system in a single system call.

Counting the Bytes

Before running the program, let’s calculate how many bytes we expect to send.

Instruction Purpose Bytes
\x1b[2J Clear the screen 4
\x1b[1;1H Move to row 1, column 1 6
Hi Draw two characters 2
\x1b[1;1H Return to row 1, column 1 6
! Overwrite the first character 1
\x1b[3;1H Move to row 3, column 1 6
Total 25

Remember that \x1b represents a single byte, even though we use four characters to express it in our C source code, we also do not include the null terminator of each C string because strlen() returns the string length without it. Our entire output should therefore consist of exactly 25 bytes.

Running the Program

Compile and execute the program:

cc -std=c11 -Wall -o buffer buffer.c
./buffer

On a compatible terminal, assuming the entire buffer is successfully written, you should see:

!i

buffered 25 bytes, write sent 25

Notice that we use fprintf(stderr, ...) instead of printf() to display our diagnostic information, this allows us to keep the diagnostic message separate from the standard output stream that we are measuring.

Inspecting the Actual Bytes

We can verify our calculation using a command-line utility called xxd, which displays binary data in hexadecimal format.

Run the following command:

./buffer | xxd

You should see a hexadecimal dump similar to this:

00000000: 1b5b 324a 1b5b 313b 3148 4869 1b5b 313b  .[2J.[1;1HHi.[1;
00000010: 3148 211b 5b33 3b31 48                   1H!.[3;1H

The first column represents the byte offset in hexadecimal.

The first line contains 16 bytes, while the second line starts at offset 0x10, which is 16 in decimal, and contains the remaining 9 bytes.

Adding them together gives us exactly 25 bytes, matching our original calculation.

Because standard output is now redirected into a pipe, the terminal does not directly interpret our escape sequences. Instead, xxd receives the raw bytes and displays their hexadecimal representation.

Our diagnostic message remains visible in the terminal because it is written to standard error.

Buffering vs. Reducing Bytes

There is an important distinction between buffering output and reducing the amount of output.

Approach Bytes sent write() calls
Sending each instruction individually 25 6
Buffering all instructions 25 1

Buffering does not reduce the number of bytes we send. It reduces the number of system calls required to send those bytes. Reducing unnecessary instructions, on the other hand, reduces the actual size of the output stream. Both techniques are important, and we will use them together when building our terminal rendering engine.

Comparing six unbuffered write system calls against buffering 25 bytes in buf[256] for one write call, and showing stdout piped to xxd while stderr stays on the terminal.

Why Counting Bytes Matters

As we progress through this series, we will encounter different ways to achieve the same visual result.

We could move the cursor before every character, or we could take advantage of automatic cursor advancement. We could repeatedly send color instructions, or we could remember the terminal’s current color, but how do we determine which approach produces less output?

We count the bytes.

Counting bytes gives us a simple, measurable way to evaluate the efficiency of our terminal instructions. Combined with measuring system calls and execution time, it helps us understand whether an optimization actually improves performance.

From now on, whenever we introduce a new rendering optimization, we will try to answer two fundamental questions:

  • How many bytes do we need to send?
  • How many system calls do we need to make?

Understanding these two questions will help us build a more efficient terminal rendering engine from scratch.

contents
  1. how a terminal reads your output
  2. Watching a byte stream draw
  3. Moving the cursor with a single byte
  4. Buffering and Counting Bytes

4 sections, 563 lines

SUMMARY OF COMMANDS

e
write an email
g
open GitHub
/
search projects or posts
h
show or hide this help
j, k
next or previous section (home)
q
back to the blog (on a post)
tab
next category (in an empty search box)
1 to 9
open a published project
esc
clear search, close this help