justerm_core/lib.rs
1// The crate-level docs and the compiled usage example both live in README.md,
2// pulled in here so the published crates.io front page and this doctest are one
3// source: the `cargo test` doc pass compiles the README's `rust` block, so the
4// published usage snippet cannot drift from the real API (#483, and the #473
5// rule that a shipped usage snippet must compile against the real types).
6#![doc = include_str!("../README.md")]
7
8mod cell;
9mod color;
10mod cursor;
11mod damage;
12mod event;
13mod grapheme;
14mod grid;
15mod input;
16mod logical;
17mod search;
18mod selection;
19mod serialize;
20mod term;
21
22pub use cell::{Cell, CellFlags};
23pub use color::Color;
24pub use cursor::{Cursor, CursorShape, Pen};
25pub use damage::{LineDamage, ScrollOp, TermDamage};
26pub use event::TermEvent;
27pub use grid::{Grid, Row};
28pub use input::{
29 Key, KeyAction, KeyEvent, KeypadKey, Modifiers, MouseAction, MouseButton, MouseEvent,
30 MouseEvents,
31};
32pub use logical::LogicalLine;
33pub use search::{Match, SearchOptions, is_valid_regex};
34pub use selection::{SelectionSpan, SelectionType, Side};
35pub use serialize::{
36 CELL_RECORD_LEN, DecodeError, Frame, FrameKind, MarkerId, MarkerKind, MarkerLine,
37 MarkerPosition, Overlay, Span, WIRE_VERSION, decode, encode, encode_cell_record, encode_color,
38};
39
40pub use term::{CommandLine, Hyperlink, MAX_COLUMNS, MAX_ROWS, MIN_COLUMNS, Term};
41
42use vte::Parser;
43
44/// The terminal engine: pairs the `vte` parser with our state model.
45///
46/// `Parser` and `Term` are kept as separate fields because `Parser::advance`
47/// borrows both the parser and the performer mutably at once — a single struct
48/// owning both could not satisfy the borrow checker.
49pub struct Engine {
50 parser: Parser,
51 term: Term,
52}
53
54impl Engine {
55 /// A blank engine with a `cols` × `rows` screen and a default scrollback cap.
56 ///
57 /// `cols` is widened to [`MIN_COLUMNS`] — a narrower screen cannot represent a
58 /// width-2 glyph, so the engine clamps rather than accepting a size it would
59 /// have three different answers for (#547).
60 pub fn new(cols: usize, rows: usize) -> Self {
61 Engine {
62 parser: Parser::new(),
63 term: Term::new(cols, rows),
64 }
65 }
66
67 /// Like [`Engine::new`] but with an explicit scrollback line limit. `cols` is
68 /// clamped to [`MIN_COLUMNS`] the same way.
69 pub fn with_scrollback(cols: usize, rows: usize, scrollback_limit: usize) -> Self {
70 Engine {
71 parser: Parser::new(),
72 term: Term::with_scrollback(cols, rows, scrollback_limit),
73 }
74 }
75
76 /// Push a slice of VT bytes. The caller owns the PTY/SSH/socket I/O — the
77 /// engine only consumes the bytes it is handed.
78 pub fn feed(&mut self, bytes: &[u8]) {
79 self.parser.advance(&mut self.term, bytes);
80 }
81
82 /// Resize the screen to `cols` x `rows`. Rows that scroll off the top enter
83 /// scrollback; the whole screen is damaged.
84 ///
85 /// **The primary screen reflows; the alternate screen does not (#567).** On the
86 /// primary, soft-wrapped logical lines are re-split at the new width — scrollback
87 /// included, since it is one buffer with the screen — so a long line keeps its tail
88 /// instead of being truncated. Reflow is *not* gated on DECAWM: the wrap flag records
89 /// that a row continues into the next one, which stays true after a re-split, and
90 /// re-reading a momentary mode at resize time would decide the fate of history written
91 /// under the opposite setting. The alt screen is re-fit only — rows are dropped or added
92 /// to reach the new size and nothing re-wraps, because a full-screen application places
93 /// its own lines and re-wrapping them would change what it drew.
94 ///
95 /// **What a consumer must redo afterwards.** Query-derived state is *invalidated* and
96 /// user-authored state is *re-anchored*: search highlights are dropped (re-run the
97 /// search at the new width — a reflow moves match coordinates and can change the match
98 /// set), while the selection is carried to its new coordinates for you.
99 ///
100 /// `cols` is widened to [`MIN_COLUMNS`] **silently**: a `resize(1, rows)` during
101 /// a pane drag yields a two-column screen with no error. Read the resulting
102 /// width back from [`Engine::grid`] or the frame header rather than assuming the
103 /// value passed here, and size the PTY from that same width (#547).
104 pub fn resize(&mut self, cols: usize, rows: usize) {
105 self.term.resize(cols, rows);
106 }
107
108 /// The current screen grid.
109 pub fn grid(&self) -> &Grid {
110 self.term.grid()
111 }
112
113 /// The current cursor (position, pending-wrap, pen).
114 pub fn cursor(&self) -> &Cursor {
115 self.term.cursor()
116 }
117
118 /// Whether bracketed-paste mode (DEC ?2004) is enabled. A consumer's input
119 /// encoder reads this to decide whether to wrap pasted text in markers.
120 pub fn bracketed_paste(&self) -> bool {
121 self.term.bracketed_paste()
122 }
123
124 /// Encode a key event to the bytes an application expects, honouring the
125 /// engine's cursor-key mode (DECCKM). The inverse of [`Engine::feed`] — the
126 /// consumer hands a decoded key event and writes the bytes to its PTY.
127 /// Returns `None` for a key with no defined encoding.
128 pub fn encode_key(&self, ev: KeyEvent) -> Option<Vec<u8>> {
129 self.term.encode_key(ev)
130 }
131
132 /// Encode a mouse event using the engine's active tracking mode + encoding.
133 /// Returns `None` when mouse reporting is off, or when the event is filtered
134 /// out by the mode (e.g. a bare move while only ?1000 is set).
135 pub fn encode_mouse(&self, ev: MouseEvent) -> Option<Vec<u8>> {
136 self.term.encode_mouse(ev)
137 }
138
139 /// Encode pasted text — wrapped in bracketed-paste markers when ?2004 is on,
140 /// raw otherwise.
141 pub fn encode_paste(&self, text: &str) -> Vec<u8> {
142 self.term.encode_paste(text)
143 }
144
145 /// Encode a focus change (`CSI I` on focus-in, `CSI O` on focus-out), or
146 /// `None` when focus reporting (?1004) is off.
147 pub fn encode_focus(&self, focused: bool) -> Option<Vec<u8>> {
148 self.term.encode_focus(focused)
149 }
150
151 /// Take the consumer events accumulated since the last drain (title / bell /
152 /// cwd — see [`TermEvent`]), emptying the queue. The pull counterpart to a
153 /// callback: poll this alongside [`Engine::frame`].
154 pub fn drain_events(&mut self) -> Vec<TermEvent> {
155 self.term.drain_events()
156 }
157
158 /// Take the reply bytes the engine produced for app queries (DA / DSR /
159 /// DECRQM) since the last drain — the consumer writes them straight back to
160 /// the PTY. The inbound-query counterpart to [`Engine::drain_events`].
161 pub fn drain_replies(&mut self) -> Vec<u8> {
162 self.term.drain_replies()
163 }
164
165 /// The OSC 8 hyperlink **URI** at **screen** `(row, col)` — the live grid, same
166 /// coordinates as [`Engine::grid`]'s `cell(row, col)` — or `None` if that cell
167 /// carries no declared link.
168 ///
169 /// **One call, not two, since #628.** This returned a `NonZeroU32` index that a
170 /// second method resolved against a buffer-wide pool; the pool is gone (it was never
171 /// reclaimed, and nothing interned across opens that a shared `Arc` does not), so
172 /// there is no index left to hand out.
173 ///
174 /// **Owned, not borrowed** — a `&str` into the row's map would be tied to `&Engine`,
175 /// so a hover handler could not keep it across the next [`Engine::feed`]. Measured:
176 /// the borrow reads at 0.75 ns but cannot be held at all, and the caller's workaround
177 /// (copying the string) costs 62.6 ns against this handle's 17.9 ns. See
178 /// [`Hyperlink`].
179 ///
180 /// Do **not** confuse this with a decoded `Span`'s `links`, which is a *frame-local*
181 /// index into that frame's `link_table` and belongs to the wire, not to the engine.
182 /// The old two-call form invited exactly that mix-up and its doc-comment recommended
183 /// it: the two index spaces coincide only when a frame carries a single link.
184 pub fn link_at(&self, row: usize, col: usize) -> Option<Hyperlink> {
185 self.term.screen_link_at(row, col)
186 }
187
188 /// The underline colour (SGR 58, #520) at **screen** `(row, col)` — same
189 /// coordinates as [`Engine::grid`]'s `cell(row, col)`. A theme-agnostic
190 /// [`Color`] reference; [`Color::Default`] means the underline follows the
191 /// glyph's foreground (the common case, and what a cell with no SGR 58 returns).
192 /// Like the hyperlink, the colour rides a per-row side table, not the 12-byte
193 /// [`Cell`] (#520).
194 pub fn underline_color_at(&self, row: usize, col: usize) -> Color {
195 self.term.screen_underline_color_at(row, col)
196 }
197
198 /// The OSC 8 hyperlink **URI** at **viewport** `(row, col)` — the visible window
199 /// including scrollback at the current scroll, same coordinates as
200 /// [`Engine::viewport_line`] — or `None`. Mirror of [`Engine::link_at`], including
201 /// its #628 note about the vanished index.
202 pub fn viewport_link_at(&self, row: usize, col: usize) -> Option<Hyperlink> {
203 self.term.viewport_link_at(row, col)
204 }
205
206 /// Number of lines currently held in scrollback history.
207 pub fn scrollback_len(&self) -> usize {
208 self.term.scrollback_len()
209 }
210
211 /// Whether the app has an open **synchronized-output** block (DEC `?2026`):
212 /// it has asked that the next frame of output be painted atomically. The
213 /// engine only *reports* this — **the consumer owns the paint-hold and the
214 /// spec-mandated timeout** (a buggy app that never closes the block must not
215 /// freeze the screen forever, and the engine has no clock). Poll this after
216 /// `feed`; while it is `true`, defer applying frames, and apply once it
217 /// clears (or your own timeout fires). (#73)
218 pub fn synchronized_output(&self) -> bool {
219 self.term.synchronized_output()
220 }
221
222 /// Whether the app enabled color-scheme-update notifications (DEC `?2031`).
223 /// The engine is theme-agnostic — it never knows the scheme. The consumer
224 /// answers a [`TermEvent::ColorSchemeQuery`] (from `?996`) and, when its
225 /// scheme changes *and* this is `true`, sends an unsolicited notification, in
226 /// both cases by calling [`Engine::report_color_scheme`] (#85).
227 pub fn color_scheme_updates(&self) -> bool {
228 self.term.color_scheme_updates()
229 }
230
231 /// Report the current light/dark color scheme to the app as `CSI ? 997 ; 1 n`
232 /// (dark) / `; 2 n` (light), drained via [`Engine::drain_replies`]. Call this
233 /// to answer a [`TermEvent::ColorSchemeQuery`], or — guarded by
234 /// [`Engine::color_scheme_updates`] — when the scheme changes. The engine only
235 /// formats the bit you pass; it stores no scheme (#85).
236 pub fn report_color_scheme(&mut self, dark: bool) {
237 self.term.report_color_scheme(dark);
238 }
239
240 /// Answer an OSC 11 `QueryBackground` event (#122): the consumer hands back
241 /// the current background spec (it owns the palette) and the engine queues
242 /// the OSC 11 reply for `drain_replies`. Theme-agnostic — the engine never
243 /// knows the colour, only formats the envelope.
244 pub fn report_background(&mut self, spec: &str) {
245 self.term.report_background(spec);
246 }
247
248 /// Answer an OSC 10 `QueryForeground` event (#122): queue the OSC 10 reply
249 /// from the consumer-supplied spec. Theme-agnostic envelope-only.
250 pub fn report_foreground(&mut self, spec: &str) {
251 self.term.report_foreground(spec);
252 }
253
254 /// Answer an OSC 4 `QueryPaletteColor` event (#122): queue the OSC 4 reply for
255 /// `index` from the consumer-supplied spec. Theme-agnostic envelope-only.
256 pub fn report_palette_color(&mut self, index: u8, spec: &str) {
257 self.term.report_palette_color(index, spec);
258 }
259
260 /// Whether the app enabled **win32-input-mode** (DEC `?9001`): it asked for
261 /// keys as raw Windows key-records. The engine only tracks the flag — encoding
262 /// the records (`CSI Vk;Sc;Uc;Kd;Cs;Rc _`) is a non-goal (raw passthrough, no
263 /// semantic conversion), so [`Engine::encode_key`] is unchanged. A ConPTY
264 /// consumer reads this to decide whether to emit the records itself (#86).
265 pub fn win32_input_mode(&self) -> bool {
266 self.term.win32_input_mode()
267 }
268
269 /// What changed since the last [`Engine::reset_damage`] — line ranges each
270 /// with a changed column span (see ADR-0003).
271 pub fn damage(&self) -> TermDamage {
272 self.term.damage()
273 }
274
275 /// Build a serializable [`Frame`] of the current diff — the damaged spans
276 /// (or every row, when `Full`), the recorded scroll op, and a frame-local
277 /// grapheme side-table. Pass it to [`encode`] for the wire (see #6). Reading
278 /// a frame does not clear damage; call [`Engine::reset_damage`] on ack.
279 pub fn frame(&self) -> Frame {
280 self.term.frame()
281 }
282
283 /// Clear accumulated damage after a frame is applied (the consumer's ack).
284 pub fn reset_damage(&mut self) {
285 self.term.reset_damage();
286 }
287
288 /// Force the next [`Engine::frame`] to be a `Full` frame (every row), even if
289 /// little changed. The use case is **reattach / late subscribe**: a renderer
290 /// that connects after output has already been parsed needs the whole current
291 /// viewport once, then incremental diffs. Marks the screen fully damaged; the
292 /// next `frame()` reports `FrameKind::Full`.
293 pub fn mark_fully_damaged(&mut self) {
294 self.term.mark_fully_damaged();
295 }
296
297 /// The first-class scroll recorded since the last [`Engine::reset_damage`],
298 /// if any — lets the renderer shift rows instead of redrawing them.
299 pub fn scroll_delta(&self) -> Option<ScrollOp> {
300 self.term.scroll_delta()
301 }
302
303 /// The cells of visible row `i` (0..rows) at the current scroll position.
304 pub fn viewport_line(&self, i: usize) -> &[Cell] {
305 self.term.viewport_line(i)
306 }
307
308 /// Scroll the viewport up by `n` lines into scrollback history.
309 pub fn scroll_up(&mut self, n: usize) {
310 self.term.scroll_up(n);
311 }
312
313 /// Scroll the viewport down by `n` lines toward the live screen.
314 pub fn scroll_down(&mut self, n: usize) {
315 self.term.scroll_down(n);
316 }
317
318 /// Jump the viewport back to the live screen (follow the bottom).
319 pub fn scroll_to_bottom(&mut self) {
320 self.term.scroll_to_bottom();
321 }
322
323 /// Begin a selection of `ty` at viewport cell `(row, col)`, on `side` of the
324 /// cell. Coordinates are viewport-relative (what a mouse event carries).
325 pub fn selection_begin(&mut self, row: usize, col: usize, side: Side, ty: SelectionType) {
326 self.term.selection_begin(row, col, side, ty);
327 }
328
329 /// Extend the live selection to viewport cell `(row, col)`, on `side`.
330 pub fn selection_extend(&mut self, row: usize, col: usize, side: Side) {
331 self.term.selection_extend(row, col, side);
332 }
333
334 /// Clear the selection.
335 pub fn selection_clear(&mut self) {
336 self.term.selection_clear();
337 }
338
339 /// The selection projected onto the viewport: one inclusive-column span per
340 /// visible row, for the renderer to highlight. Empty when nothing is
341 /// selected or the selection is fully scrolled off-screen.
342 pub fn selection_range(&self) -> Vec<SelectionSpan> {
343 self.term.selection_range()
344 }
345
346 /// The selected text for copy (respects scrollback), or `None` if no
347 /// selection.
348 pub fn selection_text(&self) -> Option<String> {
349 self.term.selection_text()
350 }
351
352 /// Literal search over the grid + scrollback, returning every match in
353 /// absolute buffer coordinates (top-to-bottom). Smart-case: a query with no
354 /// uppercase matches case-insensitively. The consumer drives next/prev by
355 /// walking the returned `Vec` and calling [`Engine::scroll_to_match`].
356 pub fn search(&self, query: &str) -> Vec<Match> {
357 self.term.search(query)
358 }
359
360 /// Search with explicit [`SearchOptions`] — regex, whole-word, and a case-sensitivity override
361 /// beyond the literal + smart-case [`search`](Self::search) (#314).
362 pub fn search_with(&self, query: &str, opts: SearchOptions) -> Vec<Match> {
363 self.term.search_with(query, opts)
364 }
365
366 /// The viewport's logical lines (#113/ADR-0017): each soft-wrap-joined line's
367 /// text plus a per-char map to its viewport `(row, col)`. The buffer-wide
368 /// mechanism for consumer-side URL detection — the consumer runs its own
369 /// regex / `new URL()` over the text and maps matches back through `cells`.
370 /// Also serves the a11y mirror (#119).
371 pub fn viewport_logical_lines(&self) -> Vec<LogicalLine> {
372 self.term.viewport_logical_lines()
373 }
374
375 /// The whole buffer (scrollback + screen) as one text document for a
376 /// screen-reader accessible view (#150) — soft-wrap-joined, wide-spacers
377 /// skipped, trailing blanks trimmed at the logical end, `\n` between logical
378 /// lines. A query seam the consumer summons (frame mode: over IPC, like
379 /// [`selection_text`](Self::selection_text)); no wire-format change. On the
380 /// alt screen only the alt buffer is shown.
381 pub fn accessible_text(&self) -> String {
382 self.term.accessible_text()
383 }
384
385 /// Scroll the viewport so `m` is visible (next/prev navigation: the consumer
386 /// picks the match, the engine scrolls to it).
387 pub fn scroll_to_match(&mut self, m: &Match) {
388 self.term.search_scroll_to(m);
389 }
390
391 /// The match projected onto the viewport as inclusive-column spans per
392 /// visible row, for the renderer to highlight.
393 pub fn match_spans(&self, m: &Match) -> Vec<SelectionSpan> {
394 self.term.match_spans(m)
395 }
396
397 /// Set the search highlights the frame should carry (#108). The
398 /// consumer owns match navigation, so it hands the set to highlight back
399 /// here; [`Engine::frame`] then projects them onto the viewport overlay
400 /// alongside the selection. An empty vec clears the highlights.
401 pub fn set_search_highlights(&mut self, matches: Vec<Match>) {
402 self.term.set_search_highlights(matches);
403 }
404
405 /// Designate which member of the held highlight set is the *active* match
406 /// (#428) — the one next/prev navigation currently points at (that choice is
407 /// the consumer's policy). [`Engine::frame`] projects it into the overlay's
408 /// `active_match` group; it also stays in `matches`, and the renderer's
409 /// highlight ranking resolves the overlap (#424). `None` or an out-of-range
410 /// index projects nothing. Passing a new set to
411 /// [`set_search_highlights`](Self::set_search_highlights) resets the
412 /// designation, so re-designate after every hand-over.
413 pub fn set_active_search_highlight(&mut self, index: Option<usize>) {
414 self.term.set_active_search_highlight(index);
415 }
416
417 /// Designate the *active* match by its absolute span (#436), independent of
418 /// the held highlight set — the past-cap path. A backend that caps its
419 /// hand-over (the documented 1000, xterm's `highlightLimit`) can still give
420 /// the current match its active emphasis: xterm builds its active
421 /// decoration from the found result *outside* the capped list, and this is
422 /// that model. The span projects through the same wrap-aware viewport math
423 /// as any match; past the cap it paints the ACTIVE colour only (no plain
424 /// highlight underneath — honest about the cap). `None` clears. Same
425 /// lifecycle as the index form: reset on every
426 /// [`set_search_highlights`](Self::set_search_highlights) hand-over and on
427 /// any coordinate-shifting invalidation (eviction, region scroll, reflow,
428 /// alt-screen swaps), so re-designate after each hand-over.
429 pub fn set_active_search_match(&mut self, m: Option<Match>) {
430 self.term.set_active_search_match(m);
431 }
432
433 /// Register a decoration marker at viewport `row`, returning its stable id
434 /// (#118). The marker anchors the content currently on that row and tracks
435 /// it through scroll/eviction/reflow; [`Engine::frame`] reports its viewport
436 /// position while visible. Use the id to remove it or to match the
437 /// `TermEvent::MarkerDisposed` fired when its line leaves the buffer.
438 pub fn add_marker(&mut self, row: usize) -> MarkerId {
439 self.term.add_marker(row)
440 }
441
442 /// Remove a marker by id (#118), firing `TermEvent::MarkerDisposed`. A no-op
443 /// for an unknown or already-disposed id.
444 pub fn remove_marker(&mut self, id: MarkerId) {
445 self.term.remove_marker(id);
446 }
447
448 /// The OSC 133 shell-integration command marks in buffer order — `(id,
449 /// absolute line, kind)` (#158). Excludes plain `add_marker` decorations.
450 /// The consumer pairs prompt/command/finished marks to drive prompt-to-prompt
451 /// navigation and command/exit announcements (#160); the engine only parses
452 /// the `133;A/B/C/D` sequences and anchors the marks.
453 pub fn command_marks(&self) -> Vec<(MarkerId, usize, MarkerKind)> {
454 self.term.command_marks()
455 }
456
457 /// The executed shell commands recovered from OSC-133 marks, in buffer order
458 /// (#166) — the query behind screen-reader command navigation. Each
459 /// [`CommandLine`] carries the typed command text (prompt/output excluded via
460 /// the captured columns), its jump line (CommandStart), and the exit code.
461 /// This is a full-buffer query, wired to the frame-mode consumer over IPC like
462 /// [`Engine::accessible_text`]; the web side has no scrollback cells to derive
463 /// it (ADR-0017 — buffer-wide text is core's).
464 pub fn command_lines(&self) -> Vec<CommandLine> {
465 self.term.command_lines()
466 }
467}