VT core
On this page
vt-core does two translations:
- it turns the bytes coming from the PTY into terminal state (grid, cursor, modes);
- it turns keys and mouse events into the bytes sent back to the PTY.
It knows nothing about windows, GPUs or plugins, so it can be tested headless and fuzzed. Three crates sit around it: pty (child processes), session (I/O thread and snapshots) and search (search over the grid).
Goals
- xterm compatibility for everything real programs use (vim and Neovim, tmux, htop, less, fzf, modern shells), verified with esctest and vttest.
- Predictable memory: about 8 bytes per cell, and a scrollback limited in bytes.
- Headless throughput at least on par with
alacritty_terminal. - No allocations on the hot path, i.e. while printing text.
Parser
- DEC/ANSI state machine:
- Paul Williams' model, the same one
vteuses, implemented with a table computed at compile time. - States:
ground,escape,escape_intermediate,csi_entry,csi_param,csi_intermediate,csi_ignore,dcs_entry,dcs_param,dcs_intermediate,dcs_passthrough,dcs_ignore,osc_string,osc_ignore,sos_pm_string,apc_string,apc_ignore,string_escape. - Changes to the model:
- C1 controls are recognized only in their 7-bit form,
ESCfollowed by a byte, as in other UTF-8 terminals. Bytes from 0x80 up are UTF-8 in text, payload in OSC, DCS and APC strings, and ignored inside sequences. - Williams'
sos_pm_apc_stringis split in two: APC strings reach the handler, while SOS and PM strings are dropped. string_escapefollows theESCthat ends a string and consumes the\of ST, so the handler does not see it as an escape sequence.osc_ignoreandapc_ignore, like Williams'dcs_ignore, consume the rest of a string past its size limit.- Colons separate sub-parameters, BEL also ends OSC strings as in xterm, and DEL is ignored in text.
- C1 controls are recognized only in their 7-bit form,
- A sequence keeps at most 2 intermediates, its private marker included. No known sequence has more, and one that does is ignored.
- Paul Williams' model, the same one
- Why not
vte: it discards the contents of APC strings, which kitty graphics needs. - Streamed payloads:
- OSC, DCS and APC payloads are delivered in pieces (start, chunks, end). The parser buffers nothing: each run of payload bytes in a read is one chunk. The terminal routes the pieces to handlers registered per type.
- Size limits are configurable: 64 KiB for each type of string, and more for the strings that need it, such as 1 MiB for OSC 52 (the clipboard), and 16 MiB for OSC 1337's and APC's images. The parser reads the OSC number, the digits before the first
;, to pick the limit. The bytes up to that;count against the general limit and the whole string against the command's, so the outcome does not depend on how reads split the string. New limits apply from the next string: one under way keeps those it started with, the limit of a number that comes later included. - A string that would pass its limit ends at once as
TooLong, so the handler can free what it holds. The parser consumes the rest without delivering it, so memory stays constant whatever the payload's size. - OSC strings end with ST or BEL, DCS and APC strings with ST, and CAN or SUB cancel any of them. A terminator split across reads is still recognized.
- CSI parameters (DCS parameters follow the same rules):
- Up to 32 values, sub-parameters included: colons separate sub-parameters (e.g.
4:3for curly underline,38:2::r:g:b), semicolons separate parameters. - Past the 32nd value, the values are dropped and the sequence is still dispatched (
vteignores such a sequence). - An empty value reads as 0, so
CSI mhas one parameter. Handlers read most parameters with a default that also replaces 0:CSI A,CSI 0 AandCSI 1 Aare the same. A value too large for 16 bits reads as 65535. - A private marker (
?,>,<,=) is valid only as the first byte. Elsewhere it voids the sequence, which is then consumed without being dispatched.
- Up to 32 values, sub-parameters included: colons separate sub-parameters (e.g.
- UTF-8:
- Incremental decoding, so a character can be split across reads.
- Each maximal subpart of an invalid sequence becomes one U+FFFD, as the Unicode Standard recommends and as Rust's lossy decoding and web browsers do. A character cut short becomes one U+FFFD. Overlong forms, surrogates and values past U+10FFFF become one per byte.
- C1 controls encoded in UTF-8 (U+0080 to U+009F) are dropped.
- Fast path:
- A loop finds the first byte outside
0x20..=0x7E, 16 bytes at a time, as two 64-bit words. The arithmetic that marks the bytes outside the range also finds the first of them (SWAR, SIMD within a register). It is safe code whose speed does not depend on the compiler vectorizing it, and it matched hand-written NEON intrinsics in the measurements, sovt-corehas nounsafecode. - Runs of printable ASCII are written straight into the row's cells, with one page lookup and one style acquisition per stretch of a row, respecting autowrap and insert mode. ASCII takes no Unicode lookup: each character is one cell wide, starts its own cluster unless a prepended character comes before it, and is already in every normal form. REP of a printable ASCII character goes this way too, its copies a run of text.
- A run goes through the slow path, character by character, while a character set other than ASCII is in use, which gives the characters other meanings, or a hyperlink is open, which takes each cell into its page's table. Protection and the semantic zone are bits of the cell that the fast path writes too: with shell integration, nearly all output is in a zone.
- Characters of more than one byte that a read holds whole are decoded in one pass over their bytes, and handed to the terminal 64 at a time. The terminal writes each stretch of them that start clusters of their own, one or two cells wide, and fit in the line, at once, as it writes ASCII, with the codepoints that join those clusters and leave them as wide, which go into the grapheme table after the stretch, those of one cluster together; a codepoint that widens the stretch's last narrow cluster, as a vowel sign that spaces, makes it wide in the stretch, where it has room for its second cell, as a stretch that reaches its line's end is written at once: anything but VS15 after a wide cluster, and after a narrow one what has no width of its own but VS16, which can widen it. The codepoints that join the cluster before the stretch, as combining marks after text that came as ASCII, go into its cell together too, when none of them can change its width, wide or narrow: what has no width of its own but VS15 and VS16, after a first codepoint that has a width. Joins, which ZWJ sequences, skin tones and combining marks make, are most of the work of text full of emoji: in the stretch, a join neither ends it nor looks the codepoint up again; the stretch's buffers, which the terminal keeps, cost nothing to set up for a short run. Characters that join a cluster otherwise, or have no width, or do not fit, take the path of each character, and so does a whole run in insert mode or with a normal form to put the text in. Invalid bytes, and characters split across reads, go to the incremental decoder.
- A property test checks that the runs, of ASCII and of other characters, leave the terminal in the same state as the characters printed one by one.
- After
ESC [, a loop takes the parameters of a CSI sequence and its final byte; any other byte goes back to the table, in the state that the table would be in. - Only control characters, escapes, the rest of CSI sequences and the bytes that the incremental decoder takes go through the state machine.
- A loop finds the first byte outside
- Interface to the state: the parser calls a trait (
Handler) that the terminal state implements. In tests, an action recorder implements it too, which is handy for differential testing.
Terminal state
- Screens: primary (with scrollback) and alternate (without).
- Cursor: position, pending wrap, style (DECSCUSR), save and restore (DECSC/DECRC, mode 1048).
- Each screen saves its own cursor. DECSC saves the position with its pending wrap, the pen, the character sets and origin mode; DECRC with nothing saved puts the cursor at the top left, with the default pen and character sets, and origin mode off. A restore that brings origin mode back on puts the cursor no lower than the scroll region's bottom margin, nor past the right margin, as xterm's
CursorSetdoes; above the region, or left of the left margin, it stays. - Moves follow xterm: the relative ones (CUU, CUD, CUF, CUB and their kin) stop at the margin that they move toward when they start at it or before it, so that CUD from above the scroll region stops at its bottom margin, and at the edge of the screen when they start past it; the absolute ones (CUP, CHA, VPA) count from the top left of the screen, or of the margins in origin mode, and stay within them. Every move ends the cluster being printed and leaves no wrap pending.
- DECSCUSR 0 gives the cursor's shape and blinking back to the configuration (see the cursor options); the other values override it.
- Each screen saves its own cursor. DECSC saves the position with its pending wrap, the pen, the character sets and origin mode; DECRC with nothing saved puts the cursor at the top left, with the default pen and character sets, and origin mode off. A restore that brings origin mode back on puts the cursor no lower than the scroll region's bottom margin, nor past the right margin, as xterm's
- Sizes that programs set, with the window's operations allowed (
Options::window_ops, off by default), so that no program changes the window's size otherwise: DECCOLM switches to 132 columns, or back to 80, once mode 40 allows it too, where xterm needs mode 40 alone, which programs set themselves; it erases the screen, unless DECNCSM (mode 95) keeps it, takes the margins away, DECLRMM's with 132 columns, and puts the cursor home. XTWINOPS 8 t sets the rows and the columns, an omitted one staying and 0 taking the display's, DECSLPP (CSI 24 t and up) the rows, and DECSNLS (CSI Pn * |) the rows too; DECRQSS reports the rows for both. The terminal takes the size at once, a side that changes at most 1000 cells, so that the program's next query reads it, and queuesSizeChanged, which waits once, for the embedder to give the window and the PTY the size, or the terminal the window's back. Past the width that the embedder gave, the primary screen's rows rewrap with room for twice the scrollback's limit, which then becomes the bytes that they take there, so that a switch to 132 columns and back keeps the rows, styled or linked ones too. The embedder's next size brings the configured limit back, unless it is the size that the terminal has, as when the embedder gives the window the size that a program set; RIS keeps the embedder's width, andTerminal::set_scrollback_limitsets the configured limit, keeping what a program's width grew while the configured limit does not shrink. The rows that output adds at a program's width narrower than the embedder's are as many as the configured limit holds there, so that a program that goes back to the embedder's width keeps those that the limit holds at that width, fewer. A size that a program sets costs what a resize does, the scrollback's reflow included. RIS goes back to 80 columns from 132. XTSAVE and XTRESTORE save and bring back DEC private modes, each in a slot of its own.- The window: with the window's operations allowed, XTWINOPS also iconifies the window (2 t) and brings it back (1 t), moves it (3 t, an omitted place being 0), resizes it in pixels (4 t), maximizes it across the display, down it or both, or brings back its size (9 t), and makes it fill the display or not (10 t); it reports whether it is iconified (11 t), its place (13 t) and the display's size, in pixels (15 t) and in cells (19 t). The terminal keeps what it knows of the window,
Terminal::window, and the display's size, which the embedder sets, and answers from them at once; a request changes them, takes the size it needs, and queuesWindowChanged, which waits once, for the embedder to do what it can and to tell the terminal how the window ended withTerminal::set_window. Where 4 t and 8 t have a size omitted, it stays; where 0, it is the display's, as xterm takes them, which the parameters tell apart, as they keep which ones had digits. Raising, lowering and refreshing the window (5 t to 7 t) do nothing, and RIS keeps the window and the display.
- The window: with the window's operations allowed, XTWINOPS also iconifies the window (2 t) and brings it back (1 t), moves it (3 t, an omitted place being 0), resizes it in pixels (4 t), maximizes it across the display, down it or both, or brings back its size (9 t), and makes it fill the display or not (10 t); it reports whether it is iconified (11 t), its place (13 t) and the display's size, in pixels (15 t) and in cells (19 t). The terminal keeps what it knows of the window,
- Full reset (RIS): the terminal goes back to how it was made, its scrollback cleared as
alacritty_terminalclears it, but it keeps its configuration: size, the width that the embedder gave, scrollback limits, widths, normalization,TERM, what programs may read back (the title, the clipboard) and the schemes that links may have. It keeps the working directory too, which describes the shell rather than the terminal. - Modes and geometry:
- ANSI and DEC private modes, tab stops;
- vertical and horizontal scroll regions (DECSTBM, DECSLRM with DECLRMM). Without DECLRMM,
CSI sis SCOSC, andCSI uwithout parameters SCORC. - The four margins make a rectangle that LF, IND, NEL and RI scroll, at the bottom and top margins, when the cursor is between the left and right ones; below the region, the last row stops LF. IL, DL, ICH, DCH, SU and SD work within the rectangle, and only a region of the whole screen sends rows into the scrollback that is shown. The alternate screen, whose scrollback is not shown, scrolls a region that leaves fewer rows out than it holds by scrolling the whole screen, when it leaves eight rows out at most or its rows span two pages, so the rows that leave that region go into its scrollback too. HT stops at the right margin from within them; CBT goes past the left one, as in xterm, but in origin mode. Wide characters across the edges of what moves are emptied whole.
- Columns: DECIC and DECDC insert and delete columns at the cursor's, in the rows of the scroll region, as ICH and DCH do in each, and only with the cursor in the region. DECBI and DECFI move the cursor a column left or right; at the left or the right margin, within the top and bottom ones, they shift the region's columns right or left instead, a column coming in at that margin, and the cursor stays. Outside the margins they move it, as DEC STD 070 says, but not past the screen's edges, where they are ignored.
- Rectangles: DECCRA copies one, with its cells' attributes and links, as through a buffer, so that the copy can overlap its source; DECERA erases every cell of one, with the pen's background, DECSERA the cells of one that DECSCA does not protect, and DECFRA fills one with a character of ASCII or Latin-1, in the pen's style. A rectangle counts from the screen's top left, or from the margins' in origin mode, and stays within the screen or the margins; a wide character that its edges split is emptied whole, and the cursor does not move. The page parameters name the screen's only page.
- Character sets: G0–G3, each designated ASCII, DEC Special Graphics or British; the locking shifts SO, SI, LS2 and LS3, and the single shifts SS2 and SS3. A designation of a set the terminal does not know leaves the slot as it was. Only printable ASCII changes meaning: DEC Special Graphics draws lines and boxes from
_to~, as the VT100 did, and its line characters are ambiguous-width. - Double-width and double-height lines (DECDWL, DECDHL, DECSWL:
ESC # 3toESC # 6) are not supported: their rows hold and draw characters at single width, as in most terminals of today; DECALN (ESC # 8) is. - Style and colors: current style (SGR), 256-color palette, special colors, dynamic colors (OSC 4/5/10/11/12), title stack.
- The colors start as xterm's until the embedder gives the theme's; OSC 4, 5, 10, 11 and 12 change them, the resets (104, 105, 110 to 112) and RIS bring back the theme's, and
?asks for one, which getsrgb:rrrr/gggg/bbbbback, ended as the query was. Colors are read as X11 writes them,rgb:with one to four digits a component and#with three to twelve; names of colors are not known. - Special colors: xterm's five, of bold, underlined, blinking, reverse and italic text, which themes call the bold and the underline colors, and which start as the foreground. OSC 5 and 105 number them from 0, and OSC 4 and 104 from 256, after the palette; OSC 104 without numbers resets them with the palette.
- SGR follows xterm and kitty: 21 is a double underline, 22 ends both bold and faint,
4:0to4:5choose the underline, and 58 and 59 set the underline color. Extended colors read38;5;nand38;2;r;g;b, and with colons38:5:n,38:2:id:r:g:band38:2:r:g:b, which many programs write without the color-space id. A color it cannot read is skipped, taking only the values it read, as invte. With a private marker,CSI … mis not SGR (CSI > … mis xterm's modifyOtherKeys).
- The colors start as xterm's until the embedder gives the theme's; OSC 4, 5, 10, 11 and 12 change them, the resets (104, 105, 110 to 112) and RIS bring back the theme's, and
- Semantics: the hyperlink and the semantic zone of the text printed next.
- Hyperlinks (OSC 8): the text printed while a link is open is part of it, both halves of a wide character too, in its page's hyperlink table. The
idparameter, among those that:separates, ties the cells of one link together. A URI longer than 2083 bytes, anidlonger than 250, the limits of the specification, a URI oridthat is not UTF-8 or holds control characters, or a scheme that the configuration does not allow closes the link instead;http,https,mailtoandfileare allowed by default, in any case. The link keeps its buffers from one to the next. - Semantic prompts (OSC 133, FinalTerm's):
Astarts a prompt and marks its row,Bstarts the command that is typed,Cits output, andDends it, back to output. The text printed next is in that zone, which each cell keeps; a cluster that widens gives its second half its own zone.D's status,D ; status, is kept,Terminal::command_status, which a full reset forgets.A'sredrawoption, kitty's, tells what the shell draws again of its prompt once the size changes:1, the whole prompt, as by default and as zsh does;last, Ghostty's, its last line, as bash does;0, nothing. It holds until anotherAgives another, and a full reset forgets it.C'scmdline_urloption, kitty's and fish's, gives the command's line, percent-encoded, which the terminal keeps on the command's marks, 2048 bytes of it at most, its control characters as spaces but its line feeds, which part a command of several lines:Terminal::command_linetakes it in place of the text from the input's mark to the output's, which shares its row with a right prompt, as zsh'sRPROMPT.P;k=rstarts a right prompt, of the prompt's zone, until the input goes on,B, which marks no input again, or the text printed next comes before it, on another row or left of its start, as the proposal ends a right prompt at the line's end; Lokyr's integration of zsh marksRPROMPTso.P's other kinds change nothing. The other options, such asaid=, are not read yet. - A click in the command line (
Terminal::prompt_click): a prompt's start,A, announces how the shell's line editor takes a click,click_events=1or2, kitty's, orcl=line,m,vorw, the semantic prompts' (a secondary prompt's,k=s, changes nothing, and a prompt of neither announces nothing),Terminal::prompt_clicks; while the shell edits its command line, afterBand beforeC, on the primary screen, a click gives the click itself, of SGR's encoding, at its column and its row on the screen, or from the prompt's first ofclick_events=2, on or below the prompt's first row; or, ofcl=, the left or right arrows from the cursor to the clicked character, one a character, a wide one too, the cells thatBstarted and that the shell printed since, within the cursor's line ofcl=line, a long one wrapped over rows too, across the command's lines ofm,vandw, a line's end one arrow, as the up and down arrows leave a first line for the history in some shells; a click on the prompt, below the command line or of a shell that announced nothing gives nothing, and one past the command line's end, a right prompt's too, takes the cursor to its end, 4096 arrows at most; a cursor whose wrap is pending counts past its cell. A selection of cells within the command line, of a shell that announced either, gives what replaces it as a key deletes or types over it,Terminal::command_line_selection: the arrows from the cursor to its end and as many Backspaces as it holds characters, within the cursor's line but ofcl=m,vorw; none of a selection that holds text not of the input, as a right prompt's (the blank cells after a line's text hold none), nor of more than 4096 arrows or Backspaces. No arrows cross a cell of a grapheme of several code points, as a letter of a combining accent, which line editors count as one step or as several, each its own way.CandDforget how the line editor takes a click, so that no arrows reach the command that runs, until the next prompt announces it again; Lokyr's integration of bash announcescl=lineonly where its output's mark comes, from PS0 ofpromptvarsor from its own DEBUG trap of a bash before 4.4. The terminal cannot tell a line editor's suggestion of the rest of the line, as zsh-autosuggestions draws it, from typed text: a click on a suggestion, or past it, sends the arrows over it, which accepts it, and a selection of it replaces it as typed text. - The programs' statuses (OSC 7501, the Program Status Protocol, of its proposal's revision 0.4): a program tells whether it is idle, working, blocked waiting for input, done or failed, of
kind,progress,app, atitleand amsgin base64, each record of itsidin a tree of tasks,Terminal::statuses; a report takes its record's place whole,cleartakes a record and the ones under it away, a repeated key takes its last value, a malformed pair is skipped, and a report of no known state, past a bound (4096 bytes whole, a key of 16, anappof 32, anidof 128 in 8 segments of 32, atitleof 192 bytes decoded and amsgof 2048) of anidof a byte that no value takes, or of a text of no base64, of no UTF-8 or of a control character is ignored whole; 256 records at most, the least recently updated going first; a new prompt (OSC 133A) drops those that work, wait or are idle, RIS every one, and the embedder those that it no longer shows,forget_statuses;Event::StatusChangedtells each change.OSC 7501 ; ? STis answered with the states and the kinds that Lokyr takes, ended as the query was. - A session's status (OSC 21337, iTerm2's): a program tells a short status of its session, as "Working", the color of a dot that marks it (
indicator), the color of its text (status-color) and a line of detail,Terminal::session_status; itskey=valuepairs are separated by;, a value's own semicolons and backslashes of a backslash before them; a key left out keeps its part, an empty value clears it, and a key not known, a color that does not read (#rrggbborrgb:r/g/b) or a text of a control character or past its bound (a status of 256 bytes, a detail of 1024) is ignored, the rest applying; RIS clears it, and the embedder as its program leaves,clear_session_status;Event::SessionStatusChangedtells each change. - Desktop notifications (OSC 99, kitty's): a notification's title and body, plain or in base64 (
e=1), each in parts of anid(i), the terminal holding them until a part that does not say more comes (d=0holds), thenEvent::Notification, as OSC 9 and 777 give it; a part of 4096 bytes at most, a title of 1024 bytes and a body of 4096 of all their parts, 16 notifications held at most, the oldest going, RIS dropping them; a part of its icon or its buttons may end it and shows nothing of its own, closing a notification and asking which live are ignored, and a payload of a kind not known is ignored whole;p=?is answered with the focus that a click gives, the notifications shown while the window has no focus, and the title and the body, of the query'sidof its letters, digits and_ - + .alone. - The commands,
Terminal::commands: each of the primary screen's commands keeps its marks as pins, its prompt, its input, its output and its end of its status, 10 000 at most,MOST_COMMANDS, the oldest going first, each of an id, from 1 in their prompts' order, which a full reset does not start again. AnAlets go of the commands whose prompts are at its row or below, which a screen cleared in place,CSI HandCSI J, left on rows written anew, and of the last one if it has noC, as a shell that draws its prompt again, after a key's command or of a theme's redraw, givesAagain for the same command: the commands stay in their prompts' order, which the gutter's binary search takes. It lets go of the oldest whose prompts and ends left the list too, as every row of theirs did; one whose end stays, past a scrollback that took its prompt, stays, of its marks that left ofNone. - A command's start and end:
Event::CommandStartedof its id as its firstCcomes, of noDbefore it, andEvent::CommandEndedof its id and its status as its firstDcomes after it; a line of no command, whoseDcomes at once, tells nothing. A command that started and that the list lets go of before its end, as anAon its rows or a full reset does, ends of no status. A program that marks commands without end makes events of no payload, which the queue of events bounds as it bounds the others. ABor aCthat comes once the command started, as its program may print them, changes nothing, neither its marks nor its line.Terminal::commandgives a command by its id, andTerminal::command_lineits line, as theCthat started it told it in itscmdline_url, or else the text from its input's mark to its output's, of the input's logical line, as a long command's notification shows it. - The commands that meet rows,
Terminal::commands_meeting: those whose rows meet the rows numbered from one to before another, the last whose first row is at the first or above it, and those after it whose first rows are above the last: a command's first row is its prompt's, or, of none, its first mark's; of a prompt that left the list, the list's first row. A binary search finds the first, of one walk of the list's pages,PageList::row_indexes, for every row's number that it needs. - The block under a row,
Terminal::command_at: the command whose block holds a row, from its first row to its end's row, which is its own where the end is past its first column and the next prompt's otherwise, or, of a command that has not ended, to the next command's first row; none above every command, or past an end before the next command · Since 1.4. - The command line being edited,
Terminal::edited_command_line: while the shell edits its command line at its prompt, afterBand beforeC, on the primary screen, the input's characters fromB's mark, of no right prompt, as the prompt's click reads them, its lines apart, without the spaces that end it; empty of nothing typed, none otherwise · Since 1.4. - The blocks of the view,
Snapshot::blocks: each command whose block the view shows, of its first row, its prompt's mark's, and its last, its end's row, or the row before where the end is at its first column, or the cursor's of the command that runs, or the row before the next command's first of a command of no end that another followed, as a nested shell's outer command, by the view's rows, either past the view, and its state, none of the prompt where you type; of the same walk of the commands as the prompts' marks of the gutter, the view's alone, none on the alternate screen · Since 1.4. - Folds,
Terminal::fold: a command's output folded into one row of the view, from its output's first row, the row after its mark where the mark is past the row's first column, to the last row before its end, or its whole block, from its prompt's row; two pins of its rows, whichunfoldlets go of,Terminal::foldsgiving them by their rows' numbers. No fold takes the last command, whose prompt is in force, a command that runs or the alternate screen, and a terminal keeps 4096 at most,MOST_FOLDS; a block's fold takes the place of its output's. A fold goes as its rows leave the list, with ED 3, a clear to the prompt and RIS. The view goes over a fold as over one row, by rows and by pages; a row's number within it,Scroll::Row, shows its placeholder at the top, and a jump to a prompt within a hidden block lands on the block's row. The snapshot of a view of folds,Snapshot::view, gives each of its rows, the list's row by its index, a fold's placeholder, of its command, its kind and its rows, or a row past the list's last, as a short session's view ends of them, andSnapshot::foldedthe rows that the folds take out of the list, all of them and those above the view, as a scroll bar counts them. Each run of the list's rows between placeholders is read once, and a scroll moves the lines with their rows, so that a view of folds costs a view's rows whatever the rows that the folds hold, and some 35 ns more a fold for each update after a scroll; of no fold, the view and the snapshot are as before. What the snapshot carries by the view's rows takes them of the view of folds: the selection's ends, a fold's placeholder's row for an end in a fold, so that a selection across a fold takes its rows whole; the decorations', the matches' and the held cursor's rows, none of a row in a fold; the gutter's marks and the blocks' ends, on the placeholder's row in a fold; the images, none whose first row a fold takes.Snapshot::shown_rowgives a row of the view by the rows' numbers, the list's row or a fold's placeholder, of its first and last rows,view_ythe view's row of a row's number, andscreen_rowthe screen's row that a row of the view shows, as a program's mouse counts it;Terminal::shown_row,view_yandshow_rowthe same of the view now,view_cellsa placeholder's row empty, andScroll::Showntakes the view to a place among the view's rows, each fold one, as a scroll bar's thumb puts it. A search's current match in a fold unfolds it,Terminal::unfold_rows· Since 1.4. - The block's prompt rows pinned,
Terminal::set_sticky_prompts: while an embedder asks, each snapshot carries, as a snapshot of their own,Snapshot::sticky, the prompt rows of the block whose rows the view's top shows, the command whose block holds the view's first row, from its prompt's row to its command line's last, the row before its output's mark or the mark's own past its first column, three at most,MOST_STICKY_ROWS, and fewer than the view's rows, as a sticky header, from the moment the prompt's first row leaves the view's top, on the primary screen alone; as the block's last row comes nearer the top than they are many, its end's row or the row before the next command's first, their last rows alone, as the block's end pushes them up, so that they cover no row of the next block. While the view is scrolled a share of a row past its first row, the prompt's first row at the view's top is partly above it, and its rows pinned already, so that they stay still as a scroll by pixels starts; andSnapshot::sticky_pushedtells that their block's end pushes them, which a renderer then draws up by the share with the rows. Nothing is pinned of the command that runs, of no command after it, while the view shows the screen, where it draws, as a pager on the primary screen or a remote shell.Snapshot::sticky_promptgives the command and its prompt's row. They are copied again only as the block, their first row, their rows' epoch or their count change, as a block's prompt rows, above its output, change only as a reflow writes them anew; RIS keeps the embedder's ask · Since 1.4. - A blank row before each prompt,
Terminal::set_block_spacing: while an embedder asks, a prompt's mark, OSC 133A, that follows a command whose output's and end's marks came takes the cursor a row down first, the region scrolling at its bottom margin, after a line's end where the cursor is past the first column, so that the prompt starts a row lower than the shell began to draw it, the blank row of no command's block; none before the first prompt, after a line of no command, as a prompt drawn again or an empty line gives none, of the cursor at the screen's first cell, as a clear leaves it, nor on the alternate screen. Shells draw their prompts from where the cursor is, and move within them of relative moves, so that they draw their command lines and their prompts again past it, zsh's, bash's and fish's alike. A command keeps whether the terminal put the row before its prompt, a prompt drawn again at its row and marked anew, as a shell does at a resize or a theme's redraw, keeping it, so that the snapshot's blocks,BlockMark::room_aboveandroom_below, tell the blank rows around each, which a renderer draws its dividers through; RIS keeps the embedder's ask · Since 1.4. - A pane's archive,
Terminal::archive: the primary screen's scrollback and screen as the bytes that write them again, from the newest rows back within a bound of bytes, which another terminal reads back through its parser, of any width: each row's text, of SGR for its styles and OSC 8 for its links, the pen reset before each line feed, so that the row that it scrolls in takes no background, and an erase to the line's end after a row that a soft wrap made of a background; a soft wrap as no line feed, so that a terminal of another width reflows the line; and the kept commands' marks of OSC 133 at their cells, the cursor moved past the text to a mark there, of their status and line, the folder where they started of OSC 7, and Lokyr's own options,lokyr_spaced, the blank row before a prompt there already, which the reading puts no other of, andlokyr_started=andlokyr_ended=, the command's times, which the reading keeps in place of its own. The images, the shell's prompt where the user types, which a new shell draws again, and the empty rows that end the screen are left out; a command's end marked on that prompt's row comes after the rows, at the next row's start. A pane full at the default limit of 10 MiB, some 9900 rows of 120 columns, archives to 1.9 MiB in 16 ms and reads back in 7 ms, of a release build · Since 1.5. - A command's times and folder: a command keeps the time of the system's clock as it starts, at its first
C, and as it ends, at its firstDafter it, and the working directory that OSC 7 told last as it started, which the commands that start share until the next OSC 7; a line of no command has none · Since 1.4. - RIS closes the link and goes back to output.
- Hyperlinks (OSC 8): the text printed while a link is open is part of it, both halves of a wide character too, in its page's hyperlink table. The
- Keyboard: the flags of the kitty keyboard protocol, in a stack for each screen, as kitty keeps them.
CSI > flags upushes flags,CSI < n upopsnentries, and popping the last one resets the flags;CSI = flags ; mode ureplaces, adds or removes flags in the entry on top, which is there even before a push;CSI ? ureports them.- A stack holds eight entries, and a push past them drops the oldest. Only the five flags that the protocol defines are kept, so the report tells which ones the terminal knows.
- Switching screens switches stacks, and RIS empties both.
- Other modes: mouse, bracketed paste, focus events, synchronized output (2026), grapheme clustering (2027), the color scheme's reports (2031).
- Synchronized output holds the drawing of the screen until the program ends the update. Each
CSI ? 2026 hthat starts an update, while none is under way, counts as an update of its own, so that the session gives it a deadline of its own; a start during an update goes on with it. The session ends an update that takes too long, as Ghostty does. RIS ends it too. - The modes that change what keys, the mouse and pastes send (DECCKM, DECKPAM, LNM, mouse tracking and encoding, focus events, alternate scroll, Meta sends ESC, bracketed paste) live together, for the input encoders. Resetting any mouse tracking mode turns tracking off, as in xterm.
- The alternate screens follow xterm: 47 switches, 1047 also erases the alternate screen on the way out, and 1049 saves the cursor and erases it on the way in, and brings the cursor back on the way out. xterm has one cursor for both screens, so the cursor goes along when they switch; each screen still keeps its own cursor for DECSC.
- Mode 2027 switches between
unicodeandlegacymode, ending the cluster being printed; RIS brings back the mode the terminal was made with. - The color scheme, as Contour's extension has it, which Ghostty, kitty, Neovim and Helix take:
CSI ? 996 nasks it, and the answer isCSI ? 997 ; 1 nfor a dark scheme orCSI ? 997 ; 2 nfor a light one; with mode 2031 set, each change of the theme's colors that the embedder gives,Terminal::set_default_colors, tells it the same way, the same colors again nothing, as the app's appearance or its theme changes. The scheme is the theme's background's,Colors::scheme: dark where white text stands out of it more than black text, its relative luminance under 0.179, whatever background a program set; the session sends the report at once, as a program waits for it in silence. RIS takes the mode off. - Reverse wraparound (45), with autowrap, lets BS and CUB go on from the right margin of the row above, when that row wraps into this one, as far as the top margin. The extended reverse wraparound (1045), xterm's mode 45 as it was until 2023, goes on whether the row above wraps or not, and from the top margin to the bottom one; within the margins, a move goes round them at once, whole turns coming back to the same cell, so that its cost does not grow with its count.
- DECNKM (66) is the keypad's mode, which DECKPAM and DECKPNM set too; smooth scrolling (DECSCLM, 4) is kept for whoever draws the screen, which
Terminal::smooth_scrolland the snapshot tell; the screen itself scrolls at once. - DECSTR, the soft reset, does as xterm's does: the cursor shows and stays where it is, its shape and blinking back to the configuration's; insert mode, origin mode and both reverse wraparounds go off, and autowrap on; the cursor keys and the keypad send their normal codes, and modifyOtherKeys goes off; the margins become the screen's, with DECLRMM off; the character sets, the style and DECSCA go back to their defaults, and the palette and the special colors to the theme's, as OSC 104 does; and the cursor that DECSC saved goes. The mouse's modes, bracketed paste and the dynamic colors stay, as in xterm.
is2andrs2of the terminfo entry send it. DECSCL keeps the conformance level, 61 or 62, the VT220's that DA tells, for DECRQSS, and resets softly, as the VT220 and xterm do; a higher level does nothing, as xterm refuses one above its own. - DECRQM replies for every mode above, 4 for the ANSI modes that xterm keeps reset for good (GATM, SRTM, VEM, HEM, PUM, FEAM, FETM, MATM, TTM, SATM, TSM, EBM) and for DECHCCM, and 0 for those the terminal does not know; replies wait in a queue that the embedder takes and writes to the PTY.
- Synchronized output holds the drawing of the screen until the program ends the update. Each
- Printing, the path of every character of text:
- A codepoint either joins the cluster printed before it, as the segmenter decides in
unicodemode or a zero width does inlegacymode, or starts a new one at the cursor. A joining codepoint goes to its cluster's cell even while the wrap is pending, and the cluster stays open until the cursor moves or a control comes; other sequences, such as SGR, leave it open. A cluster keeps at most 32 codepoints, more than Unicode's stream-safe format allows marks, and drops those past them, after normalization too. - A codepoint of no width with nothing to join, such as a mark right after a carriage return, joins the character left of the cursor if there is one, and is dropped otherwise. A prepended character starts a cluster at the cursor, which the character after it joins, as UAX #29 has it, even one of no width, as U+0600 ARABIC NUMBER SIGN has with the Unicode 8 tables.
- When VS16 widens a cluster, its cell takes a spacer tail and the cursor moves on one column; VS15 does the reverse, and the cell that it frees keeps the cluster's style, protection and zone. In insert mode, widening moves the rest of the row right, and narrowing moves it back, within the line. A cluster at the last column has no room to widen and stays narrow.
- Writing over half of a wide character empties its other half. Text written at the left margin, where wraps land, over a wide character also empties the spacer heads that the row above kept for it at the end of its line, if that row is on the screen, wherever the write starts: the one at the right margin, under whatever left margin the wrap left it, and the one at the screen's edge when there is no left margin and the row above soft-wraps into this one, its continuation, as both rows' marks say. Only a wrap from the last column to the first marks the rows so, and a head that a wrap from the last column leaves without joining them ends the mark; rows that the edits move keep their marks, as for reflow. A head that a wrap left at another right margin stays, as does one that a wrap from right of the margins left at the screen's edge with a left margin; the erasures, the edits and the operations on rectangles, which write cells rather than text, leave the heads above; and the operations within left and right margins move the characters that a wrap took to the next row, but not the heads that it left outside the margins, which stay. A wide character at the last column leaves a spacer head there and wraps, or, without autowrap, goes one column back, and keeps its head when it wraps over another wide character.
- Insert mode moves the rest of the row right, cells with their graphemes and links, and empties a wide character that would lose its second half off the row; a cluster that widens moves it one more cell.
- A line ends at the right margin, unless the cursor is past it, and then at the edge of the screen; wrapping goes on at the left margin of the next row, through the scroll region. Only a wrap from the last column of the screen to the first one of another row marks the row soft-wrapped and the next one as its continuation, for reflow. Where the index does not move, at the screen's last row below the scroll region or at the bottom margin right of the right margin, the text goes on in the same row and joins none. A wide character that does not fit at the screen's last column, and wraps without joining the rows, where the index does not move or under a left margin, ends the row's soft wrap, as an erase to its end does: its head stands for text that goes on elsewhere. Other wraps that do not join the rows leave the marks as they are, as one that DECRC brings back may wrap from a character that still goes on into the next row.
- A codepoint either joins the cluster printed before it, as the segmenter decides in
- Editing:
- Erased cells, and the cells and rows that inserting, deleting and scrolling bring in, take the pen's background color and nothing else (background color erase).
- Protection: both print paths mark the cells that DECSCA, or SPA and EPA, protect, and the kind of protection is the terminal's, the last one set: in DEC's, which DECSCA sets, DECSED, DECSEL and DECSERA keep the protected cells and ED, EL and ECH erase them; in ISO's, which SPA sets, ED, EL and ECH keep them, and ED 2 does not move the screen into the scrollback while a cell of it is protected, and the selective erases erase them, as esctest asks, where xterm's keep them. DECRQSS of DECSCA tells DEC's protection alone. DECSTR and RIS end the protection. A wide character that an erase, an insertion or a deletion would split goes whole, and an erase that reaches the end of a row ends its wrap.
- ED 2 on the primary screen first moves the rows, up to the last one that holds something, into the scrollback, as
alacritty_terminaldoes; ED 3 drops the scrollback. - IL and DL work from the cursor's row to the bottom margin, only within the scroll region, and put the cursor at the left margin, as DEC terminals and xterm do. SU and SD scroll the region, the cursor staying, and SU sends the rows that leave a region of the whole screen into the scrollback, as LF does.
- REP prints the last character given to print again, through the character sets in use, as
vtedoes. - Every edit ends the cluster being printed; those at the cursor leave no wrap pending.
- OSC strings are read whole, within their size limits, and acted on when they end with ST or BEL. What the embedder has to act on goes to a queue of events: a title changed (OSC 0, 1, 2), the working directory (OSC 7, a
file:URL, of a path of 4096 bytes at most and a host of 255, a longer one none), a notification (OSC 9, 777, 99), the progress of a task (OSC 9;4), the tab's color (OSC 6;1, a component at a time), the colors changed, and the clipboard written or, when the configuration allows it, asked for (OSC 52), which the embedder answers once it is confirmed; the base64 of a write is read up to its padding, or to the first byte that is not of it, as xterm reads it, and one that stands for no byte is ignored. Text from programs loses its control characters. The queue keeps within limits: a change that the terminal's state shows, a title's or the colors', waits once; the tab's color, the progress and the working directory wait as their latest value, once; a write to the clipboards takes the place of the writes that wait to the same clipboards, or to some of them, made since the last read, so that the clipboards end with the program's last write and a read is answered with what was written before it, the places of the writes overwritten being closed up once they are half the queue; and the events with a payload, the notifications and the clipboard's writes and reads, take a MiB at most between two takes, past which they are dropped. - Reports: replies wait in a queue that the embedder takes and writes to the PTY, and carry only what the terminal makes of its own state. The replies to queries that wait take a MiB at most, between two takes: past it, a reply is dropped whole, as some queries make replies far longer than they are, such as XTGETTCAP for
sgror the title read again and again. An answer to a clipboard read, once allowed, goes whole, and does not count against the replies' limit; it names the clipboards with the letters of the request, each once, ands0for none, as xterm does. An embedder with a session answers withSession::reply_clipboard, which writes the answer at once.- DA1 says VT220 with ANSI colors (
CSI ? 62 ; 22 c), DA2CSI > 1 ; 10 ; 0 c, and DA3 a unit id of zeros, as Ghostty does; XTVERSION gives the name and the version that the embedder gives, the app's with the date of its commit, aslokyr 0.2.0-20261101. - DECRQSS reports SGR, DECSTBM, DECSLRM, DECSCUSR, DECSCA, DECSCL and DECSACE as the sequences that set them, and DECSSDT and DECSASD as no status line and the main display, with
1 $ rfor a valid request, as xterm does, and0 $ rwithout echoing the request otherwise. - DECRQCRA, when the configuration allows it, which it does not by default, tells the checksum of a rectangle of the screen, counted from the margins in origin mode and clamped to them, or to the screen: each cell's character, an empty cell a space, a spacer head as an empty cell, as xterm leaves the cell that a wide character does not fit in as it was, and the second half of a wide one nothing, summed and negated as DEC's terminals do, in
DCS Pid ! ~ XXXX ST. The cells' attributes, which DEC's terminals add, are left out, as xterm leaves them out withchecksumExtension, and as esctest reads the characters alone. Test suites read the screen through it, a cell at a time; a request whose reply could not be queued scans nothing. - DECDSR tells what a terminal emulator has: DECXCPR the cursor's place, without a page, as DA's VT220 has none; no printer; locked user-defined keys, which the terminal does not have; a keyboard of unknown language; no locator; no macro space, and a macro checksum of 0; no errors; one session. DECID (
ESC Z) answers as DA does. XTGETTCAP answers from the terminal's terminfo entry, by terminfo name, and answersTN,CoandRGBas xterm does (Terminfo). - XTWINOPS reports the size in cells, and in pixels once the embedder gives the size of a cell; it keeps a stack of ten entries, which 22 t fills with both titles, the icon's (1) or the window's (2), an entry of one taking the other from the entry below, as xterm's does, and 23 t pops, bringing back those asked for of those saved, as xterm does, with a
TitleChangedevent. xterm's third parameter, which reads an entry without popping it, is not read. Programs read the title back (20 t and 21 t) only when the configuration allows it, and then without its control characters. The embedder gives the window's title back withTerminal::restore_title, as a program that set another left, which the stack and the reports take, of no event.
- DA1 says VT220 with ANSI colors (
- C0 controls: BEL rings; BS moves left as CUB 1 does, so that, with the wrap pending, it leaves the last column; HT goes to the next tab stop, every 8 columns by default, or to the last column, where it leaves a pending wrap pending, so that the next character wraps, as xterm does; with mode 41, xterm's fix for curses, a tab at a pending wrap wraps first, with autowrap; LF, VT and FF go down a row and scroll at the bottom; CR goes to the left margin, or to the first column from left of it; SO and SI select G1 and G0. The others do nothing.
Paged grid
The format is inspired by Ghostty's page list.
Cell (64 bits)
| Bits | Field |
|---|---|
| 0–1 | Content tag: codepoint, codepoint + grapheme, background-only from palette, background-only RGB |
| 2–25 | Content: codepoint (21 bits), palette index (8 bits) or RGB color (24 bits) |
| 26–41 | Style id (16 bits) into the page's style table |
| 42–43 | Width: narrow, wide, spacer-tail, spacer-head |
| 44 | Protected (DECSCA) |
| 45 | Has a hyperlink (the id lives in the page's table) |
| 46–47 | Semantics: output, prompt, input |
| 48–63 | Reserved (image placeholders, future use) |
- Empty cells: an empty cell is all zeros, U+0000 in the default style, so a new page is empty without being written.
- Background-only cells: cells that carry only a background color (for example after an erase with background color erase) don't use up a style.
- Multi-codepoint graphemes: emoji ZWJ sequences and combining characters live in a per-page table, keyed by cell position.
Row
Each row has compact metadata:
- soft-wrapped, i.e. continued on the next row;
- continuation of a previous row;
- start of a prompt (OSC 133);
- dirty, i.e. needs redrawing: every change of a cell marks it, and so does a change of the soft wrap or of the prompt's start, which a renderer shows, but not of the continuation, which changes with the soft wrap of the row before; a snapshot clears it as it copies the row;
- "contains graphemes / hyperlinks / images / styles" flags, so hot paths can skip work. They mean "may contain": they are reset when the row is cleared, not when the last such cell goes.
The metadata fits in one byte.
Page
- Layout: a fixed memory budget, 512 KiB to start with (to be tuned). For a given width, it sets how many rows fit next to the tables: 776 at 80 columns, 311 at 200. The page holds a header, the row metadata, the cells in blocks of a row's width, the block that each row uses, each block's extent, two bytes for the column from which its cells are all empty, so that emptying it fills the cells before it alone, a style table (deduplicated and reference-counted), a grapheme table and a hyperlink table. By default the tables have room for 256 styles, 128 graphemes, 32 link targets and 512 linked cells, about 23 KiB.
- Allocation: each part is allocated once, when the page is created, and never grows. They are separate allocations rather than one block, which in safe Rust would mean packing every table into words; the pool keeps the guarantee that matters, no allocation while output scrolls.
- Style table: its capacity is set with the page's. Equal styles share an id, every cell holds a reference to its style, and the last reference frees the id. The default style, id 0, is not counted, so unstyled text costs nothing. A lookup hashes the style packed in 128 bits, so even a style change on every character stays cheap.
- Grapheme table: the codepoints after the first, for the cells whose cluster has several, in a fixed arena of 4-codepoint chunks and keyed by cell. A cell becomes a grapheme when a codepoint is added to it; overwriting or clearing it frees the entry.
- Hyperlink table: the OSC 8 targets, id and URI, in an arena of 32-byte chunks, deduplicated and reference-counted like the styles, and a map from each linked cell to its link. The terminal holds a reference to the link while it links a cluster's cells, and lets go of it after, even when the table has no room for one of them.
- Shared machinery: the tables share one open-addressing index and one allocator of ids. A lookup stops after one turn of the index, which never happens in a sound one, so a bug fails instead of hanging the terminal.
- Growth: when a table fills up, the page is rebuilt with more capacity, so it becomes larger than a standard page. The error says which table is full, and
Capacity::grown_fordoubles that one. Every table keeps its ids, so the cells are copied as they are.- A table at its largest capacity does not grow:
grown_forreturnsNone, andPageList::grow_pagean error. The page then writes without what the table has no room for: a codepoint that would join a cluster, a cell's link, or, when printing, the pen's style. A copy between pages, withWhenFull::Drop, takes each cell without what does not fit.
- A table at its largest capacity does not grow:
- Pool: pages come from a pool and go back to it. There is no
malloc/freewhile output scrolls.
Page list and scrollback
- Structure: a doubly linked list of indexes into a slab, oldest first, rather than of pointers. The last rows form the active screen; the earlier ones form the scrollback. Scrolling adds an empty row at the bottom, in a new page when the last one is full.
- Page ids: a page's id carries the generation of its slot, so the id of a page that left the list goes stale instead of naming another page.
- Moving rows: a row of the screen moves into another one, as scrolling down, inserting and deleting lines and scroll regions need. Within a page, the two rows trade their blocks of cells, so nothing is copied and the grapheme and link entries, keyed by cell, stay valid; emptying the target first costs one compare when it is empty already.
PageList::shift_rows_upandshift_rows_down, which scroll regions, IL, DL, RI, SU and SD use across the whole width, rotate the rows of a range that one page holds: the slots of their blocks, their metadata and the heads of their chains of pins move, and nothing else; by one row, as a line feed scrolls a region, the slots and the metadata move in one pass, each row marked dirty as it moves. Across pages, the rows move one by one into the rows that the moves before emptied. On the alternate screen,PageList::scroll_rows_upscrolls a region that leaves fewer rows out than it holds by scrolling the whole screen and rotating back the rows outside it: for the region of all rows but the last, a rotation of two rows. Past eight rows out, as vtebench's top region of 23 rows of 40, the region's own rotation,PageList::rotate_rows_up_in_page, is the faster, which 120 by 40 cells measure: the whole screen's way carries the rows outside across a page's end now and then, and copies them; a region that spans two pages, which its own rotation would copy at each scroll, as the screen that no whole scroll moves stays across them, still scrolls the whole screen. Each block of cells keeps an extent, a column from which its cells are all empty, so that emptying a row fills only the cells before it. Across pages, each cell's style, grapheme and link are copied into the tables of the other page, which grows when one is full. - Eviction: when a new page would pass the byte limits below, the oldest page leaves first: it goes back to the pool, which hands it out again, so the list keeps no spare page and scrolling at the limit allocates nothing. A page whose tables grew goes back too, as it is, while its rows needed them, more styles, clusters, links or linked cells than a standard page has room for, or more of the room that the clusters' codepoints and the links' targets take, so that text that grows them, as combining marks and links do, allocates nothing once the pool has such pages; once its rows no longer need them it is freed, so that a burst of styled text leaves the scrollback its rows when plain text follows. A page is emptied as it comes out of the pool. The pages that ED 3 empties are freed, since no new page is about to take them. The oldest page leaves only when the rows after it cover the screen.
- Byte-based limits:
- One per pane, 10 MiB by default, over the pages of the list and of its pool.
- A global budget shared by all panes, 100 MiB by default, counted atomically since each pane has its own I/O thread.
- A pane that needs a page past either limit makes room with its own oldest pages: a busy pane never takes the scrollback of an idle one.
- A screen always gets its pages, even past the limits. When a page grows, or another pane's screen passes the budget, the pane frees its oldest pages, at its next new page, until it is within the limits again. So only the pages that screens need can pass them.
- Cold-page compaction:
- Short lines waste space in fixed-width pages.
PageList::compact(keep)keeps small the pages whose rows are allkeeprows or more above the last, and never the screen's: a cold page keeps each row's cells up to its last that is not entirely empty, one row after the other, and the rest of the page as it is, its tables and its rows' blocks with it, so that the entries keyed by cell are still right when it comes back. Its rows, ids and pins stay. A page that this would not make smaller, as with full rows, where the start of each row costs more than the empty cells save, stays as it is. On a scrollback of short lines at 80 columns, such asls -la, it gives back about three quarters of the bytes; on lines of 40 characters, about two fifths. Terminal::compact_scrollbackcompacts what is three screens or more above the primary screen's last row. It is for an idle terminal: compacting allocates, and a cold page that leaves the list is freed, not pooled, so output does not do it.- Readers read a cold page as it is:
PageList::rows_fromandPageList::rows_beforegive each row as aListRow, its metadata, its kept cells followed by empty ones, and its clusters, so that reading, as search does, takes no memory and keeps the page cold. A cold page returns to the normal format only to be written: resizing and reflow bring back what they rewrite, and a taller screen the rows that it takes from the scrollback, so that the screen is never cold. Warming counts the pages' bytes again, which could take the list past its limit and a shared budget past its own, making other panes give back their scrollback, so nothing else warms.PageList::iter_rows, which reads pages whole, fails on a cold page rather than skipping it. - lz4 compression on top of compaction is deferred to F7.
- Short lines waste space in fixed-width pages.
- Pins:
- A pin is a cell of the list,
(page, row, column), that the list keeps track of:PageList::pinputs one on a cell,pin_positionsays where the cell is now, andunpinlets it go.row_atandrow_indexgo between a row's index in the list, oldest first, and its page and row. - A pin follows its cell. Scrolling moves no row, so pins stay; when rows or cells move, as scroll regions, IL, DL, RI, ICH, DCH and insert mode move them, their pins go along; a page that grows keeps them; reflow carries them to where their cells go, and a cold page keeps them.
- When its cell leaves the list, with its page or the scrollback, or a move drops it, the pin is lost:
pin_positionreturnsNone, never a dangling position. Erasing a cell where it is leaves its pins. - A page keeps its pins by row: the first pin of each row, whose slot chains it to the row's others, so that a pin is let go of at once, and a row that moves takes its pins along without the page's others being looked at: many pins in a page, as a search's results, cost nothing to the rows that move without them. A pin takes 20 bytes in the slab, and a page with pins 4 bytes for each row up to its last pinned one.
- Pins live in a slab with generations, so a lost pin frees its slot at once and its id goes stale. Each page's node lists the pins in it, so a move looks only at the pins of the two pages involved, and a page without pins costs nothing.
- Used by the view, selection, OSC 133 marks, search results, images and link hover.
- A pin is a cell of the list,
- Rows' numbers: a row of the active screen or of its scrollback has a number, which output that scrolls it into the scrollback, the view's scrolling and the scrollback's limit, which takes older rows away, leave it: the screen's top row is numbered by the times that the screen scrolled up in its epoch, the rows below it on from there, and the scrollback's rows above it down from there, so that a number stays its row's until the row leaves the list. A resize, which lays the rows out again, starts an epoch, of other numbers, and another screen is another list.
Terminal::origingives the epoch and the number of the view's first row now, andSnapshot::originthe update's, the drawn frame's, so that input names the rows that were shown though output scrolled the view since; with the view's offset and the scrollback's rows,Terminal::scrollback_rowsandSnapshot::scrollback, they give the screen's first row's number and the oldest row's. The cells that a caller names take numbers:select,anchor_selection,mark_cell,line_text,link_atand the pins of cells; what the renderer draws, the snapshot's lines and the selection that it shows, is in the view's rows. - Cells' pins:
Terminal::pin_cellpins a cell of the active screen, by its column and its row's number, whichpinned_cellgives back, with its row's number now, while its text is in the list and its screen is the active one, through output, a reflowing resize and the view's scrolling, until the scrollback's limit or a clearing takes its row;unpin_celllets it go, and a pin let go, or lost, tells nothing, though another takes its slot. Decorations, search, MCP and the prompts' marks keep their lines so through a resize, which renumbers the rows.
Resizing and reflow
- Rows,
PageList::resize: a taller screen takes its new rows from the scrollback, as xterm does, and empty ones at the bottom when the scrollback runs out; the alternate screen, whose scrollback is not shown, adds them at the bottom. A shorter screen drops the empty rows below the cursor first, then sends rows from the top to the scrollback. No text is dropped: when the cursor's row goes to the scrollback too, the cursor stays in the screen's first row, and the program redraws on the resize. - Columns, without reflow: the pages are rebuilt at the new width, each row cut or extended with empty cells. A wide character that loses its second half is emptied, spacer heads go, and the rows no longer wrap; pins in the cut columns are lost, the others keep their cell. The old pages leave the byte limits at once, and go as their rows are copied, so the new pages have the room.
- The prompt: before the embedder's resize,
Terminal::resizeclears the prompt that the cursor is in, betweenAandC, from the row whereAstarted it to the bottom of the screen, as the shell draws it again on SIGWINCH: from as many rows above the cursor as the prompt took when the shell drew it, which a reflow of the prompt would change, leaving the first rows of a line that the reflow made taller above the prompt drawn again.redraw=lastclears from the cursor's line, andredraw=0keeps the prompt, which reflows. Only a prompt that starts on the primary screen clears; a prompt without the marks reflows. A prompt's start of noredrawthat comes while a command runs, after itsCand before itsD, is taken for a nested shell's, as aftersshorexec, which may mark its prompts' starts alone: no prompt clears until that shell tells its input, a command or aredraw, so that its commands' output, which prints in its prompt's zone, stays · Since 1.6.1. The cleared rows take the default background, whatever the pen's; the row above no longer wraps into them, as output without a final newline does under zsh's mark of its end, so that a wider screen does not join that output to the cleared rows, which the shell's drawing would then erase; and the cursor comes within the new width, so that the reflow keeps its row. - The terminal,
Terminal::resize: a terminal has two columns at least, asTerminal::newmakes it, so that a wide character always fits; DECSLRM leaves two too. The primary screen reflows, the alternate one is cut. Each cursor follows its cell, and so do the cursors that DECSC saved, which are pinned for the resize; one whose text went to the scrollback comes to the top row, and one whose column was cut keeps its row, in the last column. A wrap stays pending only at the last column, and goes on in the cell after its text otherwise. The margins become the whole screen, the tab stops go on every eight columns past the old width, and the cluster being printed ends. - Reflow,
PageList::reflow: on column changes, logical lines are written again into new pages at the new width. A row goes on into the next only when it soft-wraps and the next is its continuation: rows that IL, DL, RI, SU and SD move keep their flags, which then no longer pair up, and the same rule holds for reverse wraparound.- A wide character that the edge would split leaves a spacer head in the last column and goes on in the next row; spacer heads go when lines join again.
- The empty cells that end a line are left out, but those up to the cursor, which keeps its place in its line; a cell after a full row's text goes on in the next row, as the wrap would take it. A cursor on a spacer head goes with the wide character.
- Cells keep their styles, graphemes and links, and the first row of a line its prompt mark. Pins follow their cells, those of a wide character's second half too; a spacer head's go with the wide character, and those on empty cells left out stay as far after the text as they were, within its last row.
- When the text from the screen's first row to the cursor takes more rows, the empty rows below the cursor take them first, so that the text stays on screen, as iTerm2 keeps it; rows that the scrollback gains move nothing on screen. No text is dropped: when the rows below the cursor push its row into the scrollback, the cursor stays in the screen's first row. A screen with too few rows gets empty ones at the bottom.
- The old pages leave the limits before the new ones come, as for a cut.
- Alternate screen: resized without reflow, as xterm does.
- Cost and correctness: cost is linear in the scrollback size, about 0.3 µs per row of 120 columns (throughput-F1-133.md). A property test checks that shrinking and then widening again, through other sizes on the way, loses no content, wherever the cursor is and whatever edits moved the rows: every line keeps its cells, with their styles, graphemes and links.
Selection
- What it holds: two pins of the active screen's rows, its first and last cells, in one of two shapes: the cells from the first to the last in reading order, or a rectangle of the columns between them on each row between them.
Terminal::selecttakes two cells, by their rows' numbers, and grows a selection of cells to the words or the logical lines that they are in;select_alltakes the whole scrollback and screen. - Words: the cells around a cell that are neither spaces nor separators, across soft wraps and the spacer head that a wide character left at a row's end; on a space, the run of spaces; on a separator, the separator alone. The separators are the caller's,
WORD_SEPARATORSby default: quotes, brackets,|,:,;,,and the box drawing's vertical line, so that a path or a name with dots and dashes is one word. - Lines: the rows that soft-wrap into each other, whole, as a row that soft-wraps goes on into the next only when the next is its continuation.
- Its text,
Terminal::selection_text: soft-wrapped rows joined; the spaces that end a line dropped, and those that end the selection where the rest of its row shows nothing; clusters whole, a wide character once, from either of its halves; a rectangle's rows each a line. - What clears it: output that writes over its cells, other text or another style, which a hash of its cells on the screen tells, the same text written again leaving it, in the same styles too, which the hash takes by their values, as a page gives a style another id as a row is written again or moves to another page; output that writes over its cells and scrolls them into the scrollback before the next look, as the rows that left the screen are looked at once; a move of its rows that drops some or brings others in, as a scroll region's; its first or last cell leaving the list, with the scrollback's oldest rows or ED 3, or coming after the other, as a scroll within left and right margins can move them; and a switch to the other screen. A resize keeps a selection of cells, whose pins follow their text through the reflow, and drops a rectangle. A snapshot carries the selection as the view shows it, and looks only at the rows that it copies, so that a frame of an unchanged screen costs nothing more for it.
- Decorations,
Terminal::decorate: spans of a look, an underline of its own color or the text's, a background, and whether the pointer over them is the pointing hand, over the cells from one to another in reading order, each by its row's number, under an id that the embedder gives, whichundecoratetakes away: two pins, so that a decoration keeps its text through output, a resize's reflow and the view's scrolling, and goes as its rows leave the list, then forgotten at the next snapshot. A terminal keeps 4096 at most,MOST_DECORATIONS, as each snapshot looks at every one, which costs nothing without any. The snapshot carries the spans that the view shows, row by row,Snapshot::decorations, under the lock of its copy, so that a frame never draws them a row off its text; the active screen's alone, and RIS takes them all. - The gutter's marks,
Terminal::mark_gutter: a mark of a color at the left of a row, by its number, under an id that the embedder gives, whichunmark_guttertakes away: a pin of the row's first cell, so that it keeps its row through output, a resize's reflow and the view's scrolling, and goes as its row leaves the list, with ED 3 and with RIS. A terminal keeps 4096 at most,MOST_GUTTER_MARKS. The snapshot carries the marks of the view's rows,Snapshot::gutter: the laid ones of the active screen, and the prompts of the primary screen's commands that ran, of the commands that OSC 133 marks, each of its command's state, running from its output's mark, then succeeded, of the status 0 or none told, or failed; a line of no command, of no output's mark, has none. A binary search finds the view's first prompt among the commands, as a row's number costs a walk of the list's pages. - Reads of rows:
Terminal::read_rowsgives the rows' texts by their numbers in one pass, each without the spaces that end it but where it wraps into the next, which it tells;row_stylesgives a row's styles as runs of cells. - A marked cell,
Terminal::mark_cell: one cell, by its row's number, pinned as the selection's cells are, as a context menu's target, whichmarked_cellgives back by its row's number now, while it is in the list and on the screen that marked it, andunmark_celllets go. It follows its cell through scrolling and a reflowing resize, not its text: a row written again in place gives the new text. It goes with its page, with ED 3 and with RIS. A held cursor,Terminal::hold_cursor, an embedder's, a cell pinned so too, which takes the place of the terminal's cursor in the snapshots, still, while the view shows its row, the terminal's hidden meanwhile, and none of it while the other screen shows, as a mode of the keyboard's over the scrollback moves one;held_cursorgives its cell, andcursor_cellthe terminal's own cursor's, by their rows' numbers. The text of a row's logical line,line_text, as far as a number of rows before the row and after it that the caller gives, so that a line of many rows costs no more, and the link at a cell,link_at, take rows by their numbers, and none that the list does not hold.
Inline images
The pictures that programs send, as iTerm2's OSC 1337 File=, or its file in parts (MultipartFile=, FilePart= and FileEnd, as iTerm2's imgcat sends it by default, gathered within the images' memory), and kitty's graphics protocol send them, before 1.0.0, in one store.
- The store,
Terminal::keep_image: each image's bytes as they came, PNG, JPEG, GIF, TIFF, aschafasends iTerm2's, BMP, or pixels of RGB or RGBA, with its size in pixels, read from its header (terminal::dimensions), by an id, the program's or the terminal's of an image that it does not number, from 2³¹ up, past the ids that a program's images hold. The embedder decodes them as it draws, so that the terminal holds no decoded pixels. - Its bounds: the bytes of every image within
Options::image_memory, 64 MiB by default, none for 0, which shows no image, each counting 1 KiB at least, of its own keeping; 4096 images at most,MOST_IMAGES; past either, the oldest go, those of no placement first, found by an index of their order, as each image counts its placements; an image of more than 16 million pixels is refused, as a small file of a huge size would take the memory of its decoding; OSC 1337 strings 16 MiB at most, of the parser's limits, its base64 decoded once whole, its spaces and line breaks skipped. - Placements,
Terminal::place_image: an image over a rectangle of cells, from a pin of its top left cell, as decorations hold theirs, so that it scrolls into the scrollback with its rows, follows a reflow, and goes as the scrollback's limit or ED 3 takes its row; 1024 at most, the oldest going. Its size in cells: its own size in pixels of the cell's, set byset_cell_size(8 by 16 of none), or the program's width and height, in cells, pixels or a share of the screen, one side and its proportions; never wider than the screen. The cursor moves past its last column on its last row, the screen or the scroll region scrolling to make room for its rows, unless the program asks it to stay; the image starts at the cursor's cell, which the scroll moves up, into the scrollback for an image taller than the screen; on a screen of no scrollback, and above a scroll region narrower than the screen, the rows that leave are cut from the image's source. - Its life: an image of no number goes with its last placement; ED 2 on the primary screen sends the screen's placements to the scrollback with its rows, those of an image of no text after it too, and an ED 2 that erases in place (DECSED, protected cells) takes the placements that start on the screen; the alternate screen's placements go as it is erased or left; RIS forgets every image.
- kitty's graphics protocol, over APC
G(https://sw.kovidgoyal.net/kitty/graphics-protocol/), a subset: images transmitted in the stream alone (t=d), of RGB, RGBA or PNG (f=24,32,100), inflated by zlib within the images' memory, or the bytes of their pixels' size (o=z,miniz_oxide), whole in one APC string or in chunks (m=1), an APC string of 16 MiB at most, a chunk of the keysmandqalone, any other command ending the transmission under way; transmit, transmit and display, display, delete and query (a=t,T,p,d,q); images kept by the program's ids or numbers (i,I), lasting without a placement until deleted or the memory takes them; placements of a size in cells (c,r), stretched of both and in proportion of one, a rectangle of the image's pixels (x,y,w,h), a z over the text from 0, the cursor moving past or staying (C=1), a placement of a number replacing its image's of that number (p); deletions of every placement of the screen, by id or number, at the cursor, at a cell, a column, a row or a z, an upper case letter letting the images go too; replies ofOKor the protocol's errors to a command that names its image, whichq=1keeps for the errors andq=2keeps from all. Files, temporary files and shared memory (t=f,t,s) are refused, as a program's read of local files through the terminal; animation, relative placements and Unicode placeholders are F5c's. - The snapshot,
Snapshot::images: the placements that the view shows, each of its image, its column and its row in the view, negative above it, its columns and rows, its z, under the text when negative, under the cells' backgrounds too below −2³⁰, as kitty's protocol tells and the app draws it, and whether it keeps its proportions; the lowest first. Nothing, and no cost, without placements.
Unicode
- Tables generated from the UCD by
cargo xtask ucd, for Unicode 18.0.0, pinned in the repo. They cover:- East Asian Width, Emoji_Presentation, Extended_Pictographic;
- the marks (Mn, Me, Mc), the format characters (Cf) and the default ignorable ones;
- Grapheme_Cluster_Break, and Indic_Conjunct_Break for rule GB9c of UAX #29;
- the East Asian Width of Unicode 8, for
unicode-widths = "8". unicode-widthis not enough, because it does not matchwcwidth.
- The generated file (
crates/vt-core/src/unicode/tables.rs) is committed, with the name and date of every UCD file it comes from.just ucd-checkdownloads the files again and checks that they give the same file. The range tables are searched by binary search, one property at a time. Printing reads a table of three stages instead, generated from the same data, which gives in one lookup the eight properties that printing reads: both East_Asian_Widths, Grapheme_Cluster_Break, Indic_Conjunct_Break, Extended_Pictographic, and whether the code point is a mark, a format character or default-ignorable. The generator picks the block size that takes the fewest bytes: about 34 KiB for Unicode 18. The range tables stay as the reference that a test compares the table with, for every code point. unicodemode (default): grapheme segmentation per UAX #29, with the width computed for the whole cluster.- The segmenter takes one codepoint at a time, as text arrives, and passes the conformance test of the UCD,
GraphemeBreakTest.txt, whichcargo xtask ucdcopies next to the tables. - Unicode 18 changed rule GB9c: a consonant joins after a linker and extenders, with no consonant needed before the linker.
- A cluster is as wide as its first codepoint that has a width, its base, which is its first one unless a prepended character of no width comes before it, except that emoji presentation, which reads the base and what follows it, changes it: VS16 after a pictographic or a keycap base gives 2, VS15 gives 1, and a flag, a pair of regional indicators, or an emoji ZWJ sequence gives 2. Past emoji presentation, a codepoint after the base that has a width of its own, but an emoji modifier or a prepended character, gives 2: a vowel sign that spaces, as Bengali's া after ক, or a consonant that a virama joins, as in Devanagari's क्ष, as
wcwidth0.9, Ghostty, vim and the programs that count codepoint by codepoint give them, though a cluster takes two cells at most where they give some three. Printing counts a cluster as its codepoints come, each changing its width alone, as Ghostty does: a codepoint that has a width widens it, VS16 widens an emoji and VS15 narrows it, and a cluster that had no room for its second cell keeps one. With the Unicode 8 tables, which knew no emoji presentation, a cluster is always as wide as its first codepoint that has a width.
- The segmenter takes one codepoint at a time, as text arrives, and passes the conformance test of the UCD,
legacymode: one codepoint at a time, likewcwidth, for programs that compute widths themselves. A codepoint of no width joins the cell before it.- The width of a codepoint, as Markus Kuhn's
wcwidthcounts it: none for controls, nonspacing and enclosing marks, format and default-ignorable characters, and the Hangul vowels and final consonants that combine into syllables, but one for the soft hyphen, and the cells of their East Asian width for the Hangul fillers U+115F, U+3164 and U+FFA0, which are default ignorable; two for wide and fullwidth characters, and for the ambiguous ones when they count as wide; one otherwise. Inunicodemode with the current tables, aswcwidth0.9 and Ghostty count them: two for a regional indicator, alone as in a flag, and one for the prepended concatenation marks, format characters that show over the digits after them, as U+0600 ARABIC NUMBER SIGN. - Mode 2027: lets programs query and switch the mode.
- Width tables that match the programs': a program that counts a character's width differently from the terminal misplaces the cursor and the text after it. Two options make the terminal count as the programs do, in either mode:
unicode-widths: the tables of the Unicode version that Lokyr ships, or those of Unicode 8, for programs that predate Unicode 9. Unicode 8 gives most emoji one cell, and Unicode 9 gave them two.xtask ucdgenerates the Unicode 8 table too.ambiguous-width: the cells that East Asian Ambiguous characters take (①, ※, ○, Greek and Cyrillic letters…): 1 by default, 2 for CJK setups whose programs count them as two, like vim'sambiwidth=double. It is an explicit option, not a guess from the locale, because it must match the programs.- A change applies to new output; the cells already written keep their widths.
- Normalization: the
normalizationoption puts the text in a Unicode normal form as it is printed: none (the default), NFC, NFD, or HFS+, Apple's variant of NFD, which leaves the ranges U+2000–U+2FFF, U+F900–U+FAFF and U+2F800–U+2FAFF alone. NFC shows the decomposed names of macOS files composed, Hangul included, and a composed character takes no grapheme entry. Each cluster is normalized as it is built, and text already in the normal form passes a quick check without being rewritten. The terminal's buffers are reused, but the crate keeps up to four combining marks inline while it reorders them, so a cluster with more allocates, once with five and three times with six. Such clusters are rare outside of stacked marks for effect, so the terminal keeps the crate rather than decompose into its own buffers, which would mean canonical decomposition and reordering of its own. The data comes from theunicode-normalizationcrate, at Unicode 17 while the tables are at 18: canonical decompositions never change for existing characters, so the gap covers at most the new characters of Unicode 18 that have one.
Settings
The [terminal] section of the config:
[terminal]
term = "xterm-256color" # what TERM tells programs: xterm-lokyr, xterm-256color, xterm, ansi, vt100, vt220, dtterm, linux…
unicode-widths = "current" # current | 8
ambiguous-width = 1 # 1 | 2
normalization = "none" # none | nfc | nfd | hfs+
term changes only what programs are told, never the emulation, which stays xterm's: the session puts it in the environment, and the terminal reports it as TN to XTGETTCAP. The other values describe subsets of what xterm does, so they work as they are.
Input
- Keyboard:
input::encode_key, from aKeyEventthat the platform makes once dead keys and input methods are resolved: the key; whether it went down, repeats or went up; its modifiers, with the two Alt keys told apart, and the locks; what it types with every modifier; what it types with Shift alone, as macOS'scharactersIgnoringModifiersgives it; and the key in the same place on the standard PC-101 layout. The kitty flags in force choose the encoding.- Legacy xterm encoding, while no flag is set. Releases send nothing, and a repeat is one more press.
- Control maps characters to C0 as xterm does: the letters and
@[\]^_, space and2to NUL,3to7to ESC and the four after it,/to US,8and?to DEL; other characters go as they are. With Control or Meta, and without Shift, a key whose character is not ASCII goes as the key of the base layout, as kitty's legacy encoding has it, so that Control withсin a Cyrillic layout sends ETX. Backspace sends DEL, and BS with Control; Shift with Tab sendsCSI Z, which Control leaves as it is and Meta sends after ESC; Return sends CR, or CR LF in LNM. - The cursor keys, Home and End send
CSI final, orSS3 finalin application mode (DECCKM); Insert, Delete, Page Up and Page DownCSI n ~; F1 to F4SS3 PtoSS3 S, F5 to F20CSI n ~, and Menu F16'sCSI 29 ~. With modifiers, they all sendCSI 1 ; m finalorCSI n ; m ~, wheremis 1 plus 1 for Shift, 2 for Meta and 4 for Control. The keypad sendsSS3codes in application mode (DECKPAM), and what it types otherwise, with ESC first for Meta, but neither Control's codes normodifyOtherKeys's form, as in xterm; without Num Lock, its keys send what the keys they stand for send, and its 5CSI E. The locks, the modifier keys, Print Screen, Pause, the media keys and F21 to F35 send nothing. - An Alt that acts as Meta, as
KeyOptionssays for each side, sends ESC before the key, typed without Alt; one that does not types what the platform composed with it, as Option's characters on macOS, and is no modifier for the sequences. ESC is sent whatever mode 1036 says, which is reported but changes nothing: xterm's eight-bit Meta does not suit UTF-8. modifyOtherKeys, which programs set withCSI > 4 ; n mand query withCSI ? 4 m: at 1, the keys whose usual sequence loses a modifier, such as Control with a digit, Control and Shift with a letter, or Return with Control or Shift, sendCSI 27 ; m ; code ~; at 2, as xterm'sinput.chas it, every key that types a character does with Control or Meta, and so do Return, Escape and Backspace with any modifier, Shift alone included, but for Backspace with Control, which sends BS and is reported only with another modifier, with the code of BS; with Shift alone, so do space and the characters from@to DEL, which include the letters, when the key types that character, so that what Option or a dead key composes types. The keypad, the cursor keys and the function keys keep their own sequences, with their modifiers. Shift with Tab is reported with Control or Meta at either level.CSI > 4 m,CSI > m, which the parser reads asCSI > 0 m, andCSI > 4 nreset it, and so does RIS.
- Control maps characters to C0 as xterm does: the letters and
- The kitty keyboard protocol, once a program sets flags, with every flag.
- Text: a key that types text sends it, unless every key is reported. A key types nothing with Control, an Alt that acts as Meta, Super, Hyper or Meta, nor when the platform's text has a control character. Enter, Tab and Backspace without modifiers, the locks aside, send their legacy bytes and no release, so that a shell stays usable after a program that left the flags set.
- Escape codes: the other keys send
CSI code ; modifiers u, with the code of the character the key types unshifted, or the number of the protocol's table, orCSI 1 ; modifiers finalandCSI code ; modifiers ~for the keys that xterm sends those for; F3 isCSI 13 ~, sinceCSI Ris a cursor position report. The modifiers are 1 plus 1 for Shift, 2 for an Alt that acts as Meta, 4 for Control, 8 for Super, 16 for Hyper, 32 for Meta, 64 for Caps Lock and 128 for Num Lock; with none, the field goes, and so does a code of 1 with nothing after it. For a modifier key, the platform gives the modifiers as the event leaves them. Cursor key mode, the keypad's application mode andmodifyOtherKeysdo not apply. - Disambiguate (1): Esc, and the keys that a modifier such as Control or an Alt that acts as Meta keeps from typing, send escape codes, and the keypad's keys that type nothing send their own numbers.
- Event types (2):
:2after the modifiers for a repeat,:3for a release, which a key that types text reports as an escape code. Without the flag, a repeat is one more press and a release sends nothing. - Alternate keys (4): keys that type characters send
code:shifted:base, the shifted key with Shift, if it differs, and the key of the base layout, if it differs;code::basewithout the first. - All keys (8): every key sends an escape code, Enter, Tab, Backspace and the keys that type text included. The modifier keys and the locks are reported only with this flag.
- Associated text (16): the text that a press or a repeat types follows the modifiers, as codepoints separated by colons.
- Without disambiguation or every key, presses that xterm has a sequence for send it, cursor key mode included, unless Super, Hyper, Meta or a lock is held, which xterm's sequences cannot carry; those, and keys that xterm has no sequence for, send their escape codes.
input::encode_textencodes text that no key typed, such as what an input method commits: as it is, orCSI 0 ; ; codepoints uwhen every key and its text are reported.
- The kitty flags live on a per-screen stack (
CSI > u,CSI < u,CSI = u,CSI ? u).
- Legacy xterm encoding, while no flag is set. Releases send nothing, and a repeat is one more press.
- macOS specifics:
- Option can act as Meta, configurable separately for the left and right keys;
- dead keys are supported;
- IME composition text is never sent to the PTY.
- Mouse:
input::encode_mouse, from aMouseEvent: a press, a release, a motion with a button held or none, or a step of the wheel, with the modifiers and the cell and the pixel under the pointer. It returns whether the event goes to the program rather than to the terminal, which selects text and scrolls with the others.- Tracking: X10 (9) reports the presses of the first three buttons, without modifiers; 1000 presses, releases and the wheel; 1002 also motion with a button held; 1003 every motion. The platform reports a motion only when the cell changes, or the pixel, for reports in pixels.
- Codes: the first three buttons are 0 to 2, buttons 8 to 11 are 128 to 131, and the wheel 64 to 67; a motion adds 32, and Shift 4, either Alt 8 and Control 16.
- Encodings: X10's
CSI Mand three bytes, the code and the column and row from 1, each plus 32, where a release is 3, whichever button went up, and positions past 222 are the byte 0, as in xterm; SGR (1006),CSI < code ; column ; row M, ormfor a release, which keeps the button; SGR-pixels (1016), the same with the pixel, from 1. - Alternate scroll (1007): without tracking, on the alternate screen, each step of the vertical wheel sends the up or down cursor key, as cursor key mode has it.
Options::alternate_scrollsays whether it is on as the terminal starts, and after RIS: off by default, as xterm'salternateScroll; the app turns it on, so that the wheel scrollslessandman.
- Paste:
input::encode_paste. With bracketed paste (2004), the text goes betweenCSI 200 ~andCSI 201 ~; without, each line break, CR LF, LF or CR, goes as CR, as Return sends it. Either way, the control characters other than tab and the line breaks are left out, C0, DEL and C1 alike, so that a paste can neither end the bracket with its ownCSI 201 ~nor send ESC to an editor (SECURITY.md). - Focus events:
input::encode_focussendsCSI IandCSI Oin mode 1004.
PTY and processes (pty)
- Spawning:
pty::spawn(&Options)returns aPty, which gives readers and writers of the terminal, its device's name, the program's process id and the terminal's foreground process group./dev/ptmx,grantpt,unlockpt,ptsname_rand the slave opened withO_NOCTTY, both sides closed on exec as they open, and the terminal's size; then fork+exec throughstd::process::Command, with the slave as standard input, output and error. Between fork and exec the child marks every other descriptor closed on exec, so that the program has the terminal alone, though the app inherited descriptors without the mark, as a launcher or a CI runner leaves them: Linux marks them with one call ofclose_range, and macOS marks those thatproc_pidinfolists as open, into room that the parent made, so that a spawn costs the same with a soft limit of millions; where the call fails, as on a kernel without it or withoutCLOSE_RANGE_CLOEXEC, before 5.11, or under a filter that denies it, on a system with neither, or with more open than the room holds, each descriptor below the soft limit, 65 536 at most, is marked in turn. The parent keeps no copy of the slave, so the master reads the end when the program and its children have gone; the reader turns the EIO that Linux gives then into the end.- The master does not block: readers and writers wait for it with
poll, and for a descriptor that becomes ready, for good, as thePtydrops: on macOS, a kqueue with a user event that the drop triggers, which no child inherits, by a fork or a spawn; elsewhere, a pipe opened closed on exec, whose end to write the drop closes.PtyReader::read_untilreads with a deadline,PtyReader::wait_eitherwaits for output and for room at once, for a caller that reads and writes on one thread, andPtyReaderandPtyWriterimplementReadandWriteon top of the waits. - An async-signal-safe
pre_execrunssetsid()andioctl(TIOCSCTTY), empties the signal mask, which the child has from the thread that spawned it, and gives every signal its default action, since an ignored one stays ignored across exec. - The crate's spawns take no lock. On macOS,
stdopens the pipe through which a spawn learns that its child failed to exec, then marks it closed on exec, so that a spawn on another thread in between gives its child the pipe; that child marks it with its other descriptors, and the pipe closes at its exec rather than when its program ends. That holds for the crate's spawns alone, whose children mark their descriptors: the child of astd::process::Commandelsewhere in the app marks none, and holds the pipe of a spawn made at the same moment until its program ends, which that spawn waits for, as it would have with a lock. The app's later spawns go through this crate, or have their children mark their descriptors as it does. The parent opens the working directory before the fork, to be searched rather than read, for the child to enter withfchdir, a directory that cannot be opened failing at once with an error of its own; and it looks the program up, so that the child's exec gets the path found and walks noPATHbetween fork and exec: in thePATHof its environment, or the system's default, asexecvplooks, relative entries in the working directory made absolute, a candidate needing an execute bit in its mode as well asaccess, which an ACL can pass for a file thatexecverefuses. The program keeps its name asargv[0], and one that cannot be run fails at once, withEACCESorENOENTasexecvpwould: on macOS, a directory ofPATHthat cannot be searched counts as the program not there, and off macOS the lookup stops at the first error other than those that glibc'sexecvppasses over, as a loop of links. The errors' messages leave their cause to the error's source, so that a chain tells it once. - We do not use
posix_spawn, because it cannot set the controlling terminal, noropenpty, which closes the descriptors on exec only after it opens them, and gives up when the kernel fails an open of/dev/ptmxwithEREDRIVEOPEN(-6). macOS's kernel does that at times when several processes open pseudo-terminals at once, for an errno meant for itself alone; the open is tried again. - The program starts in the working directory that the caller gives, or the account's home directory, read from the system's user database with the name and the shell.
- Login shell: on macOS, launched as Terminal.app launches it:
/usr/bin/login -flp $USER /bin/bash --noprofile --norc -c "( exec -l -a <name> <shell> ); status=$?; printf '\033]133;D;%d\007' \"$status\"; exit \"$status\"".loginrecords the session as a terminal's;-fskips the password, the account being logged in already;-pkeeps the environment;-lkeeps the working directory, and keeps the shell from being a login shell too, so bash starts it with-before its name.loginexits with 0 whatever the shell's status, and closes the descriptors past the terminal's: bash waits for the shell, in a subshell, and tells its status through the terminal, as OSC 133's end of a command,D ; status, with 128 and a signal's number for a shell that a signal ended, as shells give it. The window takes that status for the login shell. The waiting bash is one process more for each session.- On Linux, the shell is started with
argv[0]prefixed by-.
- Environment:
TERM, from thetermoption (Settings),COLORTERM=truecolor,TERM_PROGRAM=lokyr,TERM_PROGRAM_VERSION, the app's version as XTVERSION gives it,LOKYR_RESOURCES_DIRwhen the caller gives it, the app's own command's directory at the end ofPATHwhen the caller gives one, unlessPATHhas it, and the caller's own variables last.- A UTF-8 locale in
LANGif none ofLC_ALL,LC_CTYPEandLANGis set; the caller chooses it (SECURITY.md). TERMINFO,COLUMNSandLINESare not inherited: they would describe the terminal that started this one, if one did.TERMINFOis set only whenTERMisxterm-lokyrorlokyrand the caller gives the resources, to theirterminfodirectory.
- Resize:
Pty::resize,TIOCSWINSZwith sizes in both cells and pixels; sixel and kitty graphics need the pixels. The kernel sends SIGWINCH to the foreground process group. Resizes are coalesced while the window or a divider is being dragged: the grid follows each step, reflowing, and the program learns the size every 25 ms at most, and once more after the last step, so that it redraws a few times a second rather than at each step. A grid that comes back, within the pace, to the size that the program was told, which a resize there and back changed meanwhile, is told by SIGWINCH to the terminal's foreground process group,Pty::signal_resize, asTIOCSWINSZof the same size signals nothing. - Process exit: EOF on the master plus
waitpid:Pty::waitandPty::try_waittell anExit, a status or the signal that ended the program. The end that the master reads can come after the program's exit, when processes that it started still have the terminal open, or never, so the exit is told apart from it. What happens next is configurable: close the pane, or show the exit code. - Closing: dropping a
Ptyhangs the program up as closing a terminal does, with SIGHUP to the program and to a job in the terminal's foreground, and ends what its readers and writers wait for: reads end, writes fail, and the terminal closes once they drop, so that a program that ignores SIGHUP sees the end of its input. A thread waits for the program, so that it leaves no zombie. - Portable API: the public interface (reader, writer, resize, child) exposes no
RawFd. A future ConPTY implementation for Windows will therefore not change any callers.
Session (session)
Session:Session::spawnstarts the program in a PTY, with aTerminalof the PTY's size, and two threads;Session::locktakes the grid lock;key,mouse,focus,textandpasteencode input with the terminal's modes and keyboard flags, andwritesends bytes as they are;scrollmoves the view;resizeresizes the grid, then the PTY;resize_ptythe PTY alone, for an embedder that resized the grid at once and tells the program at its own pace.wake, given tospawn, is called when the terminal changes and the main thread has seen the last change,clear_wakesaying so, and when the output ends;has_endedandexittell the end and the status. Dropping the session hangs the program up, and its threads end.- I/O thread: one per pane. It reads slices of at most 64 KiB, outside the lock, and feeds them to the parser under the grid lock, which it releases fairly after each slice: a thread that waits for the lock has it before the next slice. Before each slice, the I/O thread waits for the threads that came to the lock before it asked; those that come later wait for its slice to start. Each side has the lock in turn, however often the other takes it.
- Write queue: collects input (keys, pastes, replies to terminal reports), in order, for a writer thread, which writes each entry in chunks of 4 KiB and stops between two once the session closes. A paste is one entry, so that no reply comes between its brackets. The I/O thread does not write: a program that floods its output without reading its input, while it asks for replies, would otherwise stop both sides. The queue takes a slice's replies while less than a MiB of replies waits, the one that the writer writes until it asks for the next included, and drops them past it, so that such a program cannot grow the queue without end: as a slice's replies take a MiB at most too, as the terminal keeps them, about two MiB of replies wait at most. Keys, pastes and the clipboard's answers are never dropped, nor counted:
Session::reply_clipboardqueues the answer at once, as a program can wait for it without writing anything. - Synchronized output: each update that starts, a new value of
Terminal::synchronized_updates, gets a deadline, by default a second away, which the I/O thread keeps, its read waiting until then at most; past it, it ends the update withTerminal::end_synchronized_output, unless another has started. Output during the update does not put the deadline off, nor doesCSI ? 2026 hagain, and a write that blocks or fails cannot keep it. The end of the output ends the update under way at once, and so does the end of the I/O thread by a panic, which ends the session as the output's end does, waking the main thread. - The view: the rows that a renderer shows, the primary screen's or, scrolled up, the scrollback's above it.
Terminal::scroll_viewport, andSession::scroll, move it by rows, by pages of the screen's rows, to the scrollback's top and back to the screen, and to a row by its number, at its top,Scroll::Row;Terminal::viewport_offsettells how many rows it is above the screen's top, the rows that folds take out of the list counted as the list's. Above the screen, a pin on its first row keeps it on its rows as output scrolls the screen under it, and through a reflow; a view whose first row leaves the scrollback, as its oldest rows go, is at the scrollback's top, and one that a reflow brings down to the screen follows the screen again. The alternate screen, without a scrollback, has no view of its own: entering it, and ED 3, bring the view back to the screen. Input that sends anything, a key, a paste or committed text, brings it back too; output does withOptions::scroll_on_output, off by default, whichTerminal::set_scroll_on_outputchanges.Terminal::scroll_viewport_by, andSession::scroll_by, move it by a share of a row too, as a trackpad's points scroll it: whole rows move the view, and the rest is the share of a row that it is scrolled past its first row,Terminal::viewport_fraction, from 0 to under 1, kept with the view's origin, so that any other scroll, output that brings the view back to the screen, a resize, the scrollback's limit that takes its first row and the alternate screen let it go; none at the scrollback's first row nor at the screen, where the view stops. The view's rows, their numbers and what a caller reads of them stay whole rows · Since 1.4. - Renderer snapshot:
Session::snapshotbrings aSnapshot, which the renderer keeps from frame to frame, up to date under the lock, withTerminal::snapshot: it copies the rows of the view that are dirty, each with the styles that its cells use, its clusters' codepoints, its soft wrap and its prompt's start, and the cursor, in the view's rows and hidden when the view is above it, the colors and reverse video. The scrollback's rows come in as they are, from cold pages too; one that changed on the screen before it scrolled up, without an update between, is dirty, and copied once.Snapshot::colors_changedsays when the colors or reverse video changed since the last update, which calls for drawing every row again, copied or not. Rows that the screen scrolled, or that the view moved over, are not copied again: the page list counts the screen's scrolls, so the snapshot moves the lines it has, up or down, as the view's first row moved, and copies those that came in, the moves of a view on its rows copying nothing; a resize or a reflow starts a new epoch of the list, and another screen is another list, after which every row is copied. A snapshot of an unchanged screen copies nothing. While a synchronized update holds the screen, the snapshot stays as it was. While the view is scrolled a share of a row past its first,Snapshot::fractiontells it, and the lines end with the row past the view's last,Snapshot::below, at the view's rowSnapshot::rows, of its cursor, selection, decorations, gutter's marks, blocks, matches and images, so that a renderer draws the view a share of a row up and that row at its bottom;Snapshot::rowsstays the view's rows, andSnapshot::drawn_rowscounts the row below too · Since 1.4. - Independence from the main thread: the I/O thread never waits for it. If the renderer falls behind, it jumps straight to the latest state.
- Encodings (F5b): the terminal works in UTF-8 only. Other encodings, chosen per profile, come after the MVP as a conversion in the session, with
encoding_rs: the bytes from the PTY become UTF-8 before the parser, and the input goes back in the program's encoding. Latin-1, windows-125x, Shift_JIS, EUC-JP, EUC-KR, GB18030, Big5 and ISO-2022-JP are among them. C1 controls stay 7-bit only.
Terminfo
- The entry:
xterm-lokyr, also namedlokyr, incrates/vt-core/terminfo/xterm-lokyr.terminfo. It stands alone, with nouse=, so that it compiles the same on any machine, whateverxterm-256colorthe machine's database holds.- It is
xterm-256coloras ncurses 6.0 describes it, without what the terminal does not do: printing (mc0,mc4,mc5,mc5i), meta mode (smm,rmm) and memory lock (meml,memu).kbsis DEL, which Backspace sends,Serestores the cursor style that the config sets (CSI 0 SP q), andkmousis\E[<, so that ncurses asks for SGR mouse reports, which have no limit of 223 columns as X10's do, as Ghostty's entry does; ncurses reads them since late 2014, so the 6.0 library that macOS ships does too, andXM, which later versions read, turns them on. - It adds:
Tc,setrgbfandsetrgbb(24-bit color).RGBis left out: next tocolors#256, ncurses 6.1 and later would read it as direct color with 3, 3 and 2 bits per channel;SuandSmulx(styled underlines) andSetulc(underline color);Smol/Rmol(overline) andsmxx/rmxx(strikethrough);Sync(mode 2026);BD/BE/PS/PE(bracketed paste);fe/fdandkxIN/kxOUT(focus events);XM(SGR mouse reports, withkmous);hs,tsl,fslanddsl(the title as a status line);oc(OSC 104) andrep(REP).
- It keeps, from
xterm-256color,Ss/Se(cursor style),Ms(OSC 52),Cs/Cr(cursor color),E3andXT.
- It is
- Build:
cargo xtask terminfo(just terminfo) compiles it withtic -xintotarget/terminfo, in the layout of theticthat compiles it: hexadecimal directories on macOS (78/xterm-lokyr), letters on Linux. macOS's owntic, from ncurses 6.0, is enough: the entry's numbers stay below 32768, so that anyticwrites the legacy format, which every ncurses reads, macOS's own library included. The task fails ifticwarns, ifinfocmp -xdoes not read every capability of the source back with its value, its escapes undone so that the way of writing it does not count, or if the format is another. Colons are written plain, asinfocmpwould escape them. - Install: the app bundles it, in
Contents/Resources/terminfoon macOS andshare/terminfoon Linux, andTERMINFOpoints there whenTERMisxterm-lokyrorlokyr(PTY). - XTGETTCAP answers from the same source, by terminfo name: a boolean with
DCS 1 + rand its name, a number in decimal, a string as the terminal sends or reads it (kbsis7F), without the padding ($<100/>) that onlytputsreads, and a string with parameters as the source writes it, for the program to fill in, as Ghostty and kitty do. It also answers xterm's own names:TNandname, theTERMthat programs see;Co, the colors' termcap name; andRGB,8/8/8, the bits of each channel of a direct color. It does not answer other termcap names. - Default
TERM:xterm-256color, because remote hosts usually don't knowxterm-lokyr. Thetermoption chooses another (Settings). The default may change once an ssh integration, put off for now, installs the terminfo on remote hosts or falls back automatically.
Supported protocols
The sequences that the core reads, each with the version that brought it and its specification, are in Escape codes, with how a program finds Lokyr and the exact replies to its queries. Still to come: kitty's graphics' placeholders and the rest of its protocol, and Sixel (DCS q), in F5c; OSC 1337's SetUserVar, CurrentDir, RemoteHost and ShellIntegrationVersion, through a plugin.
Sequences that the core doesn't read are ignored. Debug builds also log them, so the list of missing sequences comes from real sessions.