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