~/blog/terminal/03-escape-sequence-part-2.md

Escape Sequence [Part 2]

2026-11-28#terminal#libterm#c48 min read


In the previous part, we saw how a terminal reads text and escape sequences from one byte stream, how single control bytes move the cursor, and how output buffering cuts down system calls. In this part, we open up CSI sequences and build them ourselves in C. We will break down the introducer, parameter bytes, and final byte, write an integer-to-ASCII encoder and cursor-position builder directly into a memory buffer without printf, optimize sequences by omitting default parameters, and draw a buffered frame to measure exact byte savings before seeing where relative cursor movement takes over.

Cozy Escape Sequence Night Study

Understanding the Structure of CSI Sequences

In the previous section, we learned that a terminal receives printable characters and control instructions through a single stream of bytes. We also learned how buffering allows us to collect multiple instructions before sending them to the terminal.

Now, let’s take a closer look at how these instructions are constructed.

Understanding the structure of escape sequences allows us to construct terminal commands dynamically, calculate their exact byte lengths, and eventually determine the most efficient way to communicate with the terminal.

What Is CSI?

CSI stands for Control Sequence Introducer. In its commonly used seven-bit representation, it consists of two bytes: the Escape character (0x1B) followed by an opening square bracket (0x5B).

In C, we can represent it as:

"\x1b["

These two bytes tell the terminal that the following bytes belong to a control sequence.

Most of the terminal commands we have explored so far, including cursor movement, screen clearing, and text styling, use CSI sequences.

A simple CSI sequence consists of three parts:

  • Introducer: Indicates the beginning of a control sequence.
  • Parameters: Provide additional information about the operation.
  • Final byte: Identifies the operation to perform.

Consider the following sequence:

ESC [ 1 0 ; 6 H

We can break it down into three parts:

Three-part breakdown of CSI sequence ESC[10;6H into 2-byte introducer, 4-byte ASCII parameters, and 1-byte final byte alongside CSI parameter, intermediate, and final byte ranges.

This sequence instructs the terminal to move the cursor to row 10, column 6.

The introducer always occupies two bytes in this representation, the parameters have a variable length, and the final byte occupies exactly one byte.

The complete sequence therefore occupies seven bytes.

How Does the Terminal Know When a Sequence Ends?

Since the terminal receives a continuous stream of bytes, how does it know which bytes represent parameters and which byte marks the end of an instruction?

CSI sequences define specific ranges of byte values for each component.

Component Hexadecimal range ASCII range
Parameter bytes 0x30–0x3F 0 through ?
Intermediate bytes 0x20–0x2F Space through /
Final byte 0x40–0x7E @ through ~

The complete CSI syntax is therefore:

CSI + Parameters + Intermediates + Final byte

Both parameter and intermediate bytes are optional. Most of the sequences we will use throughout this series do not require intermediate bytes, so we can focus on the simpler three-part structure.

When the terminal receives a valid CSI sequence, it continues parsing until it encounters the final byte.

For example:

ESC [ 1 0 ; 6 H

The digits and semicolon belong to the parameter byte range, while H belongs to the final byte range.

When the terminal encounters H, it knows that the sequence is complete and can perform the corresponding operation.

This is why the terminal does not accidentally display the numbers or the final letter on the screen.

Parameters Are Numbers Represented as Text

One important detail about CSI sequences is that their numerical parameters are represented as ASCII characters rather than binary integers.

Consider the number 10.

In a typical C program, we might store it as an integer:

int row = 10;

However, when constructing a CSI sequence, we cannot simply copy the binary representation of that integer into the output stream.

Instead, we need to convert it into its textual representation:

Character:   '1'    '0'
Hexadecimal: 0x31   0x30

The terminal expects the ASCII digits 1 and 0, not the binary integer value 0x0A.

This means that larger numbers require more bytes to represent.

Number ASCII bytes Length
1 31 1 byte
10 31 30 2 bytes
120 31 32 30 3 bytes
1024 31 30 32 34 4 bytes

As a result, the length of a CSI sequence depends on the values of its parameters.

This detail will become particularly important when we start comparing different cursor movement instructions.

Understanding Cursor Position (CUP)

One of the most useful CSI commands for terminal UI programming is CUP, which stands for Cursor Position.

Its structure is:

ESC [ row ; column H

The first parameter specifies the row, the second specifies the column, and the final byte H identifies the cursor positioning operation.

For example:

printf("\x1b[10;6H");

This moves the cursor to row 10, column 6.

Unlike arrays in C, terminal coordinates for CUP start at 1 rather than 0.

A 10-row by 6-column 1-based terminal coordinate grid with the cursor at row 10 column 6, mapped from zero-based C coordinates x=5 y=9 into ESC[10;6H.

If we want to represent screen coordinates using zero-based indexing in our C program, we need to add 1 to both coordinates when constructing the sequence.

int x = 5;
int y = 9;

printf("\x1b[%d;%dH", y + 1, x + 1);

Notice that the terminal expects the row first and the column second, which corresponds to y followed by x.

Calculating the Length of a CSI Sequence

Now that we understand how numerical parameters are represented, we can calculate the exact length of a cursor positioning sequence.

Target Sequence Bytes
Row 1, column 1 ESC[1;1H 6
Row 10, column 6 ESC[10;6H 7
Row 40, column 120 ESC[40;120H 9
Row 100, column 200 ESC[100;200H 10

For a CUP sequence with both parameters explicitly specified, the formula is:

length = 2 + digits(row) + 1 + digits(column) + 1

Where:

2               = CSI introducer
digits(row)     = number of digits in the row
1               = semicolon
digits(column)  = number of digits in the column
1               = final byte

We can simplify this formula to:

length = 4 + digits(row) + digits(column)

For example, moving the cursor to row 40, column 120 requires:

length = 4 + 2 + 3
       = 9 bytes

Being able to calculate the length of an instruction without sending it to the terminal will allow us to compare multiple instructions and choose the shortest one.

Default Parameters

Another interesting property of CSI sequences is that some parameters can be omitted.

When a parameter is omitted, the terminal uses the default value defined by that particular command.

For CUP, both the row and column default to 1.

Therefore, the following sequences are equivalent:

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

Both move the cursor to the top-left corner of the screen.

However, their lengths are different.

Sequence Bytes
ESC[1;1H 6
ESC[H 3

By omitting the default parameters, we have reduced the instruction size by 50%.

We can also omit individual parameters:

Sequence Meaning Bytes
ESC[10;1H Row 10, column 1 7
ESC[10H Row 10, column 1 5
ESC[1;6H Row 1, column 6 6
ESC[;6H Row 1, column 6 5

This is another example of how understanding the terminal protocol allows us to eliminate unnecessary bytes without changing the visual result.

However, remember that default values depend on the command. Not every CSI parameter defaults to 1.

Different Commands, Same Structure

CUP is only one of many CSI commands. Other commands follow the same general syntax but use different parameters and final bytes.

Sequence Parameters Final byte Meaning
ESC[2J 2 J Erase the visible display
ESC[10;6H 10;6 H Position the cursor
ESC[5C 5 C Move the cursor right
ESC[31m 31 m Set foreground color to red
ESC[?25l ?25 l Hide the cursor
ESC[?25h ?25 h Show the cursor
ESC[?2026h ?2026 h Begin synchronized update

Notice the question mark in the last three examples.

The ? character belongs to the parameter byte range and indicates a private parameter namespace. In these particular sequences, it is used to control private terminal modes.

The final byte h sets a mode, while l resets it.

For example:

// Hide the cursor
printf("\x1b[?25l");

// Show the cursor
printf("\x1b[?25h");

Although these commands use private terminal modes rather than standard CSI operations, they still follow the general CSI syntax.

We will explore synchronized updates and other terminal modes later in this series. Support for these extensions varies between terminal emulators.

Constructing a CSI Sequence in C

So far, we have been writing escape sequences manually or using printf() to format their parameters.

But since we already understand how output buffering works, let’s explore how to construct a CSI sequence directly inside a memory buffer.

The first thing we need is a function that converts an unsigned integer into ASCII digits.

#include <stddef.h>

static size_t write_uint(char *buf, unsigned int value) {
    char tmp[sizeof(unsigned int) * 3];
    size_t len = 0;

    do {
        tmp[len++] = '0' + (value % 10);
        value /= 10;
    } while (value != 0);

    for (size_t i = 0; i < len; i++) {
        buf[i] = tmp[len - i - 1];
    }

    return len;
}

This function converts an unsigned integer into its textual representation and returns the number of bytes written.

To understand how it works, consider the number 120.

Value    value % 10    Character
120          0            '0'
 12          2            '2'
  1          1            '1'

By repeatedly applying the modulo and division operations, we extract each decimal digit.

However, the digits are extracted in reverse order.

Temporary buffer:  [ '0' ][ '2' ][ '1' ]
                         Reverse
                            ↓
Output buffer:     [ '1' ][ '2' ][ '0' ]

We then copy the digits into the destination buffer in the correct order.

Notice that this function does not append a null terminator. We are constructing a stream of bytes rather than a conventional null-terminated C string.

Building the Cursor Position Command

Now we can use our write_uint() function to construct a CUP sequence.

static size_t build_cup(
    char *buf,
    unsigned int row,
    unsigned int col
) {
    size_t pos = 0;

    // Introducer
    buf[pos++] = '\x1b';
    buf[pos++] = '[';

    // Parameters
    pos += write_uint(buf + pos, row);
    buf[pos++] = ';';
    pos += write_uint(buf + pos, col);

    // Final byte
    buf[pos++] = 'H';

    return pos;
}

There is nothing particularly complicated happening here. We are simply writing the three components of a CSI sequence into a buffer.

The pos variable represents the next available position in the buffer.

Let’s visualize what happens when we call:

build_cup(buf, 10, 6);
Operation Bytes written Buffer contents Position
Write introducer 1B 5B ESC [ 2
Write row 31 30 ESC [ 1 0 4
Write separator 3B ESC [ 1 0 ; 5
Write column 36 ESC [ 1 0 ; 6 6
Write final byte 48 ESC [ 1 0 ; 6 H 7

The final buffer looks like this:

Index     0    1    2    3    4    5    6
        ┌────┬────┬────┬────┬────┬────┬────┐
Bytes   │ 1B │ 5B │ 31 │ 30 │ 3B │ 36 │ 48 │
        └────┴────┴────┴────┴────┴────┴────┘
          ESC   [    1    0    ;    6    H

The function returns 7, which is exactly the number of bytes we calculated earlier.

At this point, we have constructed a valid CSI sequence without using printf() or any other string formatting function.

Putting Everything Together

Let’s create a complete program that constructs a cursor positioning sequence and sends it to the terminal.

Create a file called csi.c:

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

static size_t write_uint(char *buf, unsigned int value) {
    char tmp[sizeof(unsigned int) * 3];
    size_t len = 0;

    do {
        tmp[len++] = '0' + (value % 10);
        value /= 10;
    } while (value != 0);

    for (size_t i = 0; i < len; i++) {
        buf[i] = tmp[len - i - 1];
    }

    return len;
}

static size_t build_cup(
    char *buf,
    unsigned int row,
    unsigned int col
) {
    size_t pos = 0;

    buf[pos++] = '\x1b';
    buf[pos++] = '[';

    pos += write_uint(buf + pos, row);
    buf[pos++] = ';';
    pos += write_uint(buf + pos, col);

    buf[pos++] = 'H';

    return pos;
}

int main(void) {
    char buf[64];

    size_t len = build_cup(buf, 10, 6);

    write(STDOUT_FILENO, buf, len);

    fprintf(stderr, "Generated %zu bytes\n", len);

    return 0;
}

Compile the program:

cc -std=c11 -Wall -o csi csi.c

Instead of immediately executing the command in our terminal, let’s inspect the generated bytes using xxd.

./csi | xxd

The expected output is:

Generated 7 bytes
00000000: 1b5b 3130 3b36 48    .[10;6H

We have successfully constructed a cursor positioning command from individual bytes.

Try changing the row and column values, predict how many bytes the resulting sequence will contain, and compare your prediction with the actual output.

This is a useful habit to develop before we start implementing more advanced rendering optimizations.

For simplicity, this example assumes that the destination buffer has sufficient capacity and that write() successfully sends the entire sequence. A production implementation must validate these assumptions.

Reserve, Write, and Commit

When constructing terminal instructions, we do not always know their exact length in advance.

However, we can calculate their maximum possible length.

For example, assuming a 32-bit unsigned integer, each coordinate can contain up to 10 decimal digits.

CSI introducer     2 bytes
Row               10 bytes
Separator          1 byte
Column            10 bytes
Final byte         1 byte
──────────────────────────
Maximum           24 bytes

This gives us a useful buffer management pattern:

  1. Reserve enough memory for the maximum possible instruction length.
  2. Write the instruction directly into the reserved memory.
  3. Commit only the number of bytes actually written.
Worst-case 24-byte CUP capacity breakdown and the three-step reserve 24 bytes, write 7 bytes of ESC[10;6H, and commit 7 bytes buffer pattern.

Although we reserved 24 bytes, we only used 7. The remaining space can be reused when constructing the next instruction.

This pattern allows us to construct variable-length instructions directly inside an output buffer without requiring a separate temporary string for each command.

It will become particularly useful when we start generating hundreds or thousands of terminal instructions during rendering.

Putting It All Together

A CSI sequence is fundamentally a structured collection of bytes. It contains an introducer, optional parameters, optional intermediate bytes, and a final byte that identifies the operation.

Because numerical parameters are represented as ASCII digits, the length of a sequence depends on the values it contains. Some commands also allow us to omit default parameters, making their representations even shorter.

We have also learned how to construct a cursor positioning sequence directly inside a memory buffer, calculate its exact length, and reserve memory efficiently.

The important concept to remember is that terminal instructions are not mysterious operations hidden behind an API. They are simply structured bytes that we can construct, inspect, measure, and optimize ourselves.

As we continue through this series, we will use this knowledge to compare different terminal instructions and determine which ones allow us to achieve the same visual result with fewer bytes.

Building a Cursor Position Sequence from Scratch

In the previous section, we learned how a CSI sequence is constructed, how its parameters are represented as ASCII digits, and how we can calculate its exact length.

Now, let’s put that knowledge into practice by building our own Cursor Position (CUP) sequence in C.

Instead of relying on printf() to format the entire escape sequence, we will construct it byte by byte inside a memory buffer. We will also inspect the resulting bytes in hexadecimal format rather than immediately sending them to the terminal.

The goal is to understand exactly what happens when we convert numerical coordinates into a terminal instruction.

Converting Numbers into ASCII Characters

Before constructing our escape sequence, we need to solve a small problem: how do we convert an integer into a sequence of ASCII characters?

For example, the number 120 needs to become three individual characters:

Integer:     120
Characters:  '1'  '2'  '0'
Hexadecimal: 0x31 0x32 0x30

We cannot simply copy the integer into our output buffer because the terminal expects textual digits, not the binary representation of an integer.

Fortunately, ASCII represents decimal digits using consecutive numerical values.

Character Decimal Hexadecimal
0 48 0x30
1 49 0x31
2 50 0x32
3 51 0x33
4 52 0x34
5 53 0x35
6 54 0x36
7 55 0x37
8 56 0x38
9 57 0x39

Because these characters are consecutive, we can convert a single numerical digit into its corresponding ASCII character by adding it to '0'.

char digit = '0' + 5;

The calculation is essentially:

0x30 + 5 = 0x35 = '5'

However, this technique only works when the number is between 0 and 9.

What happens if we try to convert a larger number directly?

Number Expression Result
4 '0' + 4 '4'
9 '0' + 9 '9'
12 '0' + 12 '<'
120 '0' + 120 0xA8 (outside ASCII)

There is no single ASCII character representing the number 120. Instead, we need to separate the number into individual decimal digits and convert each digit independently.

Extracting Digits Using Modulo

In C, the modulo operator (%) returns the remainder of an integer division.

For example:

120 % 10; // 0
12  % 10; // 2
1   % 10; // 1

But why do we specifically use the number 10?

Our decimal number system is based on powers of 10. Every decimal integer can be expressed as a multiple of 10 plus its last digit.

For example:

127 = (12 × 10) + 7

When we calculate 127 % 10, the remainder is 7, which is exactly the last digit of the number.

This means that applying % 10 to a non-negative integer always produces a value between 0 and 9.

We can combine this operation with what we learned about ASCII:

char digit = (char)('0' + (value % 10));

Now, regardless of how large the number is, we are only converting its last decimal digit into an ASCII character.

Removing the Last Digit

After extracting the last digit, we need to remove it so that we can process the next one.

We can achieve this using integer division:

value /= 10;

Unlike floating-point division, integer division discards the fractional part of the result.

120 / 10 = 12
 12 / 10 = 1
  1 / 10 = 0

By combining modulo and integer division, we can extract every digit from a number.

Let’s follow the process using 120:

Tracing write_uint(buf, 120) through modulo 10 and integer division by 10 to produce tmp ['0','2','1'] and reversing it into destination buf ['1','2','0'] (0x31 0x32 0x30).

Notice that the digits are extracted in reverse order.

This happens because we are always extracting the rightmost digit first.

To obtain the correct textual representation, we need to reverse the extracted digits before writing them into our destination buffer.

Implementing Our Integer Conversion Function

Now that we understand the underlying mechanism, let’s implement it in C.

static int write_uint(char *buf, unsigned int v) {
    char tmp[10];
    int n = 0;

    do {
        tmp[n++] = (char)('0' + v % 10);
        v /= 10;
    } while (v > 0);

    for (int i = 0; i < n; i++) {
        buf[i] = tmp[n - i - 1];
    }

    return n;
}

For this exercise, we assume that unsigned int is 32 bits, which requires at most 10 decimal digits.

Let’s examine the most important part of this function:

tmp[n++] = (char)('0' + v % 10);
v /= 10;

The first line extracts the last digit, converts it into an ASCII character, stores it in the temporary buffer, and advances the buffer index.

The second line removes the digit we just processed.

For an input of 120, the loop behaves as follows:

Iteration v v % 10 Character Temporary buffer n New v
1 120 0 '0' 0 1 12
2 12 2 '2' 02 2 1
3 1 1 '1' 021 3 0

Once v becomes zero, the loop stops.

The temporary buffer now contains:

tmp: ['0', '2', '1']

We then reverse the digits while copying them into the destination buffer:

for (int i = 0; i < n; i++) {
    buf[i] = tmp[n - i - 1];
}

The result is:

buf: ['1', '2', '0']

Our function returns 3, which represents both the number of decimal digits and the number of bytes written.

Notice that we do not append a null terminator. We are constructing a byte stream, not a conventional null-terminated C string.

Constructing the CUP Sequence

Now that we can convert integers into ASCII digits, we have everything we need to construct a cursor positioning sequence.

Recall the structure of CUP:

ESC [ row ; column H

Let’s implement a function that generates this sequence.

static size_t cup(char *p, unsigned int x, unsigned int y) {
    size_t pos = 0;

    // CSI introducer
    p[pos++] = '\x1b';
    p[pos++] = '[';

    // Row
    pos += (size_t)write_uint(p + pos, y + 1);

    // Parameter separator
    p[pos++] = ';';

    // Column
    pos += (size_t)write_uint(p + pos, x + 1);

    // Final byte
    p[pos++] = 'H';

    return pos;
}

Our function accepts zero-based coordinates, similar to array indices in C.

However, terminal coordinates start at 1. This is why we add 1 to both x and y.

We also need to remember that CUP expects the row before the column, meaning that y comes before x.

Suppose we call:

cup(buf, 5, 9);

The resulting sequence will be:

ESC[10;6H

Let’s follow how the buffer changes during each operation.

Operation Bytes written Buffer contents Position
Introducer 1B 5B ESC [ 2
Row 31 30 ESC [ 1 0 4
Separator 3B ESC [ 1 0 ; 5
Column 36 ESC [ 1 0 ; 6 6
Final byte 48 ESC [ 1 0 ; 6 H 7

The function returns 7, which is the exact length of the generated sequence.

Inspecting the Generated Bytes

Instead of sending the generated sequence directly to the terminal, let’s print its hexadecimal representation.

static void show(unsigned int x, unsigned int y) {
    char seq[24];

    size_t n = cup(seq, x, y);

    printf("x=%-3u y=%-3u %2zu bytes: ", x, y, n);

    for (size_t i = 0; i < n; i++) {
        printf("%02x ", (unsigned int)(unsigned char)seq[i]);
    }

    printf("\n");
}

We allocate 24 bytes because that is the maximum space required for a CUP sequence containing two 32-bit unsigned integer parameters.

CSI introducer     2 bytes
Row               10 bytes
Separator          1 byte
Column            10 bytes
Final byte         1 byte
──────────────────────────
Total             24 bytes

The %02x format specifier tells printf() to display each byte as a hexadecimal number, padded with a leading zero when necessary.

For example:

Decimal 7   → 07
Decimal 27  → 1b
Decimal 72  → 48

This allows us to inspect the exact bytes generated by our function without having the terminal interpret them as instructions.

Putting Everything Together

Create a file called cup.c:

#include <stdio.h>

static int write_uint(char *buf, unsigned int v) {
    char tmp[10];
    int n = 0;

    do {
        tmp[n++] = (char)('0' + v % 10);
        v /= 10;
    } while (v > 0);

    for (int i = 0; i < n; i++) {
        buf[i] = tmp[n - i - 1];
    }

    return n;
}

static size_t cup(char *p, unsigned int x, unsigned int y) {
    size_t pos = 0;

    p[pos++] = '\x1b';
    p[pos++] = '[';

    pos += (size_t)write_uint(p + pos, y + 1);
    p[pos++] = ';';
    pos += (size_t)write_uint(p + pos, x + 1);

    p[pos++] = 'H';

    return pos;
}

static void show(unsigned int x, unsigned int y) {
    char seq[24];

    size_t n = cup(seq, x, y);

    printf("x=%-3u y=%-3u %2zu bytes: ", x, y, n);

    for (size_t i = 0; i < n; i++) {
        printf("%02x ", (unsigned int)(unsigned char)seq[i]);
    }

    printf("\n");
}

int main(void) {
    show(0, 0);
    show(5, 9);
    show(119, 39);

    return 0;
}

Before running the program, try calculating the expected number of bytes yourself.

Remember the formula from the previous section:

length = 4 + digits(row) + digits(column)

Do not forget to convert the zero-based coordinates into one-based terminal coordinates first.

Compile and run the program:

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

You should see the following output:

x=0   y=0    6 bytes: 1b 5b 31 3b 31 48
x=5   y=9    7 bytes: 1b 5b 31 30 3b 36 48
x=119 y=39   9 bytes: 1b 5b 34 30 3b 31 32 30 48

Let’s examine the last sequence byte by byte:

Hexadecimal Character Purpose
1B ESC Escape character
5B [ Completes the CSI introducer
34 4 Row digit
30 0 Row digit
3B ; Parameter separator
31 1 Column digit
32 2 Column digit
30 0 Column digit
48 H Final byte

Together, these nine bytes form the following instruction:

ESC[40;120H

We have successfully constructed a terminal instruction from individual bytes without using a string formatting function to generate it.

Challenge Yourself

Before moving to the next section, try predicting the generated sequences and their lengths for these coordinates:

show(9, 9);
show(99, 99);
show(999, 999);
show(0, 49);

Calculate the expected byte count manually before running the program. Then compare your predictions with the actual results.

You can also try implementing a function that generates a shorter CUP sequence by omitting parameters when their values are equal to the default value of 1.

For example:

ESC[1;1H  → ESC[H
ESC[10;1H → ESC[10H
ESC[1;6H  → ESC[;6H

Can you achieve the same cursor position while generating fewer bytes?

Putting It All Together

In this exercise, we learned how to extract decimal digits using modulo and integer division, convert those digits into ASCII characters, and construct a CSI sequence directly inside a memory buffer.

More importantly, we can now calculate the exact number of bytes required to represent a cursor positioning instruction.

This might seem like a small achievement, but it gives us a foundation for understanding more advanced terminal rendering techniques.

When we eventually build our rendering engine, we will need to generate thousands of instructions efficiently. Understanding how those instructions are represented at the byte level will help us make better decisions about which instructions to send and which ones we can avoid.

For now, remember that even a seemingly complex terminal instruction is simply a sequence of bytes that we can construct ourselves.

Exercise 2: Optimizing CSI Sequences by Omitting Default Parameters

In the previous exercise, we learned how to construct a Cursor Position (CUP) sequence directly inside a memory buffer and calculate its exact length.

However, our implementation always includes both the row and column parameters, even when they are unnecessary.

Can we achieve the same cursor position while sending fewer bytes to the terminal?

The answer lies in understanding how CSI sequences handle default parameters. In this exercise, we will implement our first escape sequence optimization.

Understanding Default Parameters

As we learned earlier, when a parameter is omitted from a CSI sequence, the terminal uses the default value defined by that particular command.

For CUP, both the row and column default to 1.

Consider the following instruction:

ESC[1;1H

This moves the cursor to row 1, column 1. However, since both parameters are already equal to their default values, we can omit them entirely:

ESC[H

Both instructions produce the same result, but the second instruction requires only three bytes instead of six.

We can apply this principle to individual parameters as well.

There are four possible cases:

Row Column Full sequence Short sequence
1 1 ESC[1;1H ESC[H
10 1 ESC[10;1H ESC[10H
1 6 ESC[1;6H ESC[;6H
10 6 ESC[10;6H ESC[10;6H

Notice that when the row is 1 but the column is not, we still need to include the semicolon.

This is because the position of each parameter determines its meaning.

For example:

ESC[6H

This moves the cursor to row 6, column 1, not row 1, column 6.

To specify column 6 while using the default row, we need to write:

ESC[;6H

The empty parameter before the semicolon tells the terminal to use the default row value.

Visualizing the Optimization

Let’s compare the full and shortened representations of a CUP sequence targeting row 1, column 6.

Byte-by-byte comparison of full cup() versus shortened cup_short() across all four default parameter cases, reducing 26 bytes to 20 bytes (23.1% saved).

In this case, we can remove both the semicolon and the column parameter because there are no additional parameters after it.

Revisiting Our Previous Implementation

In the previous exercise, we implemented a function that constructs a CUP sequence by writing each component into a buffer.

static size_t cup(char *p, unsigned int x, unsigned int y) {
    size_t pos = 0;

    p[pos++] = '\x1b';
    p[pos++] = '[';

    pos += (size_t)write_uint(p + pos, y + 1);
    p[pos++] = ';';
    pos += (size_t)write_uint(p + pos, x + 1);

    p[pos++] = 'H';

    return pos;
}

This implementation works correctly, but it always writes both numerical parameters and the semicolon.

Since we now understand how default parameters work, we can introduce a few conditions to avoid writing unnecessary bytes.

Implementing a Shorter CUP Sequence

Let’s create another function called cup_short().

static size_t cup_short(
    char *p,
    unsigned int x,
    unsigned int y
) {
    size_t pos = 0;

    // CSI introducer
    p[pos++] = '\x1b';
    p[pos++] = '[';

    // Write the row only when it is not the default.
    if (y != 0) {
        pos += (size_t)write_uint(p + pos, y + 1);
    }

    // Write the separator and column only when necessary.
    if (x != 0) {
        p[pos++] = ';';
        pos += (size_t)write_uint(p + pos, x + 1);
    }

    // Final byte
    p[pos++] = 'H';

    return pos;
}

The structure is almost identical to our previous implementation. The only difference is that we now conditionally write the parameters.

Remember that our application uses zero-based coordinates, while the terminal uses one-based coordinates.

Therefore:

Application coordinate 0 = Terminal coordinate 1

This means that checking whether y is zero is equivalent to checking whether the terminal row is equal to its default value of 1.

The same applies to x.

Understanding How the Function Works

Let’s walk through each possible case.

Case 1: Both Parameters Are Default

Suppose we call:

cup_short(buf, 0, 0);

Both conditions evaluate to false, so neither parameter is written.

Operation              Buffer       Position
─────────────────────────────────────────────
Write introducer       ESC [        2
Skip row               ESC [        2
Skip column            ESC [        2
Write final byte       ESC [ H      3

The resulting instruction is:

ESC[H

We have reduced the sequence from six bytes to three bytes.

Case 2: Only the Column Is Default

Consider the following coordinates:

cup_short(buf, 0, 9);

The terminal coordinates are row 10, column 1.

Since the row is not equal to its default value, we write it into the buffer. However, the column is equal to its default value, so we omit both the semicolon and the column digits.

Operation              Buffer          Position
───────────────────────────────────────────────
Write introducer       ESC [           2
Write row              ESC [ 1 0       4
Skip column            ESC [ 1 0       4
Write final byte       ESC [ 1 0 H     5

The resulting instruction is:

ESC[10H

Instead of seven bytes, we only need five.

Case 3: Only the Row Is Default

Now consider:

cup_short(buf, 5, 0);

The terminal coordinates are row 1, column 6.

We omit the row parameter but retain the semicolon and the column.

Operation              Buffer          Position
───────────────────────────────────────────────
Write introducer       ESC [           2
Skip row               ESC [           2
Write separator        ESC [ ;         3
Write column           ESC [ ; 6       4
Write final byte       ESC [ ; 6 H     5

The resulting instruction is:

ESC[;6H

This is one byte shorter than the original sequence.

Case 4: Neither Parameter Is Default

Finally, consider:

cup_short(buf, 5, 9);

Neither parameter is equal to its default value, so both parameters must be included.

ESC[10;6H

In this case, the optimized implementation produces exactly the same seven bytes as the original implementation.

An optimization does not necessarily improve every possible case. Sometimes, the original representation is already as short as it can be.

Comparing the Two Implementations

Now, let’s create a complete program that compares the original CUP implementation with our optimized version.

Create a file called cup_short.c:

#include <stdio.h>

static int write_uint(char *buf, unsigned int v) {
    char tmp[10];
    int n = 0;

    do {
        tmp[n++] = (char)('0' + v % 10);
        v /= 10;
    } while (v > 0);

    for (int i = 0; i < n; i++) {
        buf[i] = tmp[n - i - 1];
    }

    return n;
}

static size_t cup(
    char *p,
    unsigned int x,
    unsigned int y
) {
    size_t pos = 0;

    p[pos++] = '\x1b';
    p[pos++] = '[';

    pos += (size_t)write_uint(p + pos, y + 1);
    p[pos++] = ';';
    pos += (size_t)write_uint(p + pos, x + 1);

    p[pos++] = 'H';

    return pos;
}

static size_t cup_short(
    char *p,
    unsigned int x,
    unsigned int y
) {
    size_t pos = 0;

    p[pos++] = '\x1b';
    p[pos++] = '[';

    if (y != 0) {
        pos += (size_t)write_uint(p + pos, y + 1);
    }

    if (x != 0) {
        p[pos++] = ';';
        pos += (size_t)write_uint(p + pos, x + 1);
    }

    p[pos++] = 'H';

    return pos;
}

static void print_seq(
    const char *label,
    const char *seq,
    size_t n
) {
    printf("  %-6s %2zu bytes: ", label, n);

    for (size_t i = 0; i < n; i++) {
        printf("%02x ",
            (unsigned int)(unsigned char)seq[i]);
    }

    printf("\n");
}

static void compare(unsigned int x, unsigned int y) {
    char a[24];
    char b[24];

    size_t na = cup(a, x, y);
    size_t nb = cup_short(b, x, y);

    printf("x=%u y=%u\n", x, y);

    print_seq("full", a, na);
    print_seq("short", b, nb);
}

int main(void) {
    compare(0, 0);
    compare(0, 9);
    compare(5, 0);
    compare(5, 9);

    return 0;
}

The compare() function generates two representations of the same cursor positioning instruction and prints their hexadecimal bytes alongside their lengths.

Before running the program, try predicting the length of each sequence yourself.

Running the Program

Compile and execute the program:

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

You should see the following output:

x=0 y=0
  full    6 bytes: 1b 5b 31 3b 31 48
  short   3 bytes: 1b 5b 48

x=0 y=9
  full    7 bytes: 1b 5b 31 30 3b 31 48
  short   5 bytes: 1b 5b 31 30 48

x=5 y=0
  full    6 bytes: 1b 5b 31 3b 36 48
  short   5 bytes: 1b 5b 3b 36 48

x=5 y=9
  full    7 bytes: 1b 5b 31 30 3b 36 48
  short   7 bytes: 1b 5b 31 30 3b 36 48

Pay particular attention to the third case:

1b 5b 3b 36 48

Let’s decode these bytes:

Hexadecimal Character Purpose
1B ESC Escape character
5B [ CSI introducer
3B ; Parameter separator
36 6 Column parameter
48 H Cursor Position command

There are no digits between the opening bracket and the semicolon. The terminal interprets this empty parameter as the default row value of 1.

Measuring the Optimization

Now that we have generated both representations, we can measure how many bytes we have saved.

Target position Full Short Bytes saved Reduction
Row 1, column 1 6 3 3 50%
Row 10, column 1 7 5 2 28.6%
Row 1, column 6 6 5 1 16.7%
Row 10, column 6 7 7 0 0%
Total 26 20 6 23.1%

Across these four instructions, we have reduced the total number of bytes from 26 to 20.

We have not changed the resulting cursor positions, introduced a compression algorithm, or used any advanced data structures.

We have simply taken advantage of the existing rules of the terminal protocol.

Although saving a few bytes might seem insignificant, these savings can accumulate when an application generates many cursor movement instructions during rendering.

However, fewer bytes do not automatically guarantee faster execution. Actual performance also depends on the cost of generating instructions, system calls, and how the terminal processes the output.

Testing on a Real Terminal

So far, we have only inspected the hexadecimal representation of our generated sequences.

Let’s verify that a shortened sequence actually works on a compatible terminal.

Run the following command in your shell:

printf '\x1b[2J\x1b[10HX\x1b[12H\n'

Let’s break down the instructions:

Instruction Purpose
\x1b[2J Clear the visible screen
\x1b[10H Move to row 10, column 1
X Draw the character X
\x1b[12H Move to row 12, column 1
\n Print a newline

Assuming the terminal has enough rows and is using its normal cursor positioning mode, you should see the character X appear at row 10, column 1.

Try replacing the shortened instruction:

printf '\x1b[2J\x1b[10;1HX\x1b[12H\n'

The character should appear in exactly the same position.

This demonstrates that both representations are functionally equivalent for cursor positioning.

Challenge Yourself

Before moving to the next section, try adding the following coordinates to your program:

compare(0, 99);
compare(99, 0);
compare(0, 999);
compare(119, 39);

For each case, try to answer these questions:

  • What are the corresponding one-based terminal coordinates?
  • What is the full CUP sequence?
  • Which parameters can be omitted?
  • How many bytes can we save?

Calculate the answers manually before running the program.

The goal is to become comfortable reading, constructing, and measuring terminal instructions without relying entirely on the computer to do the calculation for us.

Putting It All Together

In this exercise, we learned that a terminal instruction can have multiple representations that produce the same result.

By understanding the default parameters of CUP, we were able to eliminate unnecessary digits and separators, reducing the size of our output stream without changing its meaning.

This introduces an important principle of terminal rendering optimization:

Instead of asking only how to achieve a particular result, we should also ask how many bytes are necessary to achieve it.

So far, we have optimized a single type of cursor movement instruction. Later in this series, we will discover that terminals provide several different commands for moving the cursor.

Once we understand those commands, we can compare their lengths and select the most efficient instruction for each situation.

Drawing a Frame and Measuring Byte Savings

In the previous exercises, we learned how to construct CSI sequences manually and reduce their lengths by omitting default parameters.

We also learned how to collect multiple terminal instructions into an output buffer before sending them through a single system call.

Now, let’s combine these concepts.

In this exercise, we will draw the same picture using two different cursor positioning implementations: one that always includes both parameters and another that omits unnecessary default parameters.

Our goal is to measure how much data we can eliminate without changing what appears on the screen.

Defining Our Picture

Before writing any code, let’s decide what we want to draw.

We will place five characters at different positions on the terminal screen: four corners of a 10-column by 5-row rectangle and one near its center.

       Columns
       1234567890

Row 1  X........X
Row 2  ..........
Row 3  ....X.....
Row 4  ..........
Row 5  X........X

The dots represent empty cells. They are not characters that we need to send to the terminal.

Using zero-based coordinates, we can represent these positions as an array:

static const int pts[][2] = {
    {0, 0},
    {9, 0},
    {0, 4},
    {9, 4},
    {4, 2}
};

For each position, we need to perform two operations:

  • Move the cursor to the desired position.
  • Write the character X.

Once all five characters have been drawn, we will move the cursor below the picture.

Although the picture is simple, it represents a fundamental rendering operation: positioning content at specific locations on a terminal screen.

Introducing Function Pointers

We already have two functions that generate cursor positioning sequences:

cup();
cup_short();

Both functions accept the same arguments and return the number of bytes written into a buffer.

Instead of implementing two separate drawing functions, we can use a function pointer to dynamically select which cursor positioning implementation to use.

typedef size_t (*move_fn)(char *p, int x, int y);

Let’s break down this declaration:

Component Meaning
typedef Defines a type alias
size_t The function’s return type
(*move_fn) A pointer to a function
char *p Destination buffer
int x, int y Zero-based coordinates

We can now declare a function pointer and assign either implementation to it:

move_fn mv = cup;

Or:

move_fn mv = cup_short;

Calling the function through this pointer works just like calling a regular function:

size_t n = mv(buf, 5, 9);

This allows our rendering logic to remain independent of how cursor positioning sequences are constructed.

The drawing function only needs to know where it wants to move the cursor. It does not need to know how the instruction is encoded.

Creating an Output Buffer

In an earlier exercise, we used a global array and a variable to track the number of bytes stored in it.

This time, we want to maintain two independent output buffers so that we can compare their contents.

We can achieve this by grouping the buffer and its length into a structure.

struct out {
    char buf[512];
    size_t len;
};

Each instance of this structure represents an independent stream of outgoing terminal instructions.

struct out full = {0};
struct out shrt = {0};

The full buffer will contain instructions generated using our original CUP builder, while the shrt buffer will contain instructions generated using the optimized builder.

Both buffers will describe the same picture.

Appending Text to the Buffer

To append printable characters or predefined escape sequences, we can reuse the buffering technique from our previous exercise.

static void put_text(struct out *o, const char *s) {
    size_t n = strlen(s);

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

This function copies the given string into the available space at the end of the buffer and updates its length.

For example:

put_text(&full, "\x1b[2J");
put_text(&full, "X");

The buffer will contain:

Index    0    1    2    3    4
       ┌────┬────┬────┬────┬────┐
Bytes  │ 1B │ 5B │ 32 │ 4A │ 58 │
       └────┴────┴────┴────┴────┘
         ESC   [    2    J    X

Length: 5 bytes

Nothing has been sent to the terminal yet. We are simply constructing our output stream in memory.

Writing Instructions Directly into the Buffer

We could generate a cursor positioning sequence inside a temporary buffer and then copy it into our output buffer.

However, this would introduce an unnecessary memory copy.

Since our CUP builders already accept a destination pointer, we can let them write directly into the available space at the end of our output buffer.

static void put_move(
    struct out *o,
    move_fn mv,
    int x,
    int y
) {
    o->len += mv(o->buf + o->len, x, y);
}

There are three important operations happening here:

  1. o->buf + o->len calculates the address of the next available byte.
  2. mv() constructs the cursor positioning sequence directly at that address.
  3. The returned length is added to o->len.

Suppose our buffer already contains a screen-clearing instruction.

Now we call:

put_move(&shrt, cup_short, 0, 0);

The builder receives a pointer to index 4 and writes the three-byte sequence ESC[H.

The 10 by 5 five-X terminal frame comparing 47-byte full output against 39-byte short output, and put_move() writing ESC[H directly at o->buf + 4 to advance len from 4 to 7.

Because the builder returns the number of bytes it wrote, we can advance the buffer length without scanning its contents or calculating the sequence length again.

This follows the write-and-commit portion of the reserve–write–commit pattern we discussed earlier. For simplicity, we assume that enough buffer capacity is already available.

A production implementation would explicitly check or reserve the required capacity before writing.

Implementing the Drawing Function

Now that we can append text and cursor positioning instructions to our buffer, we can implement the drawing function.

static void draw(struct out *o, move_fn mv) {
    static const int pts[][2] = {
        {0, 0},
        {9, 0},
        {0, 4},
        {9, 4},
        {4, 2}
    };

    put_text(o, "\x1b[2J");

    for (size_t i = 0;
         i < sizeof pts / sizeof pts[0];
         i++) {
        put_move(o, mv, pts[i][0], pts[i][1]);
        put_text(o, "X");
    }

    put_move(o, mv, 0, 6);
}

The function first appends an instruction to clear the visible screen.

It then iterates over our five coordinates, appending a cursor positioning instruction followed by the character X.

Finally, it moves the cursor to row 7, column 1, leaving some space between the picture and any subsequent output.

Notice that the function does not call write().

Its responsibility is only to construct the output stream. Sending that stream to the terminal is a separate operation.

This separation between generating and transmitting instructions will become increasingly useful as our rendering logic grows more complex.

Putting Everything Together

Create a file called frame.c:

#define _POSIX_C_SOURCE 200809L

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

static int write_uint(char *buf, int v) {
    if (v <= 0) {
        buf[0] = '0';
        return 1;
    }

    char tmp[10];
    int n = 0;

    while (v > 0) {
        tmp[n++] = (char)('0' + v % 10);
        v /= 10;
    }

    for (int i = 0; i < n; i++) {
        buf[i] = tmp[n - i - 1];
    }

    return n;
}

static size_t cup(char *p, int x, int y) {
    size_t pos = 0;

    p[pos++] = '\x1b';
    p[pos++] = '[';

    pos += (size_t)write_uint(p + pos, y + 1);
    p[pos++] = ';';
    pos += (size_t)write_uint(p + pos, x + 1);

    p[pos++] = 'H';

    return pos;
}

static size_t cup_short(char *p, int x, int y) {
    size_t pos = 0;

    p[pos++] = '\x1b';
    p[pos++] = '[';

    if (y != 0) {
        pos += (size_t)write_uint(p + pos, y + 1);
    }

    if (x != 0) {
        p[pos++] = ';';
        pos += (size_t)write_uint(p + pos, x + 1);
    }

    p[pos++] = 'H';

    return pos;
}

typedef size_t (*move_fn)(char *p, int x, int y);

struct out {
    char buf[512];
    size_t len;
};

static void put_text(struct out *o, const char *s) {
    size_t n = strlen(s);

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

static void put_move(
    struct out *o,
    move_fn mv,
    int x,
    int y
) {
    o->len += mv(o->buf + o->len, x, y);
}

static void draw(struct out *o, move_fn mv) {
    static const int pts[][2] = {
        {0, 0},
        {9, 0},
        {0, 4},
        {9, 4},
        {4, 2}
    };

    put_text(o, "\x1b[2J");

    for (size_t i = 0;
         i < sizeof pts / sizeof pts[0];
         i++) {
        put_move(o, mv, pts[i][0], pts[i][1]);
        put_text(o, "X");
    }

    put_move(o, mv, 0, 6);
}

int main(void) {
    struct out full = {0};
    struct out shrt = {0};

    draw(&full, cup);
    draw(&shrt, cup_short);

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

    if (w < 0 || (size_t)w != shrt.len) {
        fprintf(stderr, "Failed to write complete frame\n");
        return 1;
    }

    fprintf(
        stderr,
        "full: %zu bytes, short: %zu bytes\n",
        full.len,
        shrt.len
    );

    return 0;
}

Both calls to draw() generate the same picture using different cursor positioning builders.

However, we only send the optimized output buffer to the terminal. There is no need to transmit both streams simply to compare their lengths.

We also write the diagnostic information to standard error so that it remains separate from the output stream we are measuring.

Predicting the Byte Count

Before compiling the program, let’s calculate the expected number of bytes manually.

Our output stream consists of:

  • One screen-clearing instruction.
  • Five cursor positioning instructions for drawing the characters.
  • Five printable characters.
  • One final cursor positioning instruction.

The screen-clearing instruction requires four bytes, and each X requires one byte.

These nine bytes are identical in both implementations. The only difference is how we construct the six cursor positioning instructions.

Coordinates (x, y) Full sequence Short sequence Full bytes Short bytes
(0, 0) ESC[1;1H ESC[H 6 3
(9, 0) ESC[1;10H ESC[;10H 7 6
(0, 4) ESC[5;1H ESC[5H 6 4
(9, 4) ESC[5;10H ESC[5;10H 7 7
(4, 2) ESC[3;5H ESC[3;5H 6 6
(0, 6) ESC[7;1H ESC[7H 6 4
Total 38 30

Adding the remaining nine bytes gives us:

Full sequence:

4 + 38 + 5 = 47 bytes

Short sequence:

4 + 30 + 5 = 39 bytes

We expect the optimized implementation to save eight bytes.

Running the Program

Compile and execute the program:

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

On a compatible terminal with sufficient rows and columns, you should see:

X        X

    X

X        X

full: 47 bytes, short: 39 bytes

Our prediction matches the expected output.

We have successfully reduced the size of our output stream without changing the picture.

Measuring the Optimization

Let’s calculate the percentage of bytes saved.

Bytes saved = 47 - 39
            = 8 bytes

Reduction   = (8 / 47) × 100
            ≈ 17.02%
Measurement Full builder Optimized builder
Screen-clearing bytes 4 4
Cursor positioning bytes 38 30
Printable character bytes 5 5
Total output bytes 47 39
System calls needed for a complete write 1 1

Both implementations use the same buffering strategy. Therefore, the difference in output size comes entirely from how we construct the cursor positioning instructions.

We have combined two independent optimization techniques:

  • Output buffering reduces the number of system calls.
  • Omitting default parameters reduces the number of bytes sent.

These techniques complement each other, but they solve different problems.

Understanding the Limitations

Although our optimized implementation produces fewer bytes, it cannot improve every cursor positioning instruction.

Consider the movement to row 5, column 10:

ESC[5;10H

Neither parameter is equal to its default value. Therefore, both builders generate exactly the same seven bytes.

Our current optimization cannot make this instruction any shorter.

But consider what happens immediately before this movement.

We have just drawn an X at row 5, column 1. Because printing an ordinary ASCII character advances the cursor, its current position is now row 5, column 2.

Row 5 with X at column 1 and cursor at column 2 moving 8 columns right to column 10, comparing 7-byte absolute ESC[5;10H against 4-byte relative ESC[8C.

Instead of explicitly specifying the destination row and column, what if we simply instruct the terminal to move eight columns to the right?

The terminal provides a command for exactly this operation:

ESC[8C

This instruction requires only four bytes.

Instruction Type Bytes
ESC[5;10H Absolute cursor positioning 7
ESC[8C Relative cursor movement 4

Both instructions reach the same destination in this particular situation.

However, the relative movement instruction requires us to know where the cursor is currently positioned.

This introduces another important concept in terminal rendering: tracking the terminal’s state.

If we know the current cursor position, we can potentially choose a shorter instruction instead of always using absolute positioning.

We will explore this technique in the next section.

Challenge Yourself

Try modifying the coordinates in the draw() function.

For example, place five characters vertically in the first column:

static const int pts[][2] = {
    {0, 0},
    {0, 1},
    {0, 2},
    {0, 3},
    {0, 4}
};

Before running the program, calculate how many bytes each builder will generate.

Then try placing all five characters somewhere away from the first row and first column.

Observe how the effectiveness of our optimization changes depending on the positions of the characters.

This demonstrates that the effectiveness of an optimization often depends on the characteristics of the data being processed.

Putting It All Together

In this exercise, we combined output buffering, function pointers, dynamic escape sequence construction, and default parameter optimization to generate a simple terminal frame.

By constructing instructions directly inside an output buffer, we avoided unnecessary intermediate copies. By omitting default parameters, we reduced our output stream from 47 bytes to 39 bytes, a reduction of approximately 17%.

More importantly, we now have a repeatable method for evaluating terminal rendering optimizations: generate equivalent output streams, measure their lengths, and compare the results.

We have also discovered the limitations of absolute cursor positioning.

In the next section, we will explore relative cursor movement, learn how to track the terminal’s cursor position, and discover how understanding the terminal’s current state allows us to generate even shorter instructions.

Further Reading

contents
  1. Understanding the Structure of CSI Sequences
  2. Building a Cursor Position Sequence from Scratch
  3. Exercise 2: Optimizing CSI Sequences by Omitting Default Parameters
  4. Drawing a Frame and Measuring Byte Savings

4 sections, 2034 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