~/blog/terminal/04-escape-sequence-part-3.md
Escape Sequence [Part 3]
In the previous section, we learned how to construct cursor positioning sequences and optimize them by omitting default parameters, we also discovered a limitation of this optimization: when neither the row nor the column is equal to its default value, we cannot make the CUP sequence any shorter by omitting parameters, consider the following instruction:
ESC[5;13H
This instruction requires seven bytes to move the cursor to row 5, column 13, but what if the cursor is already on row 5? Do we really need to tell the terminal which row to move to? and what if the cursor is only three columns away from our destination? Instead of specifying the entire destination, we could simply instruct the terminal to move three columns to the right, this is where understanding different cursor movement commands becomes useful. By knowing the terminal’s current state, we can choose a more efficient instruction to achieve the same result.
Relative and Horizontal Cursor Movement
Absolute vs. Relative Cursor Movement
Before exploring additional escape sequences, we need to understand the difference between absolute and relative movement, Absolute movement specifies a fixed destination, for example:
Move to column 13.
The destination does not depend on the cursor’s current column, Relative movement, on the other hand, specifies a distance from the current position.
Move three columns to the right.
The destination depends on where the cursor is currently positioned, we can visualize the difference like this:
Both instructions reach the same destination in this example, but they describe the movement differently, the terminal provides commands for both approaches.
Cursor Forward (CUF)
CUF stands for Cursor Forward. It moves the cursor a specified number of columns to the right without changing its row, the structure of the sequence is:
ESC [ n C
Where:
nspecifies the number of columns to move.Cis the final byte identifying the Cursor Forward command.
For example:
printf("\x1b[3C");
This moves the cursor three columns to the right, suppose the cursor is currently at row 5, column 10.
Before:
Column: 8 9 10 11 12 13 14
. . ▮ . . . .
After ESC[3C:
Column: 8 9 10 11 12 13 14
. . . . . ▮ .
The cursor is now at row 5, column 13, notice that we did not need to specify either the destination row or the destination column. We only needed to specify the distance, like CUP, CUF also supports a default parameter, when the parameter is omitted, the terminal moves the cursor one column to the right.
ESC[1C → ESC[C
Both sequences perform the same operation.
| Sequence | Movement | Bytes |
|---|---|---|
ESC[C |
Right by 1 column | 3 |
ESC[1C |
Right by 1 column | 4 |
ESC[3C |
Right by 3 columns | 4 |
ESC[15C |
Right by 15 columns | 5 |
ESC[100C |
Right by 100 columns | 6 |
CUF does not wrap the cursor onto the next row when it reaches the right boundary. The movement is limited by the applicable terminal boundary.
Cursor Horizontal Absolute (CHA)
CHA stands for Cursor Horizontal Absolute. Unlike CUF, CHA does not specify a distance. Instead, it moves the cursor directly to a particular column while remaining on the current row, its structure is:
ESC [ n G
Where:
nspecifies the destination column, using one-based indexing.Gis the final byte identifying the Cursor Horizontal Absolute command.
For example:
printf("\x1b[13G");
This moves the cursor to column 13 without changing its row.
Before:
Column: 8 9 10 11 12 13 14
. . ▮ . . . .
After ESC[13G:
Column: 8 9 10 11 12 13 14
. . . . . ▮ .
Unlike CUF, CHA can move the cursor in either horizontal direction, for example, if the cursor is currently at column 13, we can move it back to column 5 using:
ESC[5G
CHA also has a default parameter of 1.
ESC[1G → ESC[G
Both instructions move the cursor to the first column of the current row.
| Sequence | Destination | Bytes |
|---|---|---|
ESC[G |
Column 1 | 3 |
ESC[5G |
Column 5 | 4 |
ESC[13G |
Column 13 | 5 |
ESC[120G |
Column 120 | 6 |
CHA sits somewhere between CUP and CUF in terms of the information required to describe a destination, it does not need the destination row, but it still needs the destination column.
Comparing CUP, CHA, and CUF
We now have three different commands for positioning the cursor, imagine that we are rendering a terminal interface and have just finished drawing a group of characters, the cursor is currently at row 5, column 10, and the next group of characters begins at row 5, column 13.
Column: 1 2 3 4 5 6 7 8 9 10 11 12 13
Row 5: . . . . . . . . . ▮ . . ★
│ │
Current Target
There are three ways to reach the destination.
| Command | Sequence | Bytes | Meaning |
|---|---|---|---|
| CUP | ESC[5;13H |
7 | Move to row 5, column 13 |
| CHA | ESC[13G |
5 | Move to column 13 on the current row |
| CUF | ESC[3C |
4 | Move three columns to the right |
All three commands produce the same cursor position in this particular situation, however, each command requires a different amount of information.
CUP: Destination row + destination column
CHA: Destination column
CUF: Distance from the current column
The more we know about the current state of the terminal, the less information we may need to send, in this example, choosing CUF instead of CUP reduces the instruction from seven bytes to four bytes, a reduction of approximately 42.9%, we have achieved this without changing the resulting cursor position.
Calculating the Length of Each Command
As we learned in the previous section, numerical parameters are represented as ASCII digits, therefore, we can calculate the length of each instruction without actually constructing it, for CUP, when both parameters are explicitly specified:
ESC [ row ; col H
length = 4 + digits(row) + digits(col)
For CHA:
ESC [ col G
length = 3 + digits(col)
For CUF:
ESC [ n C
length = 3 + digits(n)
These formulas describe sequences with explicit parameters, if we apply the default parameter optimization from the previous exercise, some sequences become even shorter, for example:
CHA to column 1:
ESC[1G = 4 bytes
ESC[G = 3 bytes
CUF by one column:
ESC[1C = 4 bytes
ESC[C = 3 bytes
When comparing commands, we need to account for these shorter representations as well, this allows us to calculate the actual cost of each candidate instruction before deciding which one to generate.
Understanding the Terminal’s Current State
There is an important difference between CUP and the other two movement commands:
-
CUP explicitly specifies both the row and column, so it does not require us to know the cursor’s previous position.
-
CHA does not specify the row, which means we need to know that the cursor is already on the correct row.
-
CUF specifies neither the row nor the destination column. We need to know both the current row and the current column to calculate the correct distance.
Imagine that we want to move to row 5, column 13, if we send:
ESC[3C
But the cursor is actually at row 5, column 7, the result will be:
Expected position: row 5, column 13
Actual position: row 5, column 10
The instruction itself is valid. The problem is that our assumption about the terminal’s current state is incorrect, every character drawn afterward could appear in the wrong position, this is why an efficient terminal renderer needs to maintain its own record of the terminal’s state.
Introducing the Cursor Cache
A cursor cache is an internal representation of where we believe the terminal’s cursor is currently positioned, a simple implementation might look like this:
struct cursor {
int x;
int y;
};
We can use zero-based coordinates internally, just as we did in the previous exercises.
struct cursor cur = {
.x = 9,
.y = 4
};
This represents row 5, column 10 in terminal coordinates, whenever we generate an instruction that moves the cursor, we update our internal representation accordingly, for example, after generating a CUF instruction that moves three columns to the right:
cur.x += 3;
Our internal cursor position now represents row 5, column 13, we can visualize the relationship between the renderer and the terminal like this:
The renderer does not need to ask the terminal for its cursor position after every instruction, instead, it calculates the expected position based on the instructions it generates, however, cursor movement commands are not the only operations that affect the cursor. Printing characters, handling control characters, line wrapping, and scrolling can also change its position, a reliable renderer must account for these operations as well, for now, we will focus on explicit cursor movement and assume that we are working within the terminal’s normal screen boundaries.
Handling an Unknown Cursor Position
Sometimes, we cannot reliably determine where the cursor is, for example:
- Our application has just started.
- Another component has written directly to the terminal.
- A terminal operation has failed or been interrupted.
- Our internal representation of the terminal is no longer reliable.
We can represent an unknown cursor position using a sentinel value:
struct cursor cur = {
.x = -1,
.y = -1
};
When the cursor position is unknown, we should not use relative movement instructions, we cannot calculate a reliable distance without knowing the starting position, instead, we can use CUP to establish a known position:
ESC[5;13H
Once that instruction has been successfully processed, assuming the terminal’s positioning modes and dimensions are known, we can update our cursor cache.
cur.x = 12;
cur.y = 4;
Now we can safely consider shorter instructions for subsequent movements, correctness must always come before optimization. Saving a few bytes is not useful if the resulting interface is rendered incorrectly.
Determining Which Movement Commands Are Allowed
Before comparing the byte lengths of different commands, we first need to determine which commands can correctly reach our destination, we can represent this decision using a simple decision tree.
- In the decision tree above, an unknown cursor position or a different row uses CUP.
- If the cursor is already at the target cell, skip movement.
- If the target column is to the left on the same row, use CR (for column 1), CHA, or CUP.
- If the target column is to the right on the same row, compare CUF, CHA, and CUP.
Notice that we do not immediately choose CUF simply because the target is to the right, instead, we identify all valid candidates and compare their lengths, we also introduce another important optimization: if the cursor is already at the destination, we do not need to generate a movement instruction at all, the cheapest instruction is sometimes no instruction.
Why Not Use Cursor Backward?
The terminal also provides a command called CUB, which stands for Cursor Backward, its structure is:
ESC[nD
It moves the cursor n columns to the left, for example:
ESC[3D
This moves the cursor three columns backward, however, imagine a renderer that processes each row from left to right.
Column: 1 2 3 4 5 6 7 8 9 10
A B C . . D E . . F
└─────┘ └───┘ │
Run 1 Run 2 Run 3
Rendering direction ──────────────────►
After rendering the first group of characters, the next group will generally be somewhere to the right, if our renderer processes non-overlapping runs in this order, there is little reason to move backward within the same row, we can therefore limit our initial movement candidates to CUP, CHA, and CUF, this does not mean CUB is useless. It simply means that our rendering strategy determines which commands are worth considering.
When Does CUF Become Cheaper?
Let’s compare several movements on the same row, assume that the cursor is currently on row 40 and that all the target positions are within the terminal’s boundaries.
| Current column | Target column | CUP | CHA | CUF |
|---|---|---|---|---|
| 10 | 13 | ESC[40;13H (8) |
ESC[13G (5) |
ESC[3C (4) |
| 10 | 25 | ESC[40;25H (8) |
ESC[25G (5) |
ESC[15C (5) |
| 5 | 105 | ESC[40;105H (9) |
ESC[105G (6) |
ESC[100C (6) |
| 95 | 105 | ESC[40;105H (9) |
ESC[105G (6) |
ESC[10C (5) |
| 99 | 100 | ESC[40;100H (9) |
ESC[100G (6) |
ESC[C (3) |
The numbers in parentheses represent the byte lengths, there is an interesting mathematical relationship between CHA and CUF, when moving to the right:
distance = target_column - current_column
Because the current column is at least 1, the distance is always smaller than the target column, therefore:
digits(distance) <= digits(target_column)
Since CHA and CUF have the same fixed overhead of three bytes when their parameters are explicit, CUF will never require more bytes than CHA for a valid forward movement, it will either be shorter or have the same length, omitting the default distance of 1 makes CUF even more efficient in certain situations.
When Does CHA Become Useful?
If CUF is always shorter than or equal to CHA when moving forward, why do we need CHA at all? the answer is that CUF can only move to the right, consider a cursor currently positioned at column 20, with a target at column 5 on the same row.
Column: 1 ... 5 ................ 20
★ ▮
◄───────────────────┘
CUF cannot perform this movement, however, CHA can move directly to the target column:
ESC[5G
This requires only four bytes, alternatively, assuming we are on row 40, CUP would require:
ESC[40;5H
This requires seven bytes, CHA is useful when we know the current row but need to move horizontally to a fixed destination, particularly when moving to the left, it can also be useful when the current column is unknown but the current row is known.
Moving to the First Column with Carriage Return
There is one particularly interesting horizontal movement that deserves special attention, suppose we want to move the cursor to the first column of the current row, using CHA, we can generate:
ESC[G
This requires three bytes, but remember the carriage return control character we learned about earlier?
'\r'
Carriage return moves the cursor to the beginning of the current line under normal terminal settings, its hexadecimal representation is:
0D
It requires only a single byte, assuming normal cursor positioning and terminal margins, we can compare the following instructions:
| Instruction | Meaning | Bytes |
|---|---|---|
ESC[40;1H |
Move to row 40, column 1 | 7 |
ESC[40H |
Move to row 40, column 1 | 5 |
ESC[1G |
Move to column 1 | 4 |
ESC[G |
Move to column 1 | 3 |
\r |
Return to the beginning of the current line | 1 |
When the cursor is already on row 40, all these instructions can produce the same destination under the assumed terminal settings, however, carriage return requires significantly fewer bytes, this is another example of why understanding the terminal protocol is important. Sometimes, the most efficient instruction is not even an escape sequence.
Trying the Commands Yourself
Let’s experiment with these commands directly in the terminal, first, clear the screen, position the cursor at row 5, column 10, and move it three columns forward.
printf '\x1b[2J\x1b[5;10H\x1b[3CX\x1b[7H\n'
You should see an X at row 5, column 13, now, replace CUF with CHA:
printf '\x1b[2J\x1b[5;10H\x1b[13GX\x1b[7H\n'
Finally, use CUP:
printf '\x1b[2J\x1b[5;10H\x1b[5;13HX\x1b[7H\n'
All three commands should place the character in the same position on a compatible terminal with sufficient rows and columns, the difference is not what they draw, but how they describe the movement, you can also test carriage return:
printf '\x1b[2J\x1b[5;10H\rX\x1b[7H\n'
This time, the X should appear at row 5, column 1 under normal terminal settings.
Putting It All Together
We now understand three different cursor movement commands and one useful control character.
| Command | Movement | Required cursor knowledge |
|---|---|---|
| CUP | Absolute row and column | None |
| CHA | Absolute column | Current row |
| CUF | Relative movement to the right | Current row and column |
| CR | Beginning of the current line | Current row |
CUP is the most general of these commands because it explicitly specifies the destination. However, it often requires more bytes, CHA allows us to avoid specifying the row when we already know that it is correct, CUF allows us to avoid specifying both destination coordinates when we know the cursor’s current position, carriage return provides an even shorter representation for returning to the beginning of the current line, the important principle is that we should not choose a movement instruction solely based on its length, We should first determine whether the instruction is valid given our current knowledge of the terminal, and only then compare its byte cost.
Know the current state
│
▼
Identify valid instructions
│
▼
Calculate their byte lengths
│
▼
Choose the shortest instruction
│
▼
Generate the instruction
│
▼
Update the cursor cache
This process will eventually become the foundation of our cursor movement optimizer, so far, we have been constructing terminal instructions based on where we want to draw something. We are now beginning to construct instructions based on both the desired result and the terminal’s existing state, that distinction is fundamental to building an efficient terminal rendering engine.
Building CUF and CHA and Comparing Cursor Movement Commands
In the previous section, we learned that CUP is not the only command available for moving the cursor. We can also use Cursor Forward (CUF) and Cursor Horizontal Absolute (CHA) to reach a destination using fewer bytes, however, understanding these commands theoretically is only the first step, in this exercise, we will implement our own CUF and CHA builders, just as we previously implemented CUP. We will then compare the generated sequences and measure how many bytes each command requires to reach the same destination, these three builders will eventually become the foundation of our cursor movement optimizer.
Revisiting the Three Cursor Movement Commands
Before writing any code, let’s recall the structure of each command.
| Command | Structure | Purpose |
|---|---|---|
| CUP | ESC[row;colH |
Move to a specific row and column |
| CHA | ESC[colG |
Move to a specific column on the current row |
| CUF | ESC[nC |
Move n columns to the right |
All three commands follow the same CSI structure that we learned earlier:
Introducer + Parameters + Final byte
The difference lies in the parameters and the final byte.
- CUP:
ESC[40;13H(8 bytes) - CHA:
ESC[13G(5 bytes) - CUF:
ESC[3C(4 bytes)
Since we already know how to convert integers into ASCII digits, implementing these additional commands should be relatively straightforward.
Reusing Our Integer Conversion Function
We will reuse the write_uint() function from the previous exercises.
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;
}
Recall that this function performs four operations:
- Extracts the last decimal digit using
% 10. - Converts the digit into an ASCII character by adding
'0'. - Removes the last digit using integer division.
- Reverses the extracted digits into their correct order.
The function returns the number of bytes written without appending a null terminator, this makes it particularly useful for constructing terminal instructions directly inside a memory buffer.
Building CUP
Let’s start with the cursor positioning function that we already implemented in the previous section.
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;
}
The function accepts zero-based coordinates and converts them into one-based terminal coordinates, for example:
cup(buf, 12, 39);
Produces:
ESC[40;13H
Notice that we are using the full representation of CUP for this exercise. We will leave default parameter optimization out for now so that we can focus on comparing the three different movement commands.
Building CHA
CHA is simpler than CUP because it only requires a single parameter: the destination column.
static size_t cha(char *p, unsigned int x) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(p + pos, x + 1);
p[pos++] = 'G';
return pos;
}
There is no row parameter and no semicolon, let’s follow what happens when we call:
cha(buf, 12);
| Operation | Bytes written | Buffer contents | Position |
|---|---|---|---|
| Write introducer | 1B 5B |
ESC [ |
2 |
| Write column | 31 33 |
ESC [ 1 3 |
4 |
| Write final byte | 47 |
ESC [ 1 3 G |
5 |
The resulting sequence is:
ESC[13G
It requires five bytes, as with CUP, we add 1 to x because our application uses zero-based coordinates, while CHA expects a one-based column number, the current row remains unchanged.
Building CUF
CUF follows almost exactly the same structure as CHA, however, instead of accepting a destination column, it accepts the number of columns to move forward.
static size_t cuf(char *p, unsigned int n) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(p + pos, n);
p[pos++] = 'C';
return pos;
}
For example:
cuf(buf, 3);
Produces:
ESC[3C
Let’s inspect the generated bytes.
| Operation | Bytes written | Buffer contents | Position |
|---|---|---|---|
| Write introducer | 1B 5B |
ESC [ |
2 |
| Write distance | 33 |
ESC [ 3 |
3 |
| Write final byte | 43 |
ESC [ 3 C |
4 |
The resulting instruction requires four bytes, there is one particularly important difference between this implementation and CHA, we do not add 1 to the parameter.
Understanding Position vs. Distance
One of the easiest mistakes to make when implementing cursor movement commands is confusing a position with a distance, CUP and CHA describe positions, while CUF describes a distance, imagine that the cursor is currently at column 10 and we want to move it to column 13.
Column: 10 11 12 13
▮ ──► . ──► . ──► ★
1 2 3
Distance: 3 columns
Internally, our zero-based coordinates are:
unsigned int from_x = 9;
unsigned int to_x = 12;
To construct CHA, we need to convert the destination into a one-based position.
unsigned int column = to_x + 1;
// column = 13
To construct CUF, we only need to calculate the difference between the two coordinates.
unsigned int distance = to_x - from_x;
// distance = 3
The distance is identical whether we use zero-based or one-based coordinates.
Zero-based: 12 - 9 = 3
One-based: 13 - 10 = 3
Adding 1 to the distance would be incorrect because it would move the cursor one column too far, the rule to remember is simple:
| Command | Parameter type | Add 1? |
|---|---|---|
| CUP | Position | Yes |
| CHA | Position | Yes |
| CUF | Distance | No |
This distinction will become increasingly important when we start tracking the cursor’s position and selecting movement commands dynamically.
Printing Escape Sequences Without Executing Them
In the previous exercises, we inspected our generated sequences by printing their hexadecimal representations, this time, let’s make the output easier to read by replacing the actual Escape character with the literal text ESC.
static void print_seq(
const char *label,
const char *s,
size_t n
) {
printf(" %-4s %2zu bytes ", label, n);
for (size_t i = 0; i < n; i++) {
if (s[i] == '\x1b') {
printf("ESC");
} else {
putchar(s[i]);
}
}
printf("\n");
}
Normally, sending the Escape character followed by a valid CSI sequence causes the terminal to interpret it as an instruction, instead, this function displays a readable representation of the sequence.
Actual bytes:
1B 5B 33 43
Readable representation:
ESC[3C
Remember that ESC in our displayed representation consists of three printable characters, but the actual Escape character occupies only one byte, the reported length comes from the original buffer, not from its readable representation.
Comparing the Three Builders
Now that we have implemented all three commands, we can create a function that compares them.
static void compare(
unsigned int y,
unsigned int from_x,
unsigned int to_x
) {
char a[24];
char b[24];
char c[24];
size_t na = cup(a, to_x, y);
size_t nb = cha(b, to_x);
size_t nc = cuf(c, to_x - from_x);
printf(
"row %u: col %u -> col %u\n",
y + 1,
from_x + 1,
to_x + 1
);
print_seq("CUP", a, na);
print_seq("CHA", b, nb);
print_seq("CUF", c, nc);
}
The function receives three values:
y: The current row.from_x: The current column.to_x: The destination column.
All three values use zero-based coordinates, for this exercise, we assume that the destination is on the same row and strictly to the right of the current cursor position. This ensures that all three movement commands are valid candidates, each builder writes its instruction into a separate buffer and returns its exact length.
We are not yet automatically selecting the shortest instruction. For now, we simply generate all three candidates and inspect their costs.
Putting Everything Together
Create a file called cursor_moves.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 cha(char *p, unsigned int x) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(p + pos, x + 1);
p[pos++] = 'G';
return pos;
}
static size_t cuf(char *p, unsigned int n) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(p + pos, n);
p[pos++] = 'C';
return pos;
}
static void print_seq(
const char *label,
const char *s,
size_t n
) {
printf(" %-4s %2zu bytes ", label, n);
for (size_t i = 0; i < n; i++) {
if (s[i] == '\x1b') {
printf("ESC");
} else {
putchar(s[i]);
}
}
printf("\n");
}
static void compare(
unsigned int y,
unsigned int from_x,
unsigned int to_x
) {
char a[24];
char b[24];
char c[24];
size_t na = cup(a, to_x, y);
size_t nb = cha(b, to_x);
size_t nc = cuf(c, to_x - from_x);
printf(
"row %u: col %u -> col %u\n",
y + 1,
from_x + 1,
to_x + 1
);
print_seq("CUP", a, na);
print_seq("CHA", b, nb);
print_seq("CUF", c, nc);
}
int main(void) {
compare(39, 9, 12);
compare(39, 9, 24);
compare(39, 4, 104);
compare(39, 94, 104);
return 0;
}
Predicting the Results
Before compiling and running the program, try calculating the expected byte lengths yourself, recall the formulas from the previous section:
CUP = 4 + digits(row) + digits(column)
CHA = 3 + digits(column)
CUF = 3 + digits(distance)
These formulas apply to the explicit-parameter representations used in this exercise, all four examples take place on row 40.
| Current column | Target column | Distance |
|---|---|---|
| 10 | 13 | 3 |
| 10 | 25 | 15 |
| 5 | 105 | 100 |
| 95 | 105 | 10 |
For each movement, calculate the length of all three commands and predict which one will require the fewest bytes, try doing this before looking at the expected output.
Running the Program
Compile the program:
cc -std=c11 -Wall -o cursor_moves cursor_moves.c
Then execute it:
./cursor_moves
You should see the following output:
row 40: col 10 -> col 13
CUP 8 bytes ESC[40;13H
CHA 5 bytes ESC[13G
CUF 4 bytes ESC[3C
row 40: col 10 -> col 25
CUP 8 bytes ESC[40;25H
CHA 5 bytes ESC[25G
CUF 5 bytes ESC[15C
row 40: col 5 -> col 105
CUP 9 bytes ESC[40;105H
CHA 6 bytes ESC[105G
CUF 6 bytes ESC[100C
row 40: col 95 -> col 105
CUP 9 bytes ESC[40;105H
CHA 6 bytes ESC[105G
CUF 5 bytes ESC[10C
Compare these results with your predictions.
Understanding the Results
Let’s examine each movement individually.
Case 1: Column 10 to Column 13
CUP: ESC[40;13H 8 bytes
CHA: ESC[13G 5 bytes
CUF: ESC[3C 4 bytes
CUF wins because the distance is represented using only one decimal digit, while the destination column requires two, we save four bytes compared to CUP, reducing the instruction size by 50%.
Case 2: Column 10 to Column 25
CUP: ESC[40;25H 8 bytes
CHA: ESC[25G 5 bytes
CUF: ESC[15C 5 bytes
CHA and CUF have the same length, although the distance is smaller than the destination column, both numbers require two decimal digits, this demonstrates that a smaller numerical value does not necessarily produce a shorter escape sequence, what matters is the number of digits required to represent it.
Case 3: Column 5 to Column 105
CUP: ESC[40;105H 9 bytes
CHA: ESC[105G 6 bytes
CUF: ESC[100C 6 bytes
Once again, CHA and CUF have the same length because both parameters require three decimal digits, even though CUF describes a relative movement, it does not automatically produce a shorter instruction than CHA.
Case 4: Column 95 to Column 105
CUP: ESC[40;105H 9 bytes
CHA: ESC[105G 6 bytes
CUF: ESC[10C 5 bytes
CUF wins because the destination column requires three digits, while the distance requires only two, notice that cases 3 and 4 have exactly the same destination, however, their relative movement instructions have different lengths because the cursor starts at a different position, this is precisely why tracking the current cursor position is valuable.
Measuring the Byte Savings
Let’s summarize the results.
| Movement | CUP | CHA | CUF | Shortest |
|---|---|---|---|---|
| 10 → 13 | 8 | 5 | 4 | CUF |
| 10 → 25 | 8 | 5 | 5 | Tie |
| 5 → 105 | 9 | 6 | 6 | Tie |
| 95 → 105 | 9 | 6 | 5 | CUF |
| Total | 34 | 22 | 20 | 20 |
If we always use CUP, these four movement instructions require a total of 34 bytes, if we choose the shortest valid instruction for each movement, we only need 20 bytes.
Bytes saved = 34 - 20
= 14 bytes
Reduction = (14 / 34) × 100
≈ 41.18%
We have reduced the combined size of these movement instructions by approximately 41.2%, unlike our previous optimization, which removed unnecessary default parameters, this optimization works by selecting an entirely different command, the result is the same cursor position, but the information required to describe the movement is different.
Why Not Always Use CUF?
Looking at our results, you might wonder why we should not simply use CUF for every cursor movement, after all, CUF was either the shortest command or tied with CHA in every example, however, remember the assumptions we made at the beginning of this exercise, CUF is only a valid candidate when:
- The current cursor position is known.
- The cursor is already on the target row.
- The destination is to the right of the current cursor.
- The movement remains within the applicable terminal boundaries.
Consider the following movement:
Column: 5 6 7 8 9 10
★ ▮
◄──────────────┘
We cannot use CUF to move from column 10 to column 5, attempting to calculate the distance using unsigned integers would also cause the subtraction to wrap around to a large value, similarly, if the current cursor position is already equal to the destination, we should not generate ESC[0C. Terminals commonly interpret a zero CUF parameter as the default movement of one column, instead, we should generate no movement instruction at all, these limitations demonstrate why our future movement optimizer must first determine which commands are valid before comparing their byte lengths.
Challenge Yourself
Try adding these movements to your program:
compare(39, 0, 8);
compare(39, 8, 9);
compare(39, 98, 99);
compare(39, 99, 199);
For each movement, predict:
- The one-based destination column.
- The distance between the current and destination columns.
- The generated CUP, CHA, and CUF sequences.
- The byte length of each sequence.
- Which command requires the fewest bytes.
As an additional challenge, modify your CUF builder to omit the parameter when the distance is exactly 1.
ESC[1C → ESC[C
Do the same for CHA when the destination column is 1.
ESC[1G → ESC[G
These changes combine what we learned in the previous section with our new cursor movement commands.
Putting It All Together
In this exercise, we implemented three different cursor movement builders using the same underlying CSI structure, we learned that CUP and CHA describe positions, while CUF describes a distance. This distinction determines how we convert our internal coordinates into terminal parameters, we also discovered that the cost of a relative movement depends on the cursor’s current position, not just its destination, by comparing the three commands, we reduced the combined size of four movement instructions from 34 bytes to 20 bytes, more importantly, we now have three independent builders that can generate different instructions for reaching the same destination, the next step is to stop making these comparisons manually and teach our program how to identify valid movement commands, calculate their costs, and select the most efficient one automatically, this is where our individual escape sequence builders begin to evolve into a cursor movement optimizer.
Automatically Choosing the Most Efficient Cursor Movement
In the previous exercise, we implemented three different cursor movement commands: CUP, CHA, and CUF. We generated their escape sequences, compared their byte lengths, and manually determined which instruction was the most efficient, however, a terminal rendering engine cannot rely on a human to make these decisions, during rendering, an application may need to move the cursor many times within a single frame. Each movement may have different characteristics depending on the current cursor position and the destination, what if we could teach our program to make these decisions automatically? In this exercise, we will build a simple cursor movement optimizer that identifies valid movement commands, compares their byte lengths, and selects the most efficient one.
From Escape Sequence Builders to an Optimizer
Until now, our escape sequence builders have been responsible for generating individual terminal instructions.
cup() → Absolute row and column
cha() → Absolute column
cuf() → Relative forward movement
Each builder knows how to construct its own instruction, but none of them knows whether it is the most efficient instruction for a particular situation, instead of adding this responsibility to each builder, we will introduce a separate function called best_move().
This separates two responsibilities:
- The builders are responsible for encoding terminal instructions.
- The optimizer is responsible for deciding which instruction to use.
This separation allows us to improve our decision-making logic without changing the underlying escape sequence builders.
Defining the Decision Rules
Before implementing the optimizer, we need to establish the rules that determine which instructions are valid, remember that choosing the shortest instruction is only useful if that instruction reaches the correct destination, our optimizer will follow this decision tree:
- If the cursor position is unknown or on a different row, use CUP.
- If the cursor is already at the target cell, emit no instruction (0 bytes).
- If on the same row and the target column is 1, use CR (1 byte).
- If on the same row and the target is to the left, compare CUP and CHA.
- If on the same row and the target is to the right, compare CUP, CHA, and CUF.
This decision tree is the foundation of our optimizer, notice that we determine which instructions are allowed before comparing their lengths, a shorter instruction that moves the cursor to the wrong position is not an optimization.
Designing the Optimizer Interface
Let’s begin by defining the function signature.
static size_t best_move(
char *p,
int cx,
int cy,
int x,
int y,
const char **name
);
The function accepts the following parameters:
| Parameter | Purpose |
|---|---|
p |
Destination buffer |
cx |
Current cursor column |
cy |
Current cursor row |
x |
Target column |
y |
Target row |
name |
Name of the selected instruction |
All coordinates use zero-based indexing, unlike our previous exercises, we use signed integers for coordinates because we want to represent an unknown cursor position using a negative value, for example:
int cx = -1;
int cy = -1;
The function returns the number of bytes written into the destination buffer, it also returns the name of the selected instruction through the name parameter, allowing us to inspect the optimizer’s decision.
Understanding the Pointer to a Pointer
You might have noticed something unusual in the function signature:
const char **name
Why do we need two pointer operators? Our function already returns a size_t representing the number of generated bytes. However, we also want to return the name of the selected command, in C, we can accomplish this by passing the address of a variable that the function can modify, consider this example:
const char *name;
size_t n = best_move(
buf,
9, 39,
12, 39,
&name
);
The variable name is a pointer to a string. By passing &name, we provide the address of that pointer, inside best_move(), we can modify the caller’s pointer:
*name = "CUF";
We can visualize the relationship like this:
Inside best_move()
name
│
▼
┌──────────────────┐
│ Caller's pointer │
└────────┬─────────┘
│
▼
"CUF\0"
After the function returns, the caller can access both results.
printf("%s: %zu bytes\n", name, n);
The output might be:
CUF: 4 bytes
This is a common technique in C for returning additional information through function parameters.
Step 1: Avoid Unnecessary Movement
The first optimization does not require any escape sequence at all, suppose the cursor is already at the destination.
Current: (5, 9)
Target: (5, 9)
There is no reason to send a movement instruction.
if (cx == x && cy == y) {
*name = "none";
return 0;
}
Returning zero indicates that no bytes were written into the destination buffer, this might seem obvious, but avoiding unnecessary operations is one of the most important principles of performance optimization, for example, imagine drawing two adjacent groups of characters.
Column: 1 2 3 4 5 6
A B C ▮ . .
│
Next character starts here
After printing ABC, the cursor is already at column 4, if our next character also needs to be drawn at column 4, we can simply continue writing, we do not need CUP, CHA, or CUF, the cost of this movement is zero bytes.
Step 2: Establish a Safe Fallback
If movement is necessary, we begin by constructing a CUP sequence.
size_t best = cup(p, x, y);
*name = "CUP";
Why start with CUP? Because CUP specifies both the destination row and column. Under our assumed terminal positioning modes, it can reach the destination without knowing the cursor’s previous position, at this point, we have a valid instruction stored in our destination buffer, we also know its byte length.
Destination buffer:
┌─────┬───┬───┬───┬───┬───┬───┬───┐
│ ESC │ [ │ 4 │ 0 │ ; │ 1 │ 3 │ H │
└─────┴───┴───┴───┴───┴───┴───┴───┘
best = 8
name = "CUP"
CUP becomes our initial candidate, or our best solution so far, as we discover other valid instructions, we can replace it if we find something cheaper, this is a simple minimum-selection algorithm.
Step 3: Check Whether Other Commands Are Allowed
Next, we need to determine whether horizontal movement commands can reach the destination.
if (cx < 0 || cy != y) {
return best;
}
There are two situations where we immediately return the CUP sequence, the first is when the current cursor position is unknown.
Current: (?, ?)
Target: (12, 39)
We cannot safely calculate a relative distance or assume that the cursor is on the correct row, the second situation is when the destination is on a different row.
Current: (3, 9)
Target: (5, 4)
Neither CHA nor CUF changes the row, therefore, neither command can reach the destination, among the commands considered in this exercise, CUP is the only valid option in both situations, by returning immediately, we also avoid constructing unnecessary candidate instructions.
Step 4: Use Carriage Return When Possible
If we reach this part of the function, we know that the cursor is already on the target row, now we can check whether the target is the first column.
if (x == 0) {
p[0] = '\r';
*name = "CR";
return 1;
}
Remember that our coordinates are zero-based, so x == 0 represents terminal column 1, under normal terminal settings, carriage return moves the cursor to the beginning of the current line.
Before:
Column: 1 2 3 4 5 6
. . . . ▮ .
After CR:
Column: 1 2 3 4 5 6
▮ . . . . .
The carriage return character requires only one byte.
Hexadecimal: 0D
Compare this with the other available instructions for moving to column 1 on row 40.
| Instruction | Sequence | Bytes |
|---|---|---|
| CUP | ESC[40;1H |
7 |
| Short CUP | ESC[40H |
5 |
| CHA | ESC[1G |
4 |
| Short CHA | ESC[G |
3 |
| CR | \r |
1 |
Since we have already handled the zero-byte case, a one-byte instruction is the cheapest possible non-empty instruction in our byte stream, there is no need to compare any other candidates, we can return immediately.
Step 5: Consider CHA
If the destination is not the first column, we can construct a CHA sequence.
char tmp[24];
size_t n = cha(tmp, x);
Because we already know that the cursor is on the correct row, CHA is a valid candidate, notice that we write the candidate into a temporary buffer instead of overwriting the destination buffer immediately, why? Our destination buffer already contains a valid CUP sequence. We should only replace it if the new candidate is cheaper.
if (n < best) {
memcpy(p, tmp, n);
best = n;
*name = "CHA";
}
Suppose we are moving from column 10 to column 13 on row 40, our initial CUP sequence is:
ESC[40;13H
8 bytes
The CHA builder generates:
ESC[13G
5 bytes
Since five is smaller than eight, we replace the current best instruction.
Before comparison:
p: ESC[40;13H
best: 8
name: CUP
Candidate:
tmp: ESC[13G
n: 5
After comparison:
p: ESC[13G
best: 5
name: CHA
Although the original CUP sequence occupied more space, we do not need to erase the remaining bytes in the destination buffer, the returned length determines how many bytes are valid, anything beyond that length will not be transmitted to the terminal.
Step 6: Consider CUF
Finally, we check whether the destination is to the right of the current cursor.
if (x > cx) {
n = cuf(tmp, x - cx);
if (n < best) {
memcpy(p, tmp, n);
best = n;
*name = "CUF";
}
}
The condition is important because CUF can only move forward, if the destination is to the left, CUF is not a valid candidate, if the destination is to the right, we calculate the distance.
x - cx
Remember that this is a distance, not a position. We do not add 1, continuing with our previous example:
Current column: 10
Target column: 13
Distance: 13 - 10 = 3
The CUF builder generates:
ESC[3C
4 bytes
Our current best candidate is CHA, which requires five bytes, since four is smaller than five, we replace CHA with CUF.
CUP (8 bytes)
│
▼
CHA (5 bytes)
│
▼
CUF (4 bytes)
│
▼
Selected instruction
The optimizer has successfully selected the cheapest valid instruction.
Understanding Tie-Breaking
What happens when two commands require exactly the same number of bytes? Consider moving from column 10 to column 25.
CUP: ESC[40;25H 8 bytes
CHA: ESC[25G 5 bytes
CUF: ESC[15C 5 bytes
Both CHA and CUF require five bytes, our comparison uses the less-than operator:
if (n < best)
It does not use:
if (n <= best)
This means that a candidate only replaces the current best instruction when it is strictly cheaper, since we evaluate CHA before CUF, CHA remains selected when their lengths are equal.
Initial candidate: CUP (8 bytes)
CHA (5 bytes):
5 < 8 → true
Replace CUP with CHA.
CUF (5 bytes):
5 < 5 → false
Keep CHA.
This gives our optimizer a deterministic tie-breaking policy, when the byte costs are equal, we prefer CHA over CUF, one reasonable motivation for this policy is that CHA specifies an absolute column rather than depending on the current column to calculate a relative movement, however, this does not mean CHA is necessarily faster for the terminal to process. We are only defining a consistent preference between equally sized instructions.
Implementing the Complete Optimizer
Now we can combine all the decision rules into a single function.
static size_t best_move(
char *p,
int cx,
int cy,
int x,
int y,
const char **name
) {
// Already at the destination.
if (cx == x && cy == y) {
*name = "none";
return 0;
}
// Start with a safe candidate.
size_t best = cup(p, x, y);
*name = "CUP";
// Unknown position or a different row.
if (cx < 0 || cy < 0 || cy != y) {
return best;
}
// Return to the beginning of the current row.
if (x == 0) {
p[0] = '\r';
*name = "CR";
return 1;
}
char tmp[24];
// Consider horizontal absolute movement.
size_t n = cha(tmp, x);
if (n < best) {
memcpy(p, tmp, n);
best = n;
*name = "CHA";
}
// Consider relative forward movement.
if (x > cx) {
n = cuf(tmp, x - cx);
if (n < best) {
memcpy(p, tmp, n);
best = n;
*name = "CUF";
}
}
return best;
}
The function does not need to know anything about the content being rendered, it only needs to know the current cursor position and the desired destination, this makes it reusable across different rendering operations.
Putting Everything Together
Create a file called best_move.c:
#include <stdio.h>
#include <string.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, int x, int y) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(
p + pos, (unsigned int)y + 1
);
p[pos++] = ';';
pos += (size_t)write_uint(
p + pos, (unsigned int)x + 1
);
p[pos++] = 'H';
return pos;
}
static size_t cha(char *p, int x) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(
p + pos, (unsigned int)x + 1
);
p[pos++] = 'G';
return pos;
}
static size_t cuf(char *p, int n) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(
p + pos, (unsigned int)n
);
p[pos++] = 'C';
return pos;
}
static size_t best_move(
char *p,
int cx,
int cy,
int x,
int y,
const char **name
) {
if (cx == x && cy == y) {
*name = "none";
return 0;
}
size_t best = cup(p, x, y);
*name = "CUP";
if (cx < 0 || cy < 0 || cy != y) {
return best;
}
if (x == 0) {
p[0] = '\r';
*name = "CR";
return 1;
}
char tmp[24];
size_t n = cha(tmp, x);
if (n < best) {
memcpy(p, tmp, n);
best = n;
*name = "CHA";
}
if (x > cx) {
n = cuf(tmp, x - cx);
if (n < best) {
memcpy(p, tmp, n);
best = n;
*name = "CUF";
}
}
return best;
}
static void show(int cx, int cy, int x, int y) {
char seq[24];
const char *name;
size_t n = best_move(
seq, cx, cy, x, y, &name
);
printf(
"(%3d,%3d) -> (%3d,%3d) %-4s %zu bytes ",
cx, cy, x, y, name, n
);
for (size_t i = 0; i < n; i++) {
if (seq[i] == '\x1b') {
printf("ESC");
} else if (seq[i] == '\r') {
printf("\\r");
} else {
putchar(seq[i]);
}
}
printf("\n");
}
int main(void) {
// Unknown cursor position.
show(-1, -1, 5, 9);
// Different row.
show(3, 9, 5, 4);
// Return to column 1.
show(9, 39, 0, 39);
// Short forward movement.
show(9, 39, 12, 39);
// CHA and CUF have equal costs.
show(9, 39, 24, 39);
// Short movement to a large column.
show(94, 39, 104, 39);
// Moving backward.
show(50, 39, 20, 39);
// Already at the destination.
show(5, 9, 5, 9);
return 0;
}
As in the previous exercise, we print a readable representation of the generated escape sequences instead of executing them, this allows us to inspect the optimizer’s decisions without changing the actual cursor position.
Predicting the Results
Before running the program, try following the decision tree manually for each of the eight cases.
| Current position | Target position | Situation |
|---|---|---|
| (-1, -1) | (5, 9) | Unknown cursor position |
| (3, 9) | (5, 4) | Different row |
| (9, 39) | (0, 39) | Return to first column |
| (9, 39) | (12, 39) | Short forward movement |
| (9, 39) | (24, 39) | Equal candidate costs |
| (94, 39) | (104, 39) | Short distance to a large column |
| (50, 39) | (20, 39) | Backward movement |
| (5, 9) | (5, 9) | No movement required |
For each case, determine:
- Which commands are valid?
- How many bytes does each valid command require?
- Which command will the optimizer select?
- What escape sequence will it generate?
Remember that all coordinates in this table are zero-based.
Running the Program
Compile and execute the program:
cc -std=c11 -Wall -Wextra -o best_move best_move.c
./best_move
You should see the following output:
( -1, -1) -> ( 5, 9) CUP 7 bytes ESC[10;6H
( 3, 9) -> ( 5, 4) CUP 6 bytes ESC[5;6H
( 9, 39) -> ( 0, 39) CR 1 bytes \r
( 9, 39) -> ( 12, 39) CUF 4 bytes ESC[3C
( 9, 39) -> ( 24, 39) CHA 5 bytes ESC[25G
( 94, 39) -> (104, 39) CUF 5 bytes ESC[10C
( 50, 39) -> ( 20, 39) CHA 5 bytes ESC[21G
( 5, 9) -> ( 5, 9) none 0 bytes
Let’s examine why each instruction was selected.
Analyzing the Optimizer’s Decisions
Case 1: Unknown Cursor Position
(-1, -1) → (5, 9)
Since the current position is unknown, the optimizer cannot safely use horizontal or relative movement, it selects CUP.
ESC[10;6H
7 bytes
This establishes an absolute cursor position without relying on its previous location.
Case 2: Moving to a Different Row
(3, 9) → (5, 4)
The cursor needs to move from row 10 to row 5, neither CHA nor CUF can change the row, so the optimizer selects CUP.
ESC[5;6H
6 bytes
Case 3: Returning to the First Column
(9, 39) → (0, 39)
The cursor is already on the correct row, and the destination is column 1, the optimizer selects carriage return.
\r
1 byte
There is no need to construct another candidate.
Case 4: A Short Forward Movement
(9, 39) → (12, 39)
The cursor moves from column 10 to column 13.
CUP: ESC[40;13H 8 bytes
CHA: ESC[13G 5 bytes
CUF: ESC[3C 4 bytes
CUF is the cheapest valid instruction.
Case 5: Equal Candidate Costs
(9, 39) → (24, 39)
The cursor moves from column 10 to column 25.
CUP: ESC[40;25H 8 bytes
CHA: ESC[25G 5 bytes
CUF: ESC[15C 5 bytes
CHA and CUF have the same cost, because our optimizer only replaces a candidate when the new instruction is strictly cheaper, CHA remains selected.
Case 6: A Short Movement to a Large Column
(94, 39) → (104, 39)
The cursor moves from column 95 to column 105.
CUP: ESC[40;105H 9 bytes
CHA: ESC[105G 6 bytes
CUF: ESC[10C 5 bytes
Although the destination column requires three decimal digits, the relative distance only requires two, CUF wins.
Case 7: Moving Backward
(50, 39) → (20, 39)
The cursor moves from column 51 to column 21, since the destination is to the left, CUF is not a valid candidate.
CUP: ESC[40;21H 8 bytes
CHA: ESC[21G 5 bytes
CUF: Not allowed
The optimizer selects CHA.
Case 8: Already at the Destination
(5, 9) → (5, 9)
The cursor is already at the desired position, the optimizer generates no instruction.
0 bytes
This is the cheapest possible result.
Measuring the Overall Optimization
Now that our optimizer can make decisions automatically, let’s compare its output size with an implementation that always generates a full CUP instruction.
| Situation | Full CUP | Selected command | Optimized bytes | Bytes saved |
|---|---|---|---|---|
| Unknown position | 7 | CUP | 7 | 0 |
| Different row | 6 | CUP | 6 | 0 |
| First column | 7 | CR | 1 | 6 |
| Short forward movement | 8 | CUF | 4 | 4 |
| Equal candidate costs | 8 | CHA | 5 | 3 |
| Large destination column | 9 | CUF | 5 | 4 |
| Backward movement | 8 | CHA | 5 | 3 |
| Already at destination | 7 | None | 0 | 7 |
| Total | 60 | 33 | 27 |
The total number of bytes has decreased from 60 to 33.
Bytes saved = 60 - 33
= 27 bytes
Reduction = (27 / 60) × 100
= 45%
Across these eight independent movement scenarios, our optimizer produces 45% fewer bytes than an implementation that always uses full CUP sequences, we have achieved this by combining several techniques:
- Avoiding unnecessary cursor movement.
- Using carriage return when appropriate.
- Using horizontal absolute movement.
- Using relative forward movement.
- Falling back to absolute positioning when necessary.
The actual savings in a rendering engine will depend on the distribution of cursor movements.
Understanding the Cost of Our Optimizer
Although our optimizer produces shorter output sequences, there is still room for improvement in how it makes decisions, consider what happens during a forward movement.
1. Construct CUP.
2. Construct CHA.
3. Compare CHA with CUP.
4. Copy CHA if it is cheaper.
5. Construct CUF.
6. Compare CUF with the current best.
7. Copy CUF if it is cheaper.
In some cases, we construct three different escape sequences even though only one will eventually be transmitted to the terminal, we may also perform unnecessary memory copies, this introduces another interesting optimization problem, do we actually need to construct an escape sequence to determine its length? Recall the formulas from the previous section:
CUP = 4 + digits(row) + digits(column)
CHA = 3 + digits(column)
CUF = 3 + digits(distance)
We already know how to calculate the cost of each instruction without constructing it, for example:
Current column: 10
Target column: 13
Current row: 40
CUP cost = 4 + 2 + 2 = 8
CHA cost = 3 + 2 = 5
CUF cost = 3 + 1 = 4
We could compare these values first and then construct only the winning instruction.
Current implementation:
Build candidates
│
▼
Measure lengths
│
▼
Select winner
│
▼
Keep winning sequence
Potential improvement:
Calculate candidate costs
│
▼
Select winner
│
▼
Build winning sequence
The second approach avoids constructing instructions that will never be used, however, we would also need to account for omitted default parameters when calculating the costs, for now, our current implementation is useful because it is simple, easy to inspect, and allows us to verify the correctness of our decision-making logic, we can optimize the implementation further once we are confident that it behaves correctly.
Challenge Yourself
Try adding the following cases to your program:
show(0, 0, 1, 0);
show(98, 39, 99, 39);
show(99, 39, 98, 39);
show(20, 10, 0, 10);
show(-1, -1, 0, 0);
Predict which instruction will be selected before running the program, then try combining the optimizer with the default parameter optimization from the previous section, for example:
ESC[1;1H → ESC[H
ESC[1C → ESC[C
ESC[1G → ESC[G
Our current builders always include explicit parameters. By introducing shortened representations, we can reduce the output size even further, as an additional challenge, try implementing a function that counts the number of decimal digits in an integer.
static size_t count_digits(unsigned int v);
Use this function to calculate the cost of each candidate without constructing its escape sequence, can you modify best_move() so that it generates only the selected instruction?
Putting It All Together
In this exercise, we transformed our individual escape sequence builders into a simple cursor movement optimizer, instead of always generating an absolute cursor positioning instruction, our program now considers the terminal’s current state, identifies valid movement commands, and selects the cheapest available option, across our eight test scenarios, we reduced the total output size from 60 bytes to 33 bytes, a reduction of 45%, more importantly, we have established a general optimization strategy:
Understand the current state
│
▼
Identify valid operations
│
▼
Evaluate their costs
│
▼
Select the cheapest operation
│
▼
Generate the instruction
This principle extends beyond cursor movement, later, we can apply similar reasoning to changing text colors, modifying text attributes, updating screen regions, and deciding which characters actually need to be transmitted to the terminal, an efficient terminal rendering engine is not simply a collection of escape sequence builders. It is a system that understands the terminal’s current state and uses that knowledge to avoid unnecessary work, we have now built the first piece of that system.
Rendering a Frame with a Paint Cache
Throughout the previous sections, we have explored several fundamental techniques for optimizing terminal rendering, we learned how to construct an output buffer, generate escape sequences manually, calculate their byte lengths, and select the most efficient cursor movement instruction, so far, however, our cursor movement optimizer has relied on the caller to provide the current cursor position, in a real rendering engine, we cannot manually provide this information every time we want to draw something. The renderer needs to maintain its own understanding of the terminal’s current state, in this exercise, we will combine everything we have learned so far and introduce a new concept: the paint cache, our goal is to render the same frame using two different strategies:
- Always use absolute cursor positioning (CUP).
- Track the cursor position and dynamically select the cheapest valid movement instruction.
We will then compare the number of bytes generated by both strategies.
Understanding Runs of Characters
Before implementing our renderer, let’s define the content we want to draw, imagine a simple terminal interface that looks like this:
Title 12:00
a b c
done
Although this interface occupies several rows and columns, we do not necessarily need to write every cell individually, instead, we can represent the content as groups of consecutive characters, we will call each group a run.
- Row 1 has Run 1
"Title"at column 0 and Run 2"12:00"at column 20. - Row 3 has Run 3
"a"at column 0, Run 4"b"at column 4, and Run 5"c"at column 8. - Row 5 has Run 6
"done"at column 0.
Each run contains three pieces of information:
- The starting column.
- The starting row.
- The characters to draw.
We can represent this information using a simple C structure.
struct run {
int x, y;
const char *text;
};
Both x and y use zero-based coordinates, our frame can now be represented as an array of runs:
static const struct run runs[] = {
{0, 0, "Title"},
{20, 0, "12:00"},
{0, 2, "a"},
{4, 2, "b"},
{8, 2, "c"},
{0, 4, "done"},
};
For each run, our renderer needs to move the cursor to its starting position and write its text, in a more advanced rendering engine, these runs could be generated by comparing the previous frame with the current frame and identifying groups of changed cells, for now, we define them manually so that we can focus on the rendering process itself.
Introducing the Paint Cache
In the previous exercise, our movement optimizer accepted the current cursor position as an argument.
best_move(buf, cx, cy, x, y, &name);
But where should cx and cy come from? One possible approach would be to ask the terminal for its cursor position before every movement, some terminals support a cursor position report through the following request:
ESC[6n
However, repeatedly querying the terminal would introduce additional communication, require us to read and parse its responses, and potentially introduce unnecessary waiting, instead, we can calculate the cursor position ourselves, because our renderer controls the instructions being sent to the terminal, it can predict how those instructions affect the cursor, this internal representation of the terminal’s state is what we call a paint cache, for this exercise, our paint cache only tracks two values:
int cx;
int cy;
These represent the cursor’s expected column and row, a more complete paint cache could eventually track other terminal state, such as foreground color, background color, text attributes, and whether the cursor is visible, but for now, tracking the cursor position is enough.
Extending Our Output Buffer
In the earlier exercises, our output buffer looked like this:
struct out {
char buf[512];
size_t len;
};
It stored the generated bytes and tracked how many bytes had been written, now, let’s extend it to include our cursor cache.
struct out {
char buf[512];
size_t len;
int cx;
int cy;
};
This structure now represents two different kinds of information.
The buffer describes what we intend to send to the terminal, the paint cache describes what we expect the terminal’s state to become after processing those bytes, this distinction is important, while we are constructing the buffer, the actual terminal has not necessarily received any of our instructions yet. Our cache represents the predicted state at the end of the buffered instruction stream.
Tracking the Cursor After Writing Text
One of the most important details in terminal rendering is that printing characters also moves the cursor, consider the following operation:
printf("Title");
Assuming the cursor starts at the first column, each printable ASCII character advances it by one column.
Before:
Column: 1 2 3 4 5 6 7
▮ . . . . . .
After writing "Title":
Column: 1 2 3 4 5 6 7
T i t l e ▮ .
The cursor has moved five columns to the right, using zero-based coordinates:
Before: (0, 0)
After: (5, 0)
Our renderer must account for this movement, let’s update the put_text() function from our previous exercises.
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;
o->cx += (int)n;
}
The first two operations should already be familiar:
memcpy(o->buf + o->len, s, n);
o->len += n;
They append the text to our output buffer and update its length, the new operation is:
o->cx += (int)n;
This updates our predicted cursor position, suppose we append the string "Title".
Before:
len = 6
cx = 0
cy = 0
Append "Title":
len = 11
cx = 5
cy = 0
We have updated both the output stream and our understanding of the terminal’s state.
Bytes Are Not Always Columns
There is an important limitation in our current implementation, we are assuming that every byte written advances the cursor by exactly one column, this assumption works for the printable ASCII characters used in this exercise, provided that the text does not reach the terminal’s right boundary, however, it does not work for arbitrary text, consider the following examples:
| Character | UTF-8 bytes | Typical terminal columns |
|---|---|---|
A |
1 | 1 |
é |
2 | 1 |
界 |
3 | 2 |
| Combining acute accent | 2 | 0 |
The number of bytes required to encode a character is not necessarily equal to its display width, for example:
strlen("界");
Returns 3 when the string is encoded using UTF-8, even though the character typically occupies two terminal columns, control characters introduce additional complexity. A newline, carriage return, or tab can change the cursor position in ways that cannot be calculated by simply adding the number of bytes, line wrapping introduces another problem, therefore, a complete terminal renderer needs to distinguish between:
Number of bytes written
≠
Number of characters
≠
Number of terminal columns occupied
For this exercise, we deliberately restrict our text to printable ASCII characters that fit within the current row, this allows us to focus on the fundamental mechanism of tracking terminal state without introducing Unicode display-width calculations and wrapping behavior.
Tracking the Cursor After Movement
Writing text is not the only operation that changes the cursor position, whenever we generate a cursor movement instruction, we must also update our cache, let’s create a function that supports both rendering strategies.
static void put_move(
struct out *o,
int smart,
int x,
int y
) {
const char *name;
if (smart) {
o->len += best_move(
o->buf + o->len,
o->cx,
o->cy,
x,
y,
&name
);
} else {
o->len += cup(
o->buf + o->len,
x,
y
);
}
o->cx = x;
o->cy = y;
}
The smart parameter determines which rendering strategy to use.
smart = 0
Always generate CUP.
smart = 1
Use the cursor movement optimizer.
When optimization is enabled, we pass our cached cursor position to best_move().
o->cx,
o->cy,
The optimizer can now determine whether CUP, CHA, CUF, carriage return, or no movement is the cheapest valid option, once the instruction has been appended, we update our cursor cache.
o->cx = x;
o->cy = y;
Regardless of which valid movement instruction was selected, the expected destination is the same, for example:
Current cache: (5, 0)
Target: (20, 0)
Selected instruction: ESC[21G
Updated cache: (20, 0)
We do not need separate cache-update logic for every movement command because the optimizer guarantees that its selected instruction reaches the requested destination under our assumed terminal settings.
Understanding the Rendering Pipeline
Our renderer now performs two operations for every run.
Every operation updates the expected state that the next operation will depend on, this is the fundamental difference between generating isolated terminal instructions and building a stateful rendering engine.
Implementing the Render Function
Now we can create the function responsible for generating an entire frame.
static void render(
struct out *o,
int smart,
const struct run *runs,
size_t n
) {
o->len = 0;
o->cx = -1;
o->cy = -1;
memcpy(o->buf, "\x1b[2J", 4);
o->len = 4;
for (size_t i = 0; i < n; i++) {
put_move(
o,
smart,
runs[i].x,
runs[i].y
);
put_text(o, runs[i].text);
}
put_move(o, smart, 0, 6);
}
Let’s examine each part of this function.
Resetting the Output Buffer
o->len = 0;
We begin with an empty logical output buffer, there is no need to clear all 512 bytes of the array because the length determines which bytes are valid.
Invalidating the Cursor Cache
o->cx = -1;
o->cy = -1;
At the beginning of this exercise, we do not know where the terminal’s cursor is positioned, we represent this unknown state using negative coordinates, this ensures that our optimizer will use CUP for the first movement rather than making assumptions about the cursor’s location.
Clearing the Screen
memcpy(o->buf, "\x1b[2J", 4);
o->len = 4;
The sequence ESC[2J clears the visible screen, however, clearing the screen does not necessarily move the cursor to the top-left corner, this is why we leave our cursor cache in its unknown state, the first cursor movement will establish a known position.
Rendering Each Run
for (size_t i = 0; i < n; i++) {
put_move(o, smart, runs[i].x, runs[i].y);
put_text(o, runs[i].text);
}
For every run, we first position the cursor and then append its text, both operations update our paint cache, by the time we process the next run, we already know where we expect the cursor to be.
Parking the Cursor
put_move(o, smart, 0, 6);
After rendering all the content, we move the cursor to row 7, column 1, this keeps subsequent output below our rendered frame.
Putting Everything Together
Create a file called paint_cache.c, we will reuse the escape sequence builders and movement optimizer from the previous exercise.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <string.h>
#include <unistd.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, int x, int y) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(
p + pos, (unsigned int)y + 1
);
p[pos++] = ';';
pos += (size_t)write_uint(
p + pos, (unsigned int)x + 1
);
p[pos++] = 'H';
return pos;
}
static size_t cha(char *p, int x) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(
p + pos, (unsigned int)x + 1
);
p[pos++] = 'G';
return pos;
}
static size_t cuf(char *p, int n) {
size_t pos = 0;
p[pos++] = '\x1b';
p[pos++] = '[';
pos += (size_t)write_uint(
p + pos, (unsigned int)n
);
p[pos++] = 'C';
return pos;
}
static size_t best_move(
char *p,
int cx,
int cy,
int x,
int y,
const char **name
) {
if (cx == x && cy == y) {
*name = "none";
return 0;
}
size_t best = cup(p, x, y);
*name = "CUP";
if (cx < 0 || cy < 0 || cy != y) {
return best;
}
if (x == 0) {
p[0] = '\r';
*name = "CR";
return 1;
}
char tmp[24];
size_t n = cha(tmp, x);
if (n < best) {
memcpy(p, tmp, n);
best = n;
*name = "CHA";
}
if (x > cx) {
n = cuf(tmp, x - cx);
if (n < best) {
memcpy(p, tmp, n);
best = n;
*name = "CUF";
}
}
return best;
}
struct run {
int x, y;
const char *text;
};
struct out {
char buf[512];
size_t len;
// Predicted cursor position.
int cx, cy;
};
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;
// Valid for printable ASCII without wrapping.
o->cx += (int)n;
}
static void put_move(
struct out *o,
int smart,
int x,
int y
) {
const char *name;
if (smart) {
o->len += best_move(
o->buf + o->len,
o->cx,
o->cy,
x,
y,
&name
);
} else {
o->len += cup(
o->buf + o->len,
x,
y
);
}
o->cx = x;
o->cy = y;
}
static void render(
struct out *o,
int smart,
const struct run *runs,
size_t n
) {
o->len = 0;
// The initial cursor position is unknown.
o->cx = -1;
o->cy = -1;
memcpy(o->buf, "\x1b[2J", 4);
o->len = 4;
for (size_t i = 0; i < n; i++) {
put_move(
o,
smart,
runs[i].x,
runs[i].y
);
put_text(o, runs[i].text);
}
// Park the cursor below the frame.
put_move(o, smart, 0, 6);
}
int main(void) {
static const struct run runs[] = {
{0, 0, "Title"},
{20, 0, "12:00"},
{0, 2, "a"},
{4, 2, "b"},
{8, 2, "c"},
{0, 4, "done"},
};
size_t n = sizeof runs / sizeof runs[0];
struct out full;
struct out smart;
render(&full, 0, runs, n);
render(&smart, 1, runs, n);
ssize_t w = write(
STDOUT_FILENO,
smart.buf,
smart.len
);
if (w < 0 || (size_t)w != smart.len) {
fprintf(stderr, "Failed to write complete frame\n");
return 1;
}
fprintf(
stderr,
"CUP only: %zu bytes, best_move: %zu bytes\n",
full.len,
smart.len
);
return 0;
}
The program constructs two independent output streams.
- In the dual-renderer pipeline diagram above, the CUP renderer produces a baseline 64-byte buffer from the array of runs.
- The smart renderer produces the optimized 58-byte buffer and sends it to the terminal in a single
write()call.
Only the optimized buffer is transmitted to the terminal, the other buffer exists purely as a baseline for measuring our optimization.
Predicting the Cursor Movements
Before running the program, let’s try predicting which movement instruction will be selected for every run, this time, calculating the destination alone is not enough, we also need to track where the cursor ends up after printing each piece of text.
Run 1: Drawing the Title
Our first run is:
{0, 0, "Title"}
The initial cursor position is unknown.
Current: (-1, -1)
Target: (0, 0)
Therefore, CUP is our only valid candidate.
ESC[1;1H
6 bytes
After moving the cursor:
cx = 0
cy = 0
We then append "Title", which contains five printable ASCII characters, our cursor cache becomes:
cx = 5
cy = 0
Run 2: Drawing the Clock
The next run is:
{20, 0, "12:00"}
Our cursor is already on the correct row.
Current: (5, 0)
Target: (20, 0)
We can consider three movement commands.
| Command | Sequence | Bytes |
|---|---|---|
| CUP | ESC[1;21H |
7 |
| CHA | ESC[21G |
5 |
| CUF | ESC[15C |
5 |
CHA and CUF have the same byte cost, according to our tie-breaking policy, CHA wins.
ESC[21G
After moving the cursor, our cache becomes:
cx = 20
cy = 0
Writing "12:00" advances the cursor another five columns.
cx = 25
cy = 0
Run 3: Drawing the Character a
The next run is:
{0, 2, "a"}
Our current position is:
Current: (25, 0)
Target: (0, 2)
The destination is on a different row, neither CHA nor CUF can reach it, therefore, we use CUP.
ESC[3;1H
6 bytes
After printing a, our cursor cache becomes:
cx = 1
cy = 2
Run 4: Drawing the Character b
The next run is:
{4, 2, "b"}
Our cursor is already on the correct row.
Current: (1, 2)
Target: (4, 2)
The distance is:
4 - 1 = 3 columns
We can compare the following commands:
| Command | Sequence | Bytes |
|---|---|---|
| CUP | ESC[3;5H |
6 |
| CHA | ESC[5G |
4 |
| CUF | ESC[3C |
4 |
Once again, CHA and CUF have the same byte cost, CHA wins because of our tie-breaking policy, after moving and printing b, our cursor cache becomes:
cx = 5
cy = 2
Run 5: Drawing the Character c
Our next run is:
{8, 2, "c"}
The cursor needs to move three columns to the right.
Current: (5, 2)
Target: (8, 2)
The candidates are:
| Command | Sequence | Bytes |
|---|---|---|
| CUP | ESC[3;9H |
6 |
| CHA | ESC[9G |
4 |
| CUF | ESC[3C |
4 |
CHA wins again, after printing c, our cursor cache becomes:
cx = 9
cy = 2
Run 6: Drawing the Final Text
Our final run is:
{0, 4, "done"}
The destination is on a different row.
Current: (9, 2)
Target: (0, 4)
We must use CUP.
ESC[5;1H
6 bytes
After printing "done", our cursor cache becomes:
cx = 4
cy = 4
Parking the Cursor
Finally, we move the cursor below the picture.
Current: (4, 4)
Target: (0, 6)
Because this requires changing rows, we use CUP.
ESC[7;1H
6 bytes
Our final predicted cursor position is:
cx = 0
cy = 6
Visualizing the Paint Cache
Let’s summarize how the cursor cache changes throughout the rendering process.
| Run | Cursor before movement | Target | Selected instruction | Cursor after text |
|---|---|---|---|---|
| Title | Unknown | (0, 0) | ESC[1;1H |
(5, 0) |
| 12:00 | (5, 0) | (20, 0) | ESC[21G |
(25, 0) |
| a | (25, 0) | (0, 2) | ESC[3;1H |
(1, 2) |
| b | (1, 2) | (4, 2) | ESC[5G |
(5, 2) |
| c | (5, 2) | (8, 2) | ESC[9G |
(9, 2) |
| done | (9, 2) | (0, 4) | ESC[5;1H |
(4, 4) |
| Park | (4, 4) | (0, 6) | ESC[7;1H |
(0, 6) |
Notice how the final cursor position of each run becomes the starting position of the next run, this is what allows our optimizer to make decisions without communicating with the terminal.
Calculating the Expected Byte Count
Before executing the program, let’s calculate how many bytes each rendering strategy will generate, both strategies begin by clearing the screen.
ESC[2J = 4 bytes
Both also write the same printable characters.
| Text | Bytes |
|---|---|
| Title | 5 |
| 12:00 | 5 |
| a | 1 |
| b | 1 |
| c | 1 |
| done | 4 |
| Total | 17 |
These 21 bytes are identical in both output streams, the difference comes entirely from cursor movement instructions.
| Run | Full CUP | Optimized sequence | Full bytes | Optimized bytes |
|---|---|---|---|---|
| Title | ESC[1;1H |
ESC[1;1H |
6 | 6 |
| 12:00 | ESC[1;21H |
ESC[21G |
7 | 5 |
| a | ESC[3;1H |
ESC[3;1H |
6 | 6 |
| b | ESC[3;5H |
ESC[5G |
6 | 4 |
| c | ESC[3;9H |
ESC[9G |
6 | 4 |
| done | ESC[5;1H |
ESC[5;1H |
6 | 6 |
| Park | ESC[7;1H |
ESC[7;1H |
6 | 6 |
| Total | 43 | 37 |
Now we can calculate the complete output size.
CUP-only renderer:
4 + 17 + 43 = 64 bytes
Optimized renderer:
4 + 17 + 37 = 58 bytes
We expect our optimized renderer to save six bytes.
Running the Program
Compile the program:
cc -std=c11 -Wall -Wextra -o paint_cache paint_cache.c
Then execute it:
./paint_cache
On a compatible terminal with sufficient screen dimensions, you should see:
Title 12:00
a b c
done
CUP only: 64 bytes, best_move: 58 bytes
Both rendering strategies describe the same picture, but the optimized strategy requires fewer bytes.
Measuring the Optimization
Let’s compare the two output streams.
| Measurement | CUP only | Optimized |
|---|---|---|
| Screen-clearing bytes | 4 | 4 |
| Printable text bytes | 17 | 17 |
| Cursor movement bytes | 43 | 37 |
| Total output bytes | 64 | 58 |
The reduction in total output size is:
Bytes saved = 64 - 58
= 6 bytes
Reduction = (6 / 64) × 100
= 9.375%
Our optimized renderer generates approximately 9.4% fewer bytes, if we look only at cursor movement instructions, the reduction is larger.
Cursor movement reduction:
(6 / 43) × 100 ≈ 13.95%
We reduced the size of cursor movement instructions by approximately 14%, these are two different measurements. One describes the improvement to cursor movement itself, while the other describes its effect on the entire frame, this distinction is important when evaluating rendering optimizations.
Why Are the Savings Relatively Small?
In the previous exercise, our movement optimizer reduced the combined size of eight movement instructions by 45%, here, the reduction in total frame size is only about 9.4%, why? The effectiveness of our optimization depends on the characteristics of the content being rendered, look at the structure of our frame:
Title 12:00
─────────────►
Horizontal movement
│
│ Row change
▼
a b c
──► ──►
Horizontal movements
│
│ Row change
▼
done
Our optimizer is most effective when consecutive runs are on the same row, whenever we need to move to a different row, our current implementation falls back to CUP, additionally, the printable characters and screen-clearing instruction remain unchanged, only three of the seven movement operations benefit from our optimization in this particular frame, this illustrates an important principle: the effectiveness of an optimization depends on how frequently the conditions for that optimization occur, a renderer that processes many small runs on the same row could benefit considerably more from this technique.
What Happens When the Paint Cache Is Wrong?
Our optimizer depends entirely on the accuracy of our cached cursor position, let’s imagine that we forget to update the cursor after printing text.
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;
// Missing cursor update!
}
After printing "Title", the actual cursor has advanced five columns, however, our cache still believes that it is at the first column.
Actual cursor: (5, 0)
Cached cursor: (0, 0)
Now imagine that we want to move to zero-based column 8 using a relative movement, based on the incorrect cache, we calculate:
distance = 8 - 0
= 8
We generate:
ESC[8C
But the actual cursor is already at zero-based column 5, the resulting position becomes:
Actual destination = 5 + 8
= 13
We intended to reach column 8, but we reached column 13 instead.
The escape sequence itself is perfectly valid, the problem is that we generated it using incorrect information, this demonstrates why stateful optimization introduces additional responsibility. Every operation that affects the terminal’s state must also be reflected in our internal representation, if the cache becomes unreliable, we must invalidate it and reestablish a known cursor position before using relative movement again.
The Paint Cache and Buffered Output
There is another important detail to consider, our renderer updates the paint cache while generating instructions, before those instructions are actually transmitted to the terminal, for example:
put_move(&smart, 1, 0, 0);
put_text(&smart, "Title");
At this point, our cache contains:
cx = 5
cy = 0
But we have not called write() yet, the actual terminal may still have its cursor somewhere else, we can visualize this as two separate timelines.
- Renderer (RAM): queue CUP, predict
(0, 0), queue"Title", and predict(5, 0). - Terminal: remain unchanged while buffering, receive output via
write(), process CUP, process"Title", and reach(5, 0).
The predicted state is valid for subsequent instructions in the same buffer because the terminal processes those instructions in order, however, if transmitting the buffer fails or only part of it is transmitted, we can no longer assume that the terminal has reached the predicted final state, a production renderer needs to handle this carefully, it may need to distinguish between the state predicted while constructing a frame and the state associated with successfully transmitted output, it must also handle incomplete writes and invalidate cached state when necessary, our example detects an incomplete write and exits, which is sufficient for this exercise.
Can We Reduce the Output Even Further?
Let’s return to the following part of our frame:
a b c
Our current renderer treats these as three independent runs.
{0, 2, "a"},
{4, 2, "b"},
{8, 2, "c"},
After printing a, the cursor is already at zero-based column 1, to reach b at column 4, we need to move three columns forward, our optimizer chooses:
ESC[5G
4 bytes
However, the three cells between a and b are empty, what if we simply print three spaces?
" "
This requires only three bytes, compare the two approaches:
Approach 1: Cursor movement
a + ESC[5G + b
1 + 4 + 1 = 6 bytes
Approach 2: Rewrite the gap
a + " " + b
1 + 3 + 1 = 5 bytes
Writing additional characters can sometimes be cheaper than generating a cursor movement instruction, this may seem counterintuitive, we are deliberately drawing cells that do not need to change, yet we are reducing the total number of bytes sent to the terminal, the reason is that cursor movement itself has a cost.
Let’s compare the complete row.
| Operation | Separate runs | Merged run |
|---|---|---|
| Initial CUP | 6 | 6 |
| Characters a, b, c | 3 | 3 |
| Horizontal movement | 8 | 0 |
| Spaces between characters | 0 | 6 |
| Total | 17 | 15 |
By merging these three runs, we can save another two bytes, our complete optimized frame could therefore decrease from 58 bytes to 56 bytes, however, rewriting the gap is only correct when we know what those cells should contain, including their colors and text attributes, in this exercise, we know the gaps contain spaces because we cleared the screen first and have not drawn anything there, in a more complex interface, those gaps might contain other characters or styled cells that must be preserved, this introduces another rendering optimization technique called gap merging, instead of always minimizing the number of cells we draw, we can compare the cost of rewriting unchanged cells with the cost of skipping over them, we will explore this technique in more detail later.
Challenge Yourself
Try replacing the original runs with the following:
static const struct run runs[] = {
{0, 0, "A"},
{1, 0, "B"},
{2, 0, "C"},
{3, 0, "D"},
{4, 0, "E"},
};
Before running the program, predict which movement instruction the optimizer will select for each run, remember that printing a character advances the cursor by one column, does the renderer need to generate a movement instruction between A and B? What about between B and C? Now try a different arrangement:
static const struct run runs[] = {
{0, 0, "A"},
{0, 1, "B"},
{0, 2, "C"},
{0, 3, "D"},
{0, 4, "E"},
};
Compare the byte savings between the horizontal and vertical arrangements, as an additional challenge, try modifying the original frame by merging the three runs containing a, b, and c.
{0, 2, "a b c"}
Run the program again and observe how the output size changes, these experiments demonstrate how the arrangement of content influences the effectiveness of our rendering strategy.
Putting It All Together
In this exercise, we combined three fundamental concepts:
- Output buffering, which allows us to transmit an entire frame using a single write when the write completes successfully.
- Escape sequence optimization, which allows us to reduce the number of bytes required to describe terminal operations.
- State tracking, which allows us to select instructions based on our predicted understanding of the terminal’s current state.
By introducing a paint cache, our renderer can now make decisions automatically as it constructs a frame, instead of treating every cursor movement as an independent operation, it understands the relationship between consecutive operations.
Previous state
│
▼
Select valid instruction
│
▼
Append instruction
│
▼
Update predicted state
│
▼
Process next operation
We reduced our output stream from 64 bytes to 58 bytes without changing the resulting picture, but the most important achievement is not the six bytes we saved, it is that we have transformed our renderer from a collection of independent escape sequence builders into a stateful rendering system, this foundation will allow us to explore more advanced optimizations, including tracking text attributes, minimizing style changes, merging runs, comparing frames, and rendering only the regions that actually need to change, an efficient terminal rendering engine does not simply know what to draw. It also understands what it has already drawn, what state the terminal is expected to be in, and how to reach the desired state with the least amount of work.
Further Reading
- XTerm Control Sequences — Look for
CSI Ps C(CUF),CSI Ps D(CUB), andCSI Ps G(CHA). - ECMA-48: Control Functions for Coded Character Sets — The standard defining these control functions.