English
Terminals: where Unicode meets control codes
The terminal is probably the hardest place to get text rendering right: it uses a fixed-width grid to display modern scripts that need shaping, it has to tell text from control commands within the same byte stream, and there is almost no feedback channel between the output side (the program) and the display side (the terminal).
Why backspace eats half a character
A terminal is a fixed-width grid. A shell's line editor (readline, zle, libedit) keeps its own in-memory model of "what this line looks like and which column the cursor is in", then sends control sequences (\b, \e[nD, redrawing the whole line) for the terminal to follow. The two sides never confirm with each other: the line editor simply assumes "the number of columns I computed = the number of columns the terminal actually drew". As soon as they disagree about the width of any character, the cursor drifts, and the more you edit, the worse it gets.
User types: ❤️ (U+2764 + U+FE0F), then presses backspace
readline's model (wcwidth) What the terminal draws
U+2764 → width 1 ❤️ drawn in emoji presentation, 2 columns
U+FE0F → width 0
total 1 column total 2 columns
backspace #1: deletes U+FE0F (width 0) → cursor stays, but the emoji on screen does not turn back into text presentation
backspace #2: deletes U+2764 → cursor moves left 1 column, clears 1 column → half a heart remains on screen
Every character typed afterwards is off by one column, and on line wrap the redraw lands on the wrong rowCommon sources of disagreement
- The locale is not UTF-8 (
LANG=C, SSH not forwarding the locale, no locales installed in the container): the line editor treats each byte as a character of width 1. Type "中" (3 bytes, 2 columns on screen) and press backspace once: only the last byte is deleted, leaving invalid UTF-8, and the cursor moves back only 1 column. This is the most common case and has the worst symptoms. - Different Unicode versions: the line editor uses libc's
wcwidth(), whose width table follows the glibc version; the terminal has its own width table. Newly added emoji may be "unknown" to an old glibc (wcwidthreturns −1 or 1) while the terminal draws them as 2 columns. This is especially common over SSH to old systems: the local terminal is new, the remote glibc is old. - East Asian Ambiguous width: characters such as
①,○,§, Greek and Cyrillic letters are traditionally 2 columns in CJK environments and 1 column in Western ones. Terminals usually have an "ambiguous width" setting, whilewcwidthusually returns 1; if the two settings disagree, things misalign. - Grapheme clusters:
wcwidthworks per code point and knows nothing about graphemes.👨👩👧is counted as 2+0+2+0+2 = 6 columns; terminals that support ZWJ sequences draw only 2 columns, those that don't draw 6. The same string has different widths in different terminals, so the line editor cannot be right for both. And since backspace deletes one code point at a time, family members disappear one by one while the width keeps changing. - Flags: a flag is two Regional Indicators. Some implementations count each as 1 column and others as 2, so the combined flag may be 2 or 4 columns.
- The same kind of problem, without Unicode: if color codes in bash's
PS1are not wrapped in\[ \], readline counts the invisible escape sequences toward the prompt width, with exactly the same symptoms: a drifting cursor and broken redraws on line wrap.
ASCIIBMP (non-ASCII)CJK / Hangul / KanaSupplementary planes (emoji, rare Han)Combining mark / variation selectorInvisible / format controlLone surrogate
Graphemes (dashed boxes) → code points · Hover over any cell to highlight every code unit of the same code point
❤U+2764VS16U+FE0F
👨U+1F468ZWJU+200D👩U+1F469ZWJU+200D👧U+1F467
🇹U+1F1F9🇼U+1F1FC
①U+2460
中U+4E2D
Why this is so hard to fix
Terminal protocols have no query for "how many columns will you draw this string in?". A few programs measure widths before drawing with cursor position reports (\e[6n), but that is slow, and slower over SSH. More recently the Contour terminal proposed mode 2027 (grapheme cluster mode), which lets applications query and enable "compute widths per grapheme" (\e[?2027h). Terminals such as Contour, Ghostty, WezTerm and foot support it, but line editors and TUI libraries are still catching up.
Troubleshooting order
- Make sure
localereports UTF-8 (both locally and remotely). - Check that the terminal's ambiguous width setting matches the locale (CJK users in particular).
- Make sure the control codes in
PS1are wrapped in\[ \]. - What remains is mostly width disagreement over emoji / ZWJ sequences; the only fixes are updating glibc and the terminal, or avoiding these characters on the command line.
The terminal is a state machine
In the byte stream a program writes to the terminal, text and control commands are mixed together:
| Category | Range / form | Examples |
|---|---|---|
| C0 control characters | 0x00–0x1F, 0x7F | \n newline, \r carriage return, \b backspace, \a BEL, ESC (0x1B) |
| C1 control characters | 0x80–0x9F | 0x9B = CSI, 0x9D = OSC (8-bit form) |
| CSI sequences | ESC [ … | Move the cursor, clear the screen, set colors (\e[31m) |
| OSC sequences | ESC ] … terminated by BEL or ESC \ | Window title, clipboard, hyperlinks |
| DCS and others | ESC P … | Terminal-specific features (sixel images, tmux passthrough) |
These sequences are specified by ECMA-48 and the DEC VT100 series of terminals, and the de facto reference is xterm's ctlseqs document. Many terminal parsers are based on the DEC-compatible parser state machine (vt100.net) documented by Paul Williams.
Conflict with UTF-8: the 8-bit C1 control characters 0x80–0x9F are exactly the range of UTF-8 continuation bytes, so in UTF-8 mode raw C1 bytes tend to be treated as invalid UTF-8. Terminals handle this inconsistently: some decode UTF-8 first and then execute the decoded U+0080–U+009F (C2 80–C2 9F) as C1; xterm processes control codes only once and does not execute C1 obtained from UTF-8 decoding as control codes. For portable sequences, use the 7-bit forms that start with ESC, for example ESC [ instead of 0x9B for CSI. Error handling is another headache: when an ESC arrives in the middle of decoding a multi-byte character, or an escape sequence contains invalid UTF-8, implementations differ on what to discard and where to resume. This is exactly where parser differences arise and where fuzzing finds bugs.
Escape sequence injection
Printing untrusted text to a terminal as-is lets someone else send commands to your terminal. Common sources:
tail -f access.log:ESChidden in the User-Agent or URL parameters.ls,find: file names can containESCand newlines.git log,git branch: commit messages, branch names, author names.curloutput, CI logs,kubectl logs, chatbot replies.
Possible impact:
- Spoofing screen content: clearing the screen, moving the cursor to overwrite earlier output, using
\rto return to the start of the line and cover text, or setting the foreground color to the background color. For example,cat install.shlooks harmless while the file hides commands covered by cursor control codes. This is the same class of problem as Trojan Source (in Chinese): what is displayed is not what is there. - Changing the window title (
\e]0;…\a): harmless by itself, but usable for social engineering. - Writing to the clipboard (OSC 52,
\e]52;c;<base64>\a): on terminals that support it, printing some text can replace the clipboard contents, waiting for the user to paste into a shell. - Fake hyperlinks (OSC 8,
\e]8;;<URL>\a<text>\e]8;;\a): the displayed text differs from the actual link. - Command injection through report sequences: early terminals supported queries such as "report the window title", and the reply was written back as input. If the title was first set to a command, after the query it was sent to the shell as if the user had typed it. Modern terminals disable these features by default. iTerm2's tmux integration also had an RCE caused by handling untrusted output (CVE-2019-9535, fixed in 3.3.6).
Defenses
- When printing untrusted data, escape C0 / C1 control characters (keep
\nand\tas appropriate):repr()in Python,%q/strconv.Quotein Go,cat -vin the shell. - By default
lessshowsESCasESCinstead of executing it; uselessrather thancatfor unknown files. But-Rpasses through more than colors: since less 580 (2021) it also passes OSC 8 hyperlinks, so the link spoofing above is still possible. - JSON requires U+0000–U+001F in strings to be escaped, so structured logs never contain raw C0 control characters; but C1 and bidi control characters can still appear as-is in strings. If field values are printed straight to a terminal after being read, the display side still has to handle control characters. Plain-text logs must be handled when writing or displaying them.
- Review terminal settings: disable or restrict OSC 52, and disable report sequences.
Ligatures, complex scripts and bidi in terminals
- Ligatures and shaping: terminals draw cell by cell, but shaping results are variable-width and many-to-many. Terminals that support programming ligature fonts (such as Fira Code's
=>and!=) have to shape a run of text together and then force the result back into cells. Indic scripts and Arabic cannot be displayed correctly in most terminals. - Bidi: who should reorder? If the application (say, an editor) does its own bidi reordering and the terminal does it again, the text is reversed twice; if neither does, RTL text comes out backwards. Egmont Koblinger proposed a bidi specification for terminals that defines the division of work between terminal and application and the control codes for switching modes. It is implemented in VTE 0.58 (2019, used by GNOME Terminal and others), but few other terminals implement it.
Verification scope (2026-11-12)
CVE numbers, the less version, mode 2027 support and the status of the bidi proposal on this page were checked against original documents, announcements and terminal source code.