terminal library
The terminal without the render tree and the app: for a logger, a prompt or a command-line tool that writes lines and reads keys rather than drawing frames. Terminal opens the process's terminal (or one over a TerminalLink, or plain output where it takes no sequences) and says what it is (TerminalInfo, TerminalCaps); colorModeFor, plainAsked and runsInCi say what the environment asks for; StyleTable interns styles of Colors and Attrs, which a LineEncoder writes as lines of text with their SGR sequences; InputParser decodes the bytes read into InputEvents (KeyEvent, MouseEvent, PasteEvent, …); stringWidth, TextSegmenter and fitText measure and cut text in cells; the terminal's own sequences (a title, progress, a notification, the clipboard) are strings to write; and LogSink keeps what log records.
Import it in place of package:twk_core/twk_core.dart where nothing
is painted on a screen of cells: it compiles in about two thirds of the
time, the render tree and the frame loop left out. Every name it
exports is the same declaration as twk_core.dart's, so a program may
import both.
A question on the line the cursor is on, answered with one key, in a
program whose one import is package:twk_core/terminal.dart:
Future<void> main() async {
final terminal = await Terminal.open(
const TerminalOptions(alternateScreen: false, mouse: false),
);
final styles = StyleTable(colorMode: terminal.info.colorMode);
final ask = styles.style(fg: Color.yellow, attrs: Attr.bold);
final line = LineEncoder(styles, ansi: !terminal.info.plain)
..text(ask, 'Continue?')
..text(StyleId.base, ' [y/n] ')
..end();
terminal.write(line.out.view);
final key = await terminal.events.firstWhere((e) => e is KeyEvent);
await terminal.close();
print(key == const KeyEvent(KeyCode.char, char: 'y') ? 'yes' : 'no');
}
See also:
package:twk_core/twk_core.dart, the whole core: the screen of cells, the presenter, the render tree and the app that runs it.
Classes
- Attr
-
The bits of text attributes, combined with
|into a Pen.attrs. - ByteSink
- A growable byte buffer that the presenter writes a frame into: bytes, ASCII, decimal numbers, UTF-8 code points and CSI sequences, with no allocation per write.
- ClusterScan
- Result of scanning one cluster; reused to avoid allocation.
- ColorReport
- Reply to OSC 10/11 (foreground/background color query) or OSC 4 (a palette entry: which 4, the entry's index).
- ColorSchemeReport
-
The terminal's color scheme turned dark or light (DEC mode 2031):
CSI ? 997 ; 1 ndark,CSI ? 997 ; 2 nlight.Terminalturns the reports on where the terminal has them, and asks for its default colors again after each one: their ColorReports follow. - CursorReport
-
The reply to a cursor position query (CPR,
CSI 6 n):CSI row ; col R. - DeclaringLink
-
A TerminalLink whose terminal declares what it does
(TerminalDeclaration), which
Terminaltakes over its guess: the link to atwk shell(SocketLink, the welcome'sdeclares), and the terminal a shell serves (TerminalShellpasses it on in its welcome). - DeviceAttributes
-
The reply to the primary device attributes query (DA1,
CSI c):CSI ? params c. - FocusEvent
-
The terminal window gained or lost the input focus: reported where the
terminal has focus reports (DEC mode 1004) and
TerminalOptions.focusEventsis on, the default. - InputEvent
- One thing a terminal sent: what the user did (KeyEvent, MouseEvent, PasteEvent, FocusEvent), the terminal's new size (ResizeEvent), a reply to a query, or a sequence nothing here maps (UnknownSequence).
- InputParser
- Decodes the bytes a terminal sends into InputEvents, read by read.
- KeyboardFlagsReport
-
Reply to the kitty keyboard protocol query (
CSI ? flags u): the terminal implements the protocol; flags are the ones currently active (KittyKeyboardFlags). - KeyEvent
- A key typed: which one (code, with char the character it types), the modifiers held (modifiers) and, with the kitty keyboard protocol's KittyKeyboardFlags.eventTypes, whether it went down, repeats or came up (kind).
- KittyKeyboardFlags
-
The progressive enhancements of kitty's keyboard protocol
(sw.kovidgoyal.net/kitty/keyboard-protocol), bits of the flags a
program pushes (
CSI > flags u,TerminalOptions.kittyKeyboardFlags) and a terminal reports (KeyboardFlagsReport.flags). Each makes the terminal report more of the keyboard. InputParser decodes what each sends, but the base layout key of alternateKeys; a key that types text (no modifier but Shift) is the text it types, Shift not among its modifiers, as typed text is without the flags. - LineEncoder
- Writes lines of text, each from runs of text in a style (text) or from a row of a Surface (row), into out: with ansi, each style as the shortest SGR sequence from the one before in the styles' colour mode, and where hyperlinks are taken too, each link as OSC 8, its target percent-encoded as the Presenter writes it (linkTarget); without ansi, the text alone.
- LocalAddress
- A local socket's address and the token a client sends first.
- LogRecord
- One entry of a LogSink: when, how much it matters, the message, and the error and its stack where there are.
- LogSink
- The records of one app: the last capacity of them kept in a ring for listeners that come later (a console overlay), every one passed to the listeners as it comes and, with a path, appended to that file; while it serves, sent to the clients of its socket too.
- Mod
- The bits of KeyEvent.modifiers and MouseEvent.modifiers, one per modifier key held: the values xterm and the kitty keyboard protocol encode as their modifier parameter less one.
- ModeReport
-
DECRPM reply to a DECRQM query:
CSI ? mode ; value $ y(value 1 set, 2 reset, 3 permanently set, 4 permanently reset, 0 unknown). - MouseEvent
- What the mouse did (kind), in which cell (x, y), with which button and modifiers.
- MouseTrackingBackend
-
A TerminalBackend whose mouse reports can be switched while it is
open (Terminal,
HeadlessTerminal), so that an app has on only what it uses: while it uses none, the terminal's own selection and wheel work. - PasteEvent
-
Text pasted into the terminal, all in one event: what bracketed paste
mode (
TerminalOptions.bracketedPaste) brackets, so keys in it (an Enter, a Ctrl+C) are text and act on nothing. A paste longer than InputParser.pasteLimit comes in several, one after another, each but the last with more set: a field inserts each as it comes, and what takes a paste as one thing (a message to send) joins them. - Pen
-
A paint style.
nullcolors inherit from the cell being painted over (like Flutter text over a background); colors with alpha < 255 are blended: the background over the existing one, the text over the background the cell ends up with. A background with alpha 0 leaves the cell's background as it was. - ResizeEvent
-
The terminal's new size in cells: decoded from an in-band resize report
(DEC mode 2048,
CSI 48 ; rows ; cols ; ... t), or delivered byTerminalwhen the size it watches changes. - StyleTable
- Interned cell styles (style id StyleId.base = all defaults) and registered pens.
- SuspendableBackend
-
A TerminalBackend that can hand the terminal to another program and
take it back (Terminal);
TwkApp.suspenddoes both around the other program. - Terminal
- A terminal a program draws on and reads input from, opened in raw mode, asked what it can do, and put back as it was however the program ends.
- TerminalBackend
-
What the frame loop (
TwkApp) needs from a terminal: Terminal is the real one; a test can stand in with a fake. - TerminalCaps
- What the presenter may assume about the terminal.
- TerminalDeclaration
-
What a terminal says it does, in place of what twk would guess from its
name: a terminal that is none of those twk knows (an editor's terminal,
an emulator in a test) declares it rather than pretending to be one
with a
TERM_PROGRAMthat says more than meant. - TerminalInfo
- What Terminal found out about the terminal as it opened it: what it asked the terminal, what the terminal answered, and what its environment tells.
- TerminalLink
-
A terminal's input, output, size, environment and console modes: what
a
Terminalruns over. - TerminalOptions
- How Terminal opens a terminal: the screen it draws on, the input it asks for, how long it waits for answers.
- TerminalStateBackend
-
A TerminalBackend that keeps state an app set on the terminal beyond
its screen (the pointer's shape, the progress in its tab) and puts it
back as it was on every way out, as it does the modes it opened with:
Terminal,
HeadlessTerminal. - TextSegmenter
- Segments text into terminal cells and computes their widths.
- UnknownSequence
- An escape sequence the parser recognised as one but doesn't map to an event: a key it has no KeyCode for, a reply to a query it doesn't decode, a sequence cut off or aborted by the next ESC.
- WindowBackend
-
A TerminalBackend that sets the title of the terminal's window or tab
and shows desktop notifications (Terminal,
HeadlessTerminal). A backend that wraps a terminal implements it to pass both on; twk'sTerminalTitleandAppBinding.notifydo nothing on a backend without it.
Enums
- BidiReordering
-
Who puts right-to-left text in the order it reads on a terminal
(
TerminalInfo.bidi). - Brightness
- Whether colors are dark or light: a terminal's background, its color scheme (ColorSchemeReport).
- ColorMode
- The colors a terminal shows, which a StyleTable brings its colors down to as it writes them.
- GraphicsProtocol
- How a terminal shows images.
- KeyCode
- The key a KeyEvent is for: char for a key that types a character, the rest for keys without one.
- KeyKind
- What happened to the key of a KeyEvent.
- LogLevel
- How much a LogRecord matters, from the least to the most.
- MouseKind
- What the mouse did in a MouseEvent.
- MouseTracking
- What the terminal reports of the mouse, each value what the one before it reports and more, at more bytes: a DEC mode each, with SGR coordinates (mode 1006).
- Multiplexer
- The terminal multiplexer between a program and the terminal, which keeps sequences it doesn't know from the terminal unless they are wrapped (passthroughSequence).
- NotificationProtocol
- How a terminal shows a desktop notification (notifySequence).
- PointerNames
- How a terminal names the shapes of the mouse pointer in OSC 22 (pointerShapeSequence).
- PointerShape
-
The shapes of the mouse pointer OSC 22 sets (pointerShapeSequence),
by the names of CSS's
cursor(css), as kitty's protocol names them, or by the X cursor font's (x11), as xterm and iTerm2 do. - ProgressState
- What a program's progress in the terminal's tab or taskbar shows (progressSequence), by the number OSC 9;4 gives it (code).
- TextAlign
-
Where a
RenderParagraphputs each line across its width. A line wider than the paragraph starts at the edge its paragraph starts at: the left one, or the right one for a right-to-left paragraph in visual order (TextOrder.visual). - TextMode
- How text is split into terminal cells.
- TextOverflow
-
How a
RenderParagraphshows that it cut text off: a line too long for it (orfitText), or the lines beyond itsRenderParagraph.maxLines.
Extension Types
- Color
- A terminal color: the terminal's default, an entry of its palette, or 24-bit RGB, packed into a small int (always a Smi):
- StyleId
- The id of a cell's style in a StyleTable: its colors, attributes and link, each set of them interned once (StyleTable.style).
Constants
- popTitleSequence → const String
- XTWINOPS that pops the titles pushTitleSequence pushed, putting them back.
- pushTitleSequence → const String
- XTWINOPS that pushes the window's and icon's titles on the terminal's title stack, for popTitleSequence to put back.
- unicodeVersion → const String
- The version of the Unicode Character Database the segmentation, width and bidi tables are generated from.
Functions
-
clipboardSequence(
String text, {Multiplexer multiplexer = Multiplexer.none}) → String -
Returns OSC 52, which puts
texton the system clipboard, wrapped formultiplexer(passthroughSequence). -
colorModeFor(
Map< String, String> env, {bool windows = false}) → ColorMode -
The colors a terminal supports, from its environment: none where
NO_COLORis set to anything but an empty string (see no-color.org) orTERMisdumb; else byCOLORTERM,TERM,TERM_PROGRAMand known terminals,windowsfor a Windows console, which takes 24-bit color. -
fitText(
TextSegmenter segmenter, String text, int width, {TextOverflow overflow = TextOverflow.ellipsis, String ellipsis = '\u2026'}) → String -
textcut off to fitwidthcolumns assegmentermeasures them (TextSegmenter.width),…in place of what is cut:textitself where it fits; else the clusters that fit and the ellipsis, which takes the columns of an East Asian Ambiguous character (TextSegmenter.ambiguousWidth), as on a line thatRenderParagraphcuts with the sameoverflow; where the ellipsis does not fit either, the clusters that fit, with none, as there; and nothing at all for awidthof 0 or less. No cluster is split, and no blank is left next to the ellipsis, as the paragraph trims them (TextOverflow.clip keeps them). -
graphemeBoundaries(
String s) → Iterable< (int, int)> -
Iterates the extended grapheme clusters of
sas (start, end) pairs. Convenience API for tests and non-hot paths. -
log(
Object? message, {LogLevel level = LogLevel.info, Object? error, StackTrace? stack}) → void -
Records
messagein the LogSink of the app whose handlers, timers or frames call it; elsewhere prints the record. -
mouseTrackingSequence(
MouseTracking from, MouseTracking to) → String -
What switches the terminal's mouse reports from
fromtoto: the mode offromoff, that oftoon (terminals keep one of them on at a time, and some turn any of them off with the reset of another), SGR coordinates on with the first and off with the last; empty when they are the same. -
notifySequence(
String title, String body, {required NotificationProtocol protocol, Multiplexer multiplexer = Multiplexer.none, String id = '1'}) → String -
Returns a desktop notification of
titleandbodyinprotocol, wrapped formultiplexer. -
padCells(
TextSegmenter segmenter, String text, int width, {TextAlign alignment = TextAlign.left}) → String -
textpadded with blanks towidthcolumns assegmentermeasures them (TextSegmenter.width), placed byalignment: TextAlign.left (and TextAlign.justify and TextAlign.start, which a string has no direction for) first, with the blanks after it; TextAlign.right (and TextAlign.end) with the blanks before it; TextAlign.center between them, the odd one after.textitself where it takeswidthcolumns or more: a longer one is not cut (cut it with fitText first). -
passthroughSequence(
String sequence, Multiplexer multiplexer) → String -
Returns
sequencewrapped so thatmultiplexerpasses it on to the terminal outside;sequenceitself for Multiplexer.none. -
plainAsked(
Map< String, String> env) → bool? -
What
TWK_PLAINinenvasks for: true for1ortrue, false for0orfalse, null for anything else or nothing. -
pointerShapeSequence(
PointerShape? shape, [PointerNames names = PointerNames.css]) → String -
Returns OSC 22, which shows the mouse pointer in
shapeover the terminal, by the names it knows (names), or as the terminal shows it by itself for null. -
progressSequence(
ProgressState state, {int? percent}) → String -
Returns OSC 9;4, ConEmu's, which shows the program's progress in
state, withpercentdone (cut to 0…100) where given. -
runsInCi(
Map< String, String> env) → bool -
Whether
envsays the program runs in CI, as the is-in-ci and ci-info packages tell:CI,CONTINUOUS_INTEGRATION,BUILD_NUMBERorRUN_IDset to anything but an empty string,0orfalse, unlessCIis0orfalse. -
stringWidth(
String s, {TextMode mode = TextMode.graphemes, int ambiguousWidth = 1}) → int -
Columns
stakes when drawn (Canvas.text) undermode: a tab is one blank, other controls take none, and in grapheme mode a mark without a base is dropped. -
styledUnderlinesFor(
Map< String, String> env) → bool -
Whether the terminal shows the underline styles of SGR
4:2to4:5(TerminalCaps.styledUnderlines), by its environment: all but Terminal.app, which reads4:3as43, a yellow background. ATERMof a terminal of its own (kitty, ghostty, Alacritty, foot, WezTerm) comes before aTERM_PROGRAMinherited from the Terminal.app it was started in. Over ssh Terminal.app'sTERM_PROGRAMis not passed on: the probe tells it there by its secondary device attributes. -
titleSequence(
String title) → String -
Returns OSC 2, which sets the window's or tab's title to
title.
Exceptions / Errors
- TerminalException
-
Thrown when there is no usable terminal (
Terminal.open, TerminalLink.enterRaw); what a link's input ends with when its far end goes away (the shell serving the terminal), whichTerminal.eventsget.