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 base64;
9mod cell;
10mod color;
11mod cursor;
12mod damage;
13mod event;
14mod grapheme;
15mod grid;
16mod input;
17mod logical;
18mod search;
19mod selection;
20mod serialize;
21mod term;
22
23pub use cell::{Cell, CellFlags, UnderlineStyle};
24pub use color::Color;
25pub use cursor::{Cursor, CursorShape, Pen};
26pub use damage::{LineDamage, ScrollOp, TermDamage};
27pub use event::{ClipboardTarget, TermEvent, Terminator};
28pub use grid::{Grid, Row};
29pub use input::{
30 Key, KeyAction, KeyEvent, KeypadKey, Modifiers, MouseAction, MouseButton, MouseEvent,
31 MouseEvents,
32};
33pub use logical::LogicalLine;
34pub use search::{Match, SearchOptions, is_valid_regex};
35pub use selection::{SelectionSpan, SelectionType, Side};
36pub use serialize::{
37 CELL_RECORD_LEN, DecodeError, Frame, FrameKind, MarkerId, MarkerKind, MarkerPosition, Overlay,
38 Span, WIRE_VERSION, decode, encode, encode_cell_record, encode_color,
39};
40
41pub use term::{
42 CommandLine, DEFAULT_WORD_SEPARATORS, Hyperlink, MAX_COLUMNS, MAX_COMMAND_TEXT, MAX_MARKERS,
43 MAX_ROWS, MIN_COLUMNS, MarkerEntry, MarkerIndex, Term, TrackedId,
44};
45
46use vte::Parser;
47
48/// The terminal engine: pairs the `vte` parser with our state model.
49///
50/// `Parser` and `Term` are kept as separate fields because `Parser::advance`
51/// borrows both the parser and the performer mutably at once — a single struct
52/// owning both could not satisfy the borrow checker.
53pub struct Engine {
54 parser: Parser,
55 term: Term,
56}
57
58impl Engine {
59 /// A blank engine with a `cols` × `rows` screen and a default scrollback cap.
60 ///
61 /// `cols` is widened to [`MIN_COLUMNS`] — a narrower screen cannot represent a
62 /// width-2 glyph, so the engine clamps rather than accepting a size it would
63 /// have three different answers for (#547).
64 pub fn new(cols: usize, rows: usize) -> Self {
65 Engine {
66 parser: Parser::new(),
67 term: Term::new(cols, rows),
68 }
69 }
70
71 /// Like [`Engine::new`] but with an explicit scrollback line limit. `cols` is
72 /// clamped to [`MIN_COLUMNS`] the same way.
73 pub fn with_scrollback(cols: usize, rows: usize, scrollback_limit: usize) -> Self {
74 Engine {
75 parser: Parser::new(),
76 term: Term::with_scrollback(cols, rows, scrollback_limit),
77 }
78 }
79
80 /// Push a slice of VT bytes. The caller owns the PTY/SSH/socket I/O — the
81 /// engine only consumes the bytes it is handed.
82 ///
83 /// **The stream is UTF-8, and a lone `0x80..=0x9F` byte is ill-formed input
84 /// rather than a C1 control (#847).** So the 8-bit forms of the C1 controls are
85 /// not interpreted: `0x9B` does not open a CSI, `0x9D` an OSC, `0x90` a DCS, and
86 /// `0x9C` does not terminate a string — nor does `C2 9C`, the well-formed UTF-8
87 /// encoding of U+009C. Send the 7-bit forms, which every one of them has:
88 /// `ESC [`, `ESC ]`, `ESC P`, `ESC \`.
89 ///
90 /// **This is a contract, not a gap**, and the reason is that an OSC payload
91 /// legitimately carries 8-bit text. `0x9C` is the last byte of `한` (`ED 95 9C`)
92 /// — all six occurrences of it in this repository's recorded captures are
93 /// exactly that — so honouring it as `ST` in a byte-wise parser would cut a
94 /// title mid-character. xterm arrives at the same place from the other side:
95 /// under UTF-8 it maps an ill-formed byte to U+FFFD and *ignores* a properly
96 /// encoded C1, with both escape hatches (`EXP_C2_CONTROLS`, `allowC1Printable`)
97 /// off by default. Measurements and reference sites are in
98 /// `docs/agents/reference-facts.md`.
99 ///
100 /// Two visible consequences, stated so they are not re-discovered as bugs: an
101 /// unrecognised 8-bit introducer leaves its payload to print as ordinary text,
102 /// and an OSC "closed" with `0x9C` stays open, accumulating everything after it
103 /// until a `BEL`, `ESC`, `CAN` or `SUB` arrives.
104 pub fn feed(&mut self, bytes: &[u8]) {
105 self.parser.advance(&mut self.term, bytes);
106 }
107
108 /// Resize the screen to `cols` x `rows`. Rows that scroll off the top enter
109 /// scrollback; the whole screen is damaged.
110 ///
111 /// **The primary screen reflows; the alternate screen does not (#567).** On the
112 /// primary, soft-wrapped logical lines are re-split at the new width — scrollback
113 /// included, since it is one buffer with the screen — so a long line keeps its tail
114 /// instead of being truncated. Reflow is *not* gated on DECAWM: the wrap flag records
115 /// that a row continues into the next one, which stays true after a re-split, and
116 /// re-reading a momentary mode at resize time would decide the fate of history written
117 /// under the opposite setting. The alt screen is re-fit only — rows are dropped or added
118 /// to reach the new size and nothing re-wraps, because a full-screen application places
119 /// its own lines and re-wrapping them would change what it drew.
120 ///
121 /// **What a consumer must redo afterwards.** Query-derived state is *invalidated* and
122 /// user-authored state is *re-anchored*: search highlights are dropped (re-run the
123 /// search at the new width — a reflow moves match coordinates and can change the match
124 /// set), while the selection is carried to its new coordinates for you.
125 ///
126 /// **Two pieces of application-written state, answered differently.** The tab-stop table is
127 /// *extended*, never rebuilt: a resize that changes only the row count — or one that changes
128 /// nothing, since this call has no early return — leaves it exactly as the application set it,
129 /// and a stop pushed outside a narrowed grid returns when the grid widens again (#849). The
130 /// DECSTBM scroll region is **reset** to the full screen — but only when the geometry actually
131 /// changed, since it is a range over the current screen and a resize to the size you already
132 /// have redefines nothing. An application that set one re-sends it after a real resize; nothing
133 /// tells it the region is gone, so a call that discarded one needlessly could never be repaired.
134 ///
135 /// `cols` is widened to [`MIN_COLUMNS`] **silently**: a `resize(1, rows)` during
136 /// a pane drag yields a two-column screen with no error. Read the resulting
137 /// width back from [`Engine::grid`] or the frame header rather than assuming the
138 /// value passed here, and size the PTY from that same width (#547).
139 pub fn resize(&mut self, cols: usize, rows: usize) {
140 self.term.resize(cols, rows);
141 }
142
143 /// The current screen grid.
144 pub fn grid(&self) -> &Grid {
145 self.term.grid()
146 }
147
148 /// The current cursor (position, pending-wrap, pen).
149 pub fn cursor(&self) -> &Cursor {
150 self.term.cursor()
151 }
152
153 /// Whether bracketed-paste mode (DEC ?2004) is enabled. A consumer's input
154 /// encoder reads this to decide whether to wrap pasted text in markers.
155 pub fn bracketed_paste(&self) -> bool {
156 self.term.bracketed_paste()
157 }
158
159 /// Encode a key event to the bytes an application expects, honouring the
160 /// engine's cursor-key mode (DECCKM). The inverse of [`Engine::feed`] — the
161 /// consumer hands a decoded key event and writes the bytes to its PTY.
162 /// Returns `None` for a key with no defined encoding.
163 pub fn encode_key(&self, ev: KeyEvent) -> Option<Vec<u8>> {
164 self.term.encode_key(ev)
165 }
166
167 /// Encode a mouse event using the engine's active tracking mode + encoding.
168 /// Returns `None` when mouse reporting is off, or when the event is filtered
169 /// out by the mode (e.g. a bare move while only ?1000 is set).
170 pub fn encode_mouse(&self, ev: MouseEvent) -> Option<Vec<u8>> {
171 self.term.encode_mouse(ev)
172 }
173
174 /// Encode pasted text — wrapped in bracketed-paste markers when ?2004 is on,
175 /// raw otherwise.
176 pub fn encode_paste(&self, text: &str) -> Vec<u8> {
177 self.term.encode_paste(text)
178 }
179
180 /// Encode a focus change (`CSI I` on focus-in, `CSI O` on focus-out), or
181 /// `None` when focus reporting (?1004) is off.
182 pub fn encode_focus(&self, focused: bool) -> Option<Vec<u8>> {
183 self.term.encode_focus(focused)
184 }
185
186 /// Take the consumer events accumulated since the last drain (title / bell /
187 /// cwd — see [`TermEvent`]), emptying the queue. The pull counterpart to a
188 /// callback: poll this alongside [`Engine::frame`].
189 pub fn drain_events(&mut self) -> Vec<TermEvent> {
190 self.term.drain_events()
191 }
192
193 /// Take the reply bytes the engine produced for app queries (DA / DSR /
194 /// DECRQM) since the last drain — the consumer writes them straight back to
195 /// the PTY. The inbound-query counterpart to [`Engine::drain_events`].
196 pub fn drain_replies(&mut self) -> Vec<u8> {
197 self.term.drain_replies()
198 }
199
200 /// The OSC 8 hyperlink **URI** at **screen** `(row, col)` — the live grid, same
201 /// coordinates as [`Engine::grid`]'s `cell(row, col)` — or `None` if that cell
202 /// carries no declared link.
203 ///
204 /// **One call, not two, since #628.** This returned a `NonZeroU32` index that a
205 /// second method resolved against a buffer-wide pool; the pool is gone (it was never
206 /// reclaimed, and nothing interned across opens that a shared `Arc` does not), so
207 /// there is no index left to hand out.
208 ///
209 /// **Owned, not borrowed** — a `&str` into the row's map would be tied to `&Engine`,
210 /// so a hover handler could not keep it across the next [`Engine::feed`]. Measured:
211 /// the borrow reads at 0.75 ns but cannot be held at all, and the caller's workaround
212 /// (copying the string) costs 62.6 ns against this handle's 17.9 ns. See
213 /// [`Hyperlink`].
214 ///
215 /// Do **not** confuse this with a decoded `Span`'s `links`, which is a *frame-local*
216 /// index into that frame's `link_table` and belongs to the wire, not to the engine.
217 /// The old two-call form invited exactly that mix-up and its doc-comment recommended
218 /// it: the two index spaces coincide only when a frame carries a single link.
219 pub fn link_at(&self, row: usize, col: usize) -> Option<Hyperlink> {
220 self.term.screen_link_at(row, col)
221 }
222
223 /// The underline colour (SGR 58, #520) at **screen** `(row, col)` — same
224 /// coordinates as [`Engine::grid`]'s `cell(row, col)`. A theme-agnostic
225 /// [`Color`] reference; [`Color::Default`] means the underline follows the
226 /// glyph's foreground (the common case, and what a cell with no SGR 58 returns).
227 /// Like the hyperlink, the colour rides a per-row side table, not the 12-byte
228 /// [`Cell`] (#520).
229 pub fn underline_color_at(&self, row: usize, col: usize) -> Color {
230 self.term.screen_underline_color_at(row, col)
231 }
232
233 /// The OSC 8 hyperlink **URI** at **viewport** `(row, col)` — the visible window
234 /// including scrollback at the current scroll, same coordinates as
235 /// [`Engine::viewport_line`] — or `None`. Mirror of [`Engine::link_at`], including
236 /// its #628 note about the vanished index.
237 pub fn viewport_link_at(&self, row: usize, col: usize) -> Option<Hyperlink> {
238 self.term.viewport_link_at(row, col)
239 }
240
241 /// Number of lines currently held in scrollback history.
242 pub fn scrollback_len(&self) -> usize {
243 self.term.scrollback_len()
244 }
245
246 /// Whether the app has an open **synchronized-output** block (DEC `?2026`):
247 /// it has asked that the next frame of output be painted atomically. The
248 /// engine only *reports* this — **the consumer owns the paint-hold and the
249 /// spec-mandated timeout** (a buggy app that never closes the block must not
250 /// freeze the screen forever, and the engine has no clock). Poll this after
251 /// `feed`; while it is `true`, defer applying frames, and apply once it
252 /// clears (or your own timeout fires). (#73)
253 pub fn synchronized_output(&self) -> bool {
254 self.term.synchronized_output()
255 }
256
257 /// Whether the app enabled color-scheme-update notifications (DEC `?2031`).
258 /// The engine is theme-agnostic — it never knows the scheme. The consumer
259 /// answers a [`TermEvent::ColorSchemeQuery`] (from `?996`) and, when its
260 /// scheme changes *and* this is `true`, sends an unsolicited notification, in
261 /// both cases by calling [`Engine::report_color_scheme`] (#85).
262 pub fn color_scheme_updates(&self) -> bool {
263 self.term.color_scheme_updates()
264 }
265
266 /// Report the current light/dark color scheme to the app as `CSI ? 997 ; 1 n`
267 /// (dark) / `; 2 n` (light), drained via [`Engine::drain_replies`]. Call this
268 /// to answer a [`TermEvent::ColorSchemeQuery`], or — guarded by
269 /// [`Engine::color_scheme_updates`] — when the scheme changes. The engine only
270 /// formats the bit you pass; it stores no scheme (#85).
271 pub fn report_color_scheme(&mut self, dark: bool) {
272 self.term.report_color_scheme(dark);
273 }
274
275 /// Answer an OSC 11 `QueryBackground` event (#122): the consumer hands back
276 /// the current background spec (it owns the palette) and the engine queues
277 /// the OSC 11 reply for `drain_replies`. Theme-agnostic — the engine never
278 /// knows the colour, only formats the envelope.
279 pub fn report_background(&mut self, spec: &str, terminator: Terminator) {
280 self.term.report_background(spec, terminator);
281 }
282
283 /// Answer an OSC 10 `QueryForeground` event (#122): queue the OSC 10 reply
284 /// from the consumer-supplied spec. Theme-agnostic envelope-only.
285 pub fn report_foreground(&mut self, spec: &str, terminator: Terminator) {
286 self.term.report_foreground(spec, terminator);
287 }
288
289 /// Answer an OSC 12 `QueryCursorColor` event (#832): queue the OSC 12 reply
290 /// from the consumer-supplied spec. Theme-agnostic envelope-only, like its
291 /// foreground and background siblings.
292 pub fn report_cursor_color(&mut self, spec: &str, terminator: Terminator) {
293 self.term.report_cursor_color(spec, terminator);
294 }
295
296 /// Answer an OSC 4 `QueryPaletteColor` event (#122): queue the OSC 4 reply for
297 /// `index` from the consumer-supplied spec. Theme-agnostic envelope-only.
298 pub fn report_palette_color(&mut self, index: u8, spec: &str, terminator: Terminator) {
299 self.term.report_palette_color(index, spec, terminator);
300 }
301
302 /// Answer an OSC 52 [`TermEvent::QueryClipboard`] event (#828): base64-encode
303 /// the consumer's clipboard text into the OSC 52 reply envelope for
304 /// [`Engine::drain_replies`].
305 ///
306 /// The engine holds no clipboard — the text comes from the consumer, which
307 /// owns it along with every policy about it. **Not calling this is how a read
308 /// is refused**, independently of whether stores are honoured, and nothing is
309 /// queued until you do.
310 pub fn report_clipboard(
311 &mut self,
312 target: ClipboardTarget,
313 text: &str,
314 terminator: Terminator,
315 ) {
316 self.term.report_clipboard(target, text, terminator);
317 }
318
319 /// Whether the app enabled **win32-input-mode** (DEC `?9001`): it asked for
320 /// keys as raw Windows key-records. The engine only tracks the flag — encoding
321 /// the records (`CSI Vk;Sc;Uc;Kd;Cs;Rc _`) is a non-goal (raw passthrough, no
322 /// semantic conversion), so [`Engine::encode_key`] is unchanged. A ConPTY
323 /// consumer reads this to decide whether to emit the records itself (#86).
324 pub fn win32_input_mode(&self) -> bool {
325 self.term.win32_input_mode()
326 }
327
328 /// What changed since the last [`Engine::reset_damage`] — line ranges each
329 /// with a changed column span (see ADR-0003).
330 pub fn damage(&self) -> TermDamage {
331 self.term.damage()
332 }
333
334 /// Build a serializable [`Frame`] of the current diff — the damaged spans
335 /// (or every row, when `Full`), the recorded scroll op, and a frame-local
336 /// grapheme side-table. Pass it to [`encode`] for the wire (see #6). Reading
337 /// a frame does not clear damage; call [`Engine::reset_damage`] on ack.
338 pub fn frame(&self) -> Frame {
339 self.term.frame()
340 }
341
342 /// Clear accumulated damage after a frame is applied (the consumer's ack).
343 pub fn reset_damage(&mut self) {
344 self.term.reset_damage();
345 }
346
347 /// Force the next [`Engine::frame`] to be a `Full` frame (every row), even if
348 /// little changed. The use case is **reattach / late subscribe**: a renderer
349 /// that connects after output has already been parsed needs the whole current
350 /// viewport once, then incremental diffs. Marks the screen fully damaged; the
351 /// next `frame()` reports `FrameKind::Full`.
352 pub fn mark_fully_damaged(&mut self) {
353 self.term.mark_fully_damaged();
354 }
355
356 /// The first-class scroll recorded since the last [`Engine::reset_damage`],
357 /// if any — lets the renderer shift rows instead of redrawing them.
358 ///
359 /// **`count` is capped at the scroll region's own height (#661).** Repeated
360 /// scrolls of one region accumulate into a single op between acks, and a flood
361 /// accumulates far past the region: 32 KB of newlines in one [`Engine::feed`] is
362 /// enough. Shifting a region by more than its height already moves every source
363 /// row outside it, so the surplus names nothing a consumer can act on — while it
364 /// did overflow the `i16` this value rides on the wire and arrive as a scroll in
365 /// the *opposite* direction. Suppressed entirely while the viewport is scrolled
366 /// up, since a content scroll must not shift a frozen view.
367 pub fn scroll_delta(&self) -> Option<ScrollOp> {
368 self.term.scroll_delta()
369 }
370
371 /// The cells of visible row `i` (0..rows) at the current scroll position.
372 pub fn viewport_line(&self, i: usize) -> &[Cell] {
373 self.term.viewport_line(i)
374 }
375
376 /// Scroll the viewport up by `n` lines into scrollback history.
377 pub fn scroll_up(&mut self, n: usize) {
378 self.term.scroll_up(n);
379 }
380
381 /// Scroll the viewport down by `n` lines toward the live screen.
382 pub fn scroll_down(&mut self, n: usize) {
383 self.term.scroll_down(n);
384 }
385
386 /// Jump the viewport back to the live screen (follow the bottom).
387 pub fn scroll_to_bottom(&mut self) {
388 self.term.scroll_to_bottom();
389 }
390
391 /// Begin a selection of `ty` at viewport cell `(row, col)`, on `side` of the
392 /// cell. Coordinates are viewport-relative (what a mouse event carries).
393 pub fn selection_begin(&mut self, row: usize, col: usize, side: Side, ty: SelectionType) {
394 self.term.selection_begin(row, col, side, ty);
395 }
396
397 /// Extend the live selection to viewport cell `(row, col)`, on `side`.
398 pub fn selection_extend(&mut self, row: usize, col: usize, side: Side) {
399 self.term.selection_extend(row, col, side);
400 }
401
402 /// Replace the characters that end a word for [`SelectionType::Word`] — consumer
403 /// policy injected into a core mechanism (ADR-0017). Defaults to
404 /// [`DEFAULT_WORD_SEPARATORS`]. `' '` is forced in; see [`Term::set_word_separators`]
405 /// for why that floor is load-bearing rather than defensive.
406 pub fn set_word_separators(&mut self, separators: &str) {
407 self.term.set_word_separators(separators);
408 }
409
410 /// The word-boundary set currently in force (including the forced `' '`).
411 pub fn word_separators(&self) -> &str {
412 self.term.word_separators()
413 }
414
415 /// Clear the selection.
416 pub fn selection_clear(&mut self) {
417 self.term.selection_clear();
418 }
419
420 /// The selection projected onto the viewport: one inclusive-column span per
421 /// visible row, for the renderer to highlight. Empty when nothing is
422 /// selected or the selection is fully scrolled off-screen.
423 ///
424 /// **A span never ends inside a wide glyph** (#454). An endpoint landing on
425 /// half of a width-2 pair takes the whole pair, so a highlight cannot split
426 /// a CJK glyph down the middle — which also means a span may be one column
427 /// wider than the columns the caller's gesture named. On a `Block`
428 /// selection that widening is per row, so the rectangle's rows can differ
429 /// in width. [`selection_text`](Self::selection_text) widens identically;
430 /// the two never disagree.
431 pub fn selection_range(&self) -> Vec<SelectionSpan> {
432 self.term.selection_range()
433 }
434
435 /// The selected text for copy (respects scrollback), or `None` if no
436 /// selection.
437 ///
438 /// Widened onto whole wide-glyph pairs exactly as
439 /// [`selection_range`](Self::selection_range) is (#454) — a spacer extracts
440 /// as nothing, so a range ending inside a pair would copy text the
441 /// highlight does not show.
442 pub fn selection_text(&self) -> Option<String> {
443 self.term.selection_text()
444 }
445
446 /// Literal search over the grid + scrollback, returning every match in
447 /// absolute buffer coordinates (top-to-bottom). Smart-case: a query with no
448 /// uppercase matches case-insensitively. The consumer drives next/prev by
449 /// walking the returned `Vec` and calling [`Engine::scroll_to_match`].
450 pub fn search(&self, query: &str) -> Vec<Match> {
451 self.term.search(query)
452 }
453
454 /// Search with explicit [`SearchOptions`] — regex, whole-word, and a case-sensitivity override
455 /// beyond the literal + smart-case [`search`](Self::search) (#314).
456 pub fn search_with(&self, query: &str, opts: SearchOptions) -> Vec<Match> {
457 self.term.search_with(query, opts)
458 }
459
460 /// The viewport's logical lines (#113/ADR-0017): each soft-wrap-joined line's
461 /// text plus a per-char map to its viewport `(row, col)`. The buffer-wide
462 /// mechanism for consumer-side URL detection — the consumer runs its own
463 /// regex / `new URL()` over the text and maps matches back through `cells`.
464 /// Also serves the a11y mirror (#119).
465 pub fn viewport_logical_lines(&self) -> Vec<LogicalLine> {
466 self.term.viewport_logical_lines()
467 }
468
469 /// The whole buffer (scrollback + screen) as one text document for a
470 /// screen-reader accessible view (#150) — soft-wrap-joined, wide-spacers
471 /// skipped, trailing blanks trimmed at the logical end, `\n` between logical
472 /// lines. A query seam the consumer summons (frame mode: over IPC, like
473 /// [`selection_text`](Self::selection_text)); no wire-format change. On the
474 /// alt screen only the alt buffer is shown.
475 ///
476 /// **This is the document [`CommandLine::line`] indexes, which makes that last
477 /// sentence a pairing obligation rather than a detail (#743):** ask both in the
478 /// same breath and keep them together, because a document line is meaningless
479 /// against a document sampled at another instant — and while the alt screen is up
480 /// the two queries are about different buffers entirely. See
481 /// [`Engine::command_lines`].
482 pub fn accessible_text(&self) -> String {
483 self.term.accessible_text()
484 }
485
486 /// Scroll the viewport so `m` is visible (next/prev navigation: the consumer
487 /// picks the match, the engine scrolls to it).
488 pub fn scroll_to_match(&mut self, m: &Match) {
489 self.term.search_scroll_to(m);
490 }
491
492 /// The match projected onto the viewport as inclusive-column spans per
493 /// visible row, for the renderer to highlight.
494 ///
495 /// **A span never ends inside a wide glyph** (#454), the same widening
496 /// [`selection_range`](Self::selection_range) applies. It matters more here,
497 /// because a `Match` may be one the *caller* assembled: an out-of-range
498 /// column is bounded onto the row's last cell, which is a trailing spacer
499 /// whenever the row ends in a wide glyph — so without the widening a
500 /// highlight could be that glyph's right half alone.
501 pub fn match_spans(&self, m: &Match) -> Vec<SelectionSpan> {
502 self.term.match_spans(m)
503 }
504
505 /// Set the search highlights the frame should carry (#108). The
506 /// consumer owns match navigation, so it hands the set to highlight back
507 /// here; [`Engine::frame`] then projects them onto the viewport overlay
508 /// alongside the selection. An empty vec clears the highlights.
509 pub fn set_search_highlights(&mut self, matches: Vec<Match>) {
510 self.term.set_search_highlights(matches);
511 }
512
513 /// Designate which member of the held highlight set is the *active* match
514 /// (#428) — the one next/prev navigation currently points at (that choice is
515 /// the consumer's policy). [`Engine::frame`] projects it into the overlay's
516 /// `active_match` group; it also stays in `matches`, and the renderer's
517 /// highlight ranking resolves the overlap (#424). `None` or an out-of-range
518 /// index projects nothing. Passing a new set to
519 /// [`set_search_highlights`](Self::set_search_highlights) resets the
520 /// designation, so re-designate after every hand-over.
521 pub fn set_active_search_highlight(&mut self, index: Option<usize>) {
522 self.term.set_active_search_highlight(index);
523 }
524
525 /// Designate the *active* match by its absolute span (#436), independent of
526 /// the held highlight set — the past-cap path. A backend that caps its
527 /// hand-over (the documented 1000, xterm's `highlightLimit`) can still give
528 /// the current match its active emphasis: xterm builds its active
529 /// decoration from the found result *outside* the capped list, and this is
530 /// that model. The span projects through the same wrap-aware viewport math
531 /// as any match; past the cap it paints the ACTIVE colour only (no plain
532 /// highlight underneath — honest about the cap). `None` clears. Same
533 /// lifecycle as the index form: reset on every
534 /// [`set_search_highlights`](Self::set_search_highlights) hand-over and on
535 /// any coordinate-shifting invalidation (eviction, region scroll, reflow,
536 /// alt-screen swaps), so re-designate after each hand-over.
537 pub fn set_active_search_match(&mut self, m: Option<Match>) {
538 self.term.set_active_search_match(m);
539 }
540
541 /// Register a decoration marker at viewport `row`, returning its stable id
542 /// (#118). The marker anchors the content currently on that row and tracks
543 /// it through scroll/eviction/reflow; [`Engine::frame`] reports its viewport
544 /// position while visible. Use the id to remove it or to match the
545 /// `TermEvent::MarkerDisposed` fired when its line leaves the buffer.
546 ///
547 /// A buffer holds at most [`MAX_MARKERS`] live markers (#721) — the population is
548 /// also grown by the *stream*, through OSC 133 command marks, so it is bounded.
549 /// Past the cap the **oldest** marker is retired and announced through the same
550 /// `MarkerDisposed` event, so a consumer that already handles disposal needs no new
551 /// handling; a consumer that ignores it can leave a decoration bound to a dead id.
552 pub fn add_marker(&mut self, row: usize) -> MarkerId {
553 self.term.add_marker(row)
554 }
555
556 /// Remove a marker by id (#118), firing `TermEvent::MarkerDisposed`. A no-op
557 /// for an unknown or already-disposed id.
558 pub fn remove_marker(&mut self, id: MarkerId) {
559 self.term.remove_marker(id);
560 }
561
562 /// Track absolute buffer `(line, col)`, returning a stable id (#691): the
563 /// engine keeps the position on the content that is there now, through
564 /// scrollback eviction, region scrolls and reflow.
565 ///
566 /// This is what an absolute coordinate held *outside* the engine needs to stay
567 /// meaningful — a search anchor carrying an emphasis across a re-search is the
568 /// case it exists for. The engine renumbers this space (evicting the oldest
569 /// history line shifts every index down by one), and it renumbers it in the
570 /// consumer's absence, so a remembered `Match` silently comes to name
571 /// different text.
572 ///
573 /// Mechanism only: which position is worth remembering, and what to do once it
574 /// is gone, stay with the consumer (ADR-0017). Release it with
575 /// [`Engine::untrack_point`] — the engine cannot know when you are done.
576 ///
577 /// **The line is maintained; the column is carried, not tracked.** In-row edits
578 /// (ICH / DCH) shift cells past a tracked column without moving it, so a point
579 /// on text that was pushed sideways names the wrong cell in that row. No
580 /// reference maintains a column here either — xterm's markers carry none at
581 /// all, and ghostty's pins are untouched by its `insertChars`/`deleteChars` —
582 /// so this is the convergent behaviour rather than an omission.
583 pub fn track_point(&mut self, line: usize, col: usize) -> TrackedId {
584 self.term.track_point(line, col)
585 }
586
587 /// Where the point registered as `id` sits now, in the **active** screen's
588 /// coordinates — or `None` (#691).
589 ///
590 /// `None` covers three cases, and a caller does not need to tell them apart:
591 /// the content has left the buffer, the id is unknown or released, or the point
592 /// belongs to *the other screen*. The last one is not a limitation but the only
593 /// honest answer: the primary grid and the alt grid occupy the **same** absolute
594 /// indices, so a number alone cannot say which screen it means. All three say
595 /// *do not move anything on account of this point*.
596 ///
597 /// An out-of-range coordinate is clamped rather than rejected, at both ends
598 /// (ADR-0026 D2/D3): the line into the buffer's range, the column to the grid
599 /// width. That bound is applied here, at the read; a coordinate that was never
600 /// in range to begin with is also **resolved by a reflow** (it maps to the top
601 /// of the buffer), so "bounded once" holds for the site, not for the value.
602 pub fn tracked_point(&self, id: TrackedId) -> Option<(usize, usize)> {
603 self.term.tracked_point(id)
604 }
605
606 /// Release a tracked point (#691). A no-op for an unknown or already-released
607 /// id.
608 pub fn untrack_point(&mut self, id: TrackedId) {
609 self.term.untrack_point(id);
610 }
611
612 /// The OSC 133 shell-integration command marks in buffer order — `(id,
613 /// absolute line, kind)` (#158). Excludes plain `add_marker` decorations.
614 /// The consumer pairs prompt/command/finished marks to drive prompt-to-prompt
615 /// navigation and command/exit announcements (#160); the engine only parses
616 /// the `133;A/B/C/D` sequences and anchors the marks.
617 ///
618 /// **The answer is instantaneous — it describes the buffer it was asked of, and
619 /// nothing on it dates it (#742). Re-ask; never keep it and never rebase it.**
620 /// The lines move on *both* of the axes [`MarkerIndex`] carries a scalar for:
621 /// scrollback eviction shifts every mark by the same amount, and a top-anchored
622 /// `DECSTBM` region shifts the marks below its margin once per output line — the
623 /// second inside a single [`Engine::feed`], with no resize anywhere.
624 ///
625 /// **Why this is not shaped like its sibling.** [`Engine::marker_index`] carries a
626 /// basis and an epoch because a consumer *must* hold its answer: it feeds an
627 /// overview ruler that has to be current in every frame, and re-pulling per frame
628 /// is the `O(M)`-per-frame payload ADR-0020 R3 exists to forbid. This query is
629 /// consumed when a user acts, so re-asking **is** the natural act — and here a
630 /// re-ask always answers, because this population's frame of reference never
631 /// changes. That is the property the sibling lacks, and the reason it needed the
632 /// epoch rather than a reason this one does: an alt switch is one of the four
633 /// moves that epoch announces.
634 ///
635 /// **The lines are `[scrollback ++ primary]`, always — including while the alt
636 /// screen is up.** They do not name the *active* buffer. The two buffers occupy the
637 /// same absolute indices, so one integer from here and the same integer from
638 /// [`Engine::marker_index`] name different content, and neither tuple nor struct
639 /// says which. [`Engine::tracked_point`] meets that ambiguity and answers `None`
640 /// rather than a number (ADR-0026 D2/D3); it can, because it is asked about *one*
641 /// point of unknown origin. This query enumerates a population whose screen is
642 /// fixed by definition, so it answers — and states the screen here instead.
643 ///
644 /// Consequently an empty answer means every mark was disposed and can mean nothing
645 /// else, where `marker_index`'s silence is ambiguous between that and *"you are on
646 /// the other screen"*.
647 ///
648 /// **A mark also dies when a whole row is blanked where it stands (#750).** Until
649 /// then the only deaths were the buffer *moving* — eviction, a region rotate, a
650 /// reflow — and a `clear` left every mark on the screen alive over blank rows. `ED`
651 /// now retires the marks on each whole row it blanks, through the same
652 /// `TermEvent::MarkerDisposed` a consumer already handles, so this query going empty
653 /// after a `clear` is the ordinary meaning above and not a new one. **`EL` and `ECH`
654 /// deliberately do not**, whatever they blank: a line editor redraws its input line
655 /// with `\r ESC[K` on every keystroke, and the `CommandStart` of the command being
656 /// typed is on that row.
657 pub fn command_marks(&self) -> Vec<(MarkerId, usize, MarkerKind)> {
658 self.term.command_marks()
659 }
660
661 /// The executed shell commands recovered from OSC-133 marks, in buffer order
662 /// (#166) — the query behind screen-reader command navigation. Each
663 /// [`CommandLine`] carries the typed command text (prompt/output excluded via
664 /// the captured columns), its jump line (CommandStart), and the exit code.
665 /// This is a full-buffer query, wired to the frame-mode consumer over IPC like
666 /// [`Engine::accessible_text`]; the web side has no scrollback cells to derive
667 /// it (ADR-0017 — buffer-wide text is core's).
668 ///
669 /// **The text and the exit are frozen when the stream reveals them; only the line
670 /// is derived (#750).** [`CommandLine::command`] is captured at the `133;C` that
671 /// closes the command — the instant it is complete and on screen — and
672 /// [`CommandLine::exit`] is written down when `133;D` is parsed. Neither is
673 /// recoverable afterwards: re-reading the text through the recorded columns names
674 /// whatever *now* occupies those cells, which a plain overwrite, `ICH`, `DCH` and an
675 /// erase all arrange, and an exit code is in no cell at any time. A capture is
676 /// bounded at [`MAX_COMMAND_TEXT`] `char`s, truncated at a `char` boundary, for the
677 /// reason [`MAX_MARKERS`] exists: the stream chooses the distance between `B` and
678 /// `C`. [`CommandLine::line`] stays derived, because it is the half the anchor
679 /// fixups already maintain.
680 ///
681 /// **The answer is instantaneous — it describes the buffer it was asked of, and
682 /// nothing on it dates it (#743). Re-ask; never keep it past the document it
683 /// indexes, and never rebase it.** Same discharge as [`Engine::command_marks`] and
684 /// for the same two reasons (ADR-0029 D3): the clock is a user action, so the ask
685 /// *is* the act; and this population's frame of reference never flips, so a re-ask
686 /// always answers. Absence means the command is gone **or** that its output has not
687 /// started yet — both of which the next ask resolves. What absence never means is
688 /// *"you are on the other screen"*, which is the meaning no re-ask could undo.
689 ///
690 /// **Do not rebase by [`MarkerIndex::evicted_total`].** That dates the *absolute*
691 /// space. [`CommandLine::line`] is a **document** line, and the two spaces move
692 /// apart in both directions: an eviction that pops a soft-wrap continuation row
693 /// moves the absolute lines and not this one, and flipping a row's wrap bit — which
694 /// ordinary output does — moves this one while the absolute lines and both of
695 /// `MarkerIndex`'s scalars stay put. They agree most of the time, which is what
696 /// makes rebasing look correct right up until it silently is not.
697 ///
698 /// **Ask [`Engine::accessible_text`] in the same breath, and only on the primary
699 /// screen.** The lines index that document; while the alt screen is up it returns
700 /// the *alt* document instead, and these lines are indices into the primary one. If
701 /// the alt screen is taller than the held index — a full-screen TUI, which is the
702 /// normal case — the index still **resolves**, onto unrelated content, so a bounds
703 /// check does not save a caller here. The query keeps answering on the alt screen
704 /// deliberately: emptying it would give absence the one meaning a re-ask cannot
705 /// recover from, which is what the discharge above rests on. Pairing the two is the
706 /// caller's, and this is where it is said.
707 pub fn command_lines(&self) -> Vec<CommandLine> {
708 self.term.command_lines()
709 }
710
711 /// Every live marker of the active buffer with its **absolute** buffer line, plus
712 /// the basis that says how long the answer stays usable (#490).
713 ///
714 /// The pull half of the marker surface. It shares [`Engine::command_lines`]'s
715 /// *shape* — the consumer asks once and keeps the answer, rather than being handed
716 /// every live marker inside every frame, which is `O(M)` payload per frame for a
717 /// quantity unrelated to what changed (ADR-0020 R3). It does **not** share its
718 /// coordinate: only the lines *here* are buffer-absolute and rebasable by the
719 /// `evicted_total` delta. [`CommandLine::line`] is a **document** line over
720 /// [`Engine::accessible_text`], where soft-wrapped rows collapse — eviction moves it
721 /// by an amount no scalar on this surface expresses, so it is an answer to keep only
722 /// as long as the buffer it was asked of.
723 ///
724 /// Ask again when [`MarkerIndex::epoch`] differs from the one you hold. Drop an
725 /// entry when its `TermEvent::MarkerDisposed` arrives, and append one when
726 /// `TermEvent::MarkerCreated` does — neither deliberately moves the epoch, so
727 /// neither costs a re-pull. **Append it on the instant the event carries, not on the
728 /// newest frame's**: a `feed` can create a marker and then evict, and those are two
729 /// different origins (#737).
730 ///
731 /// **Adopt a birth only into the generation it names (#741).** The event carries this
732 /// pull's whole triple — line, basis, [`MarkerIndex::epoch`] — because the basis dates
733 /// only a *uniform* move. A reflow or a region rotate moves markers individually, so a
734 /// line dated to the generation before one is not stale by a delta; it is an answer
735 /// about a different buffer, and the re-pull the epoch already forces is what supplies
736 /// the marker instead. Compare generations for **equality**: the counter wraps.
737 ///
738 /// **Draining before you read the frame is then a cost preference, not a correctness
739 /// one.** Reading the frame first leaves `marker_count` one ahead of an index that has
740 /// not been told yet, so a consumer comparing the two spends an `O(M)` re-pull
741 /// reconciling a fact this event delivered at `O(1)`. Placement does not depend on the
742 /// order, on either axis.
743 pub fn marker_index(&self) -> MarkerIndex {
744 self.term.marker_index()
745 }
746}