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, 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 pub fn new(cols: usize, rows: usize) -> Self {
57 Engine {
58 parser: Parser::new(),
59 term: Term::new(cols, rows),
60 }
61 }
62
63 /// Like [`Engine::new`] but with an explicit scrollback line limit.
64 pub fn with_scrollback(cols: usize, rows: usize, scrollback_limit: usize) -> Self {
65 Engine {
66 parser: Parser::new(),
67 term: Term::with_scrollback(cols, rows, scrollback_limit),
68 }
69 }
70
71 /// Push a slice of VT bytes. The caller owns the PTY/SSH/socket I/O — the
72 /// engine only consumes the bytes it is handed.
73 pub fn feed(&mut self, bytes: &[u8]) {
74 self.parser.advance(&mut self.term, bytes);
75 }
76
77 /// Resize the screen to `cols` x `rows`. Rows that scroll off the top enter
78 /// scrollback; the whole screen is damaged. (Soft-wrap reflow lands in #7.)
79 pub fn resize(&mut self, cols: usize, rows: usize) {
80 self.term.resize(cols, rows);
81 }
82
83 /// The current screen grid.
84 pub fn grid(&self) -> &Grid {
85 self.term.grid()
86 }
87
88 /// The current cursor (position, pending-wrap, pen).
89 pub fn cursor(&self) -> &Cursor {
90 self.term.cursor()
91 }
92
93 /// Whether bracketed-paste mode (DEC ?2004) is enabled. A consumer's input
94 /// encoder reads this to decide whether to wrap pasted text in markers.
95 pub fn bracketed_paste(&self) -> bool {
96 self.term.bracketed_paste()
97 }
98
99 /// Encode a key event to the bytes an application expects, honouring the
100 /// engine's cursor-key mode (DECCKM). The inverse of [`Engine::feed`] — the
101 /// consumer hands a decoded key event and writes the bytes to its PTY.
102 /// Returns `None` for a key with no defined encoding.
103 pub fn encode_key(&self, ev: KeyEvent) -> Option<Vec<u8>> {
104 self.term.encode_key(ev)
105 }
106
107 /// Encode a mouse event using the engine's active tracking mode + encoding.
108 /// Returns `None` when mouse reporting is off, or when the event is filtered
109 /// out by the mode (e.g. a bare move while only ?1000 is set).
110 pub fn encode_mouse(&self, ev: MouseEvent) -> Option<Vec<u8>> {
111 self.term.encode_mouse(ev)
112 }
113
114 /// Encode pasted text — wrapped in bracketed-paste markers when ?2004 is on,
115 /// raw otherwise.
116 pub fn encode_paste(&self, text: &str) -> Vec<u8> {
117 self.term.encode_paste(text)
118 }
119
120 /// Encode a focus change (`CSI I` on focus-in, `CSI O` on focus-out), or
121 /// `None` when focus reporting (?1004) is off.
122 pub fn encode_focus(&self, focused: bool) -> Option<Vec<u8>> {
123 self.term.encode_focus(focused)
124 }
125
126 /// Take the consumer events accumulated since the last drain (title / bell /
127 /// cwd — see [`TermEvent`]), emptying the queue. The pull counterpart to a
128 /// callback: poll this alongside [`Engine::frame`].
129 pub fn drain_events(&mut self) -> Vec<TermEvent> {
130 self.term.drain_events()
131 }
132
133 /// Take the reply bytes the engine produced for app queries (DA / DSR /
134 /// DECRQM) since the last drain — the consumer writes them straight back to
135 /// the PTY. The inbound-query counterpart to [`Engine::drain_events`].
136 pub fn drain_replies(&mut self) -> Vec<u8> {
137 self.term.drain_replies()
138 }
139
140 /// The OSC 8 hyperlink index at **screen** `(row, col)` — the live grid, same
141 /// coordinates as [`Engine::grid`]'s `cell(row, col)` — or `None`. Combining
142 /// and links no longer ride on the [`Cell`] (#45/#46); read the
143 /// index here, then resolve it with [`Engine::hyperlink`].
144 pub fn link_at(&self, row: usize, col: usize) -> Option<core::num::NonZeroU32> {
145 self.term.screen_link_at(row, col)
146 }
147
148 /// The underline colour (SGR 58, #520) at **screen** `(row, col)` — same
149 /// coordinates as [`Engine::grid`]'s `cell(row, col)`. A theme-agnostic
150 /// [`Color`] reference; [`Color::Default`] means the underline follows the
151 /// glyph's foreground (the common case, and what a cell with no SGR 58 returns).
152 /// Like the hyperlink, the colour rides a per-row side table, not the 12-byte
153 /// [`Cell`] (#520).
154 pub fn underline_color_at(&self, row: usize, col: usize) -> Color {
155 self.term.screen_underline_color_at(row, col)
156 }
157
158 /// The OSC 8 hyperlink index at **viewport** `(row, col)` — the visible
159 /// window including scrollback at the current scroll, same coordinates as
160 /// [`Engine::viewport_line`] — or `None`.
161 pub fn viewport_link_at(&self, row: usize, col: usize) -> Option<core::num::NonZeroU32> {
162 self.term.viewport_link_at(row, col)
163 }
164
165 /// Resolve a hyperlink index (from [`Engine::link_at`] /
166 /// [`Engine::viewport_link_at`], or a decoded `Span`'s `links`) to its URI,
167 /// to make a cell clickable.
168 pub fn hyperlink(&self, link: core::num::NonZeroU32) -> Option<&str> {
169 self.term.hyperlink(link)
170 }
171
172 /// Number of lines currently held in scrollback history.
173 pub fn scrollback_len(&self) -> usize {
174 self.term.scrollback_len()
175 }
176
177 /// Whether the app has an open **synchronized-output** block (DEC `?2026`):
178 /// it has asked that the next frame of output be painted atomically. The
179 /// engine only *reports* this — **the consumer owns the paint-hold and the
180 /// spec-mandated timeout** (a buggy app that never closes the block must not
181 /// freeze the screen forever, and the engine has no clock). Poll this after
182 /// `feed`; while it is `true`, defer applying frames, and apply once it
183 /// clears (or your own timeout fires). (#73)
184 pub fn synchronized_output(&self) -> bool {
185 self.term.synchronized_output()
186 }
187
188 /// Whether the app enabled color-scheme-update notifications (DEC `?2031`).
189 /// The engine is theme-agnostic — it never knows the scheme. The consumer
190 /// answers a [`TermEvent::ColorSchemeQuery`] (from `?996`) and, when its
191 /// scheme changes *and* this is `true`, sends an unsolicited notification, in
192 /// both cases by calling [`Engine::report_color_scheme`] (#85).
193 pub fn color_scheme_updates(&self) -> bool {
194 self.term.color_scheme_updates()
195 }
196
197 /// Report the current light/dark color scheme to the app as `CSI ? 997 ; 1 n`
198 /// (dark) / `; 2 n` (light), drained via [`Engine::drain_replies`]. Call this
199 /// to answer a [`TermEvent::ColorSchemeQuery`], or — guarded by
200 /// [`Engine::color_scheme_updates`] — when the scheme changes. The engine only
201 /// formats the bit you pass; it stores no scheme (#85).
202 pub fn report_color_scheme(&mut self, dark: bool) {
203 self.term.report_color_scheme(dark);
204 }
205
206 /// Answer an OSC 11 `QueryBackground` event (#122): the consumer hands back
207 /// the current background spec (it owns the palette) and the engine queues
208 /// the OSC 11 reply for `drain_replies`. Theme-agnostic — the engine never
209 /// knows the colour, only formats the envelope.
210 pub fn report_background(&mut self, spec: &str) {
211 self.term.report_background(spec);
212 }
213
214 /// Answer an OSC 10 `QueryForeground` event (#122): queue the OSC 10 reply
215 /// from the consumer-supplied spec. Theme-agnostic envelope-only.
216 pub fn report_foreground(&mut self, spec: &str) {
217 self.term.report_foreground(spec);
218 }
219
220 /// Answer an OSC 4 `QueryPaletteColor` event (#122): queue the OSC 4 reply for
221 /// `index` from the consumer-supplied spec. Theme-agnostic envelope-only.
222 pub fn report_palette_color(&mut self, index: u8, spec: &str) {
223 self.term.report_palette_color(index, spec);
224 }
225
226 /// Whether the app enabled **win32-input-mode** (DEC `?9001`): it asked for
227 /// keys as raw Windows key-records. The engine only tracks the flag — encoding
228 /// the records (`CSI Vk;Sc;Uc;Kd;Cs;Rc _`) is a non-goal (raw passthrough, no
229 /// semantic conversion), so [`Engine::encode_key`] is unchanged. A ConPTY
230 /// consumer reads this to decide whether to emit the records itself (#86).
231 pub fn win32_input_mode(&self) -> bool {
232 self.term.win32_input_mode()
233 }
234
235 /// What changed since the last [`Engine::reset_damage`] — line ranges each
236 /// with a changed column span (see ADR-0003).
237 pub fn damage(&self) -> TermDamage {
238 self.term.damage()
239 }
240
241 /// Build a serializable [`Frame`] of the current diff — the damaged spans
242 /// (or every row, when `Full`), the recorded scroll op, and a frame-local
243 /// grapheme side-table. Pass it to [`encode`] for the wire (see #6). Reading
244 /// a frame does not clear damage; call [`Engine::reset_damage`] on ack.
245 pub fn frame(&self) -> Frame {
246 self.term.frame()
247 }
248
249 /// Clear accumulated damage after a frame is applied (the consumer's ack).
250 pub fn reset_damage(&mut self) {
251 self.term.reset_damage();
252 }
253
254 /// Force the next [`Engine::frame`] to be a `Full` frame (every row), even if
255 /// little changed. The use case is **reattach / late subscribe**: a renderer
256 /// that connects after output has already been parsed needs the whole current
257 /// viewport once, then incremental diffs. Marks the screen fully damaged; the
258 /// next `frame()` reports `FrameKind::Full`.
259 pub fn mark_fully_damaged(&mut self) {
260 self.term.mark_fully_damaged();
261 }
262
263 /// The first-class scroll recorded since the last [`Engine::reset_damage`],
264 /// if any — lets the renderer shift rows instead of redrawing them.
265 pub fn scroll_delta(&self) -> Option<ScrollOp> {
266 self.term.scroll_delta()
267 }
268
269 /// The cells of visible row `i` (0..rows) at the current scroll position.
270 pub fn viewport_line(&self, i: usize) -> &[Cell] {
271 self.term.viewport_line(i)
272 }
273
274 /// Scroll the viewport up by `n` lines into scrollback history.
275 pub fn scroll_up(&mut self, n: usize) {
276 self.term.scroll_up(n);
277 }
278
279 /// Scroll the viewport down by `n` lines toward the live screen.
280 pub fn scroll_down(&mut self, n: usize) {
281 self.term.scroll_down(n);
282 }
283
284 /// Jump the viewport back to the live screen (follow the bottom).
285 pub fn scroll_to_bottom(&mut self) {
286 self.term.scroll_to_bottom();
287 }
288
289 /// Begin a selection of `ty` at viewport cell `(row, col)`, on `side` of the
290 /// cell. Coordinates are viewport-relative (what a mouse event carries).
291 pub fn selection_begin(&mut self, row: usize, col: usize, side: Side, ty: SelectionType) {
292 self.term.selection_begin(row, col, side, ty);
293 }
294
295 /// Extend the live selection to viewport cell `(row, col)`, on `side`.
296 pub fn selection_extend(&mut self, row: usize, col: usize, side: Side) {
297 self.term.selection_extend(row, col, side);
298 }
299
300 /// Clear the selection.
301 pub fn selection_clear(&mut self) {
302 self.term.selection_clear();
303 }
304
305 /// The selection projected onto the viewport: one inclusive-column span per
306 /// visible row, for the renderer to highlight. Empty when nothing is
307 /// selected or the selection is fully scrolled off-screen.
308 pub fn selection_range(&self) -> Vec<SelectionSpan> {
309 self.term.selection_range()
310 }
311
312 /// The selected text for copy (respects scrollback), or `None` if no
313 /// selection.
314 pub fn selection_text(&self) -> Option<String> {
315 self.term.selection_text()
316 }
317
318 /// Literal search over the grid + scrollback, returning every match in
319 /// absolute buffer coordinates (top-to-bottom). Smart-case: a query with no
320 /// uppercase matches case-insensitively. The consumer drives next/prev by
321 /// walking the returned `Vec` and calling [`Engine::scroll_to_match`].
322 pub fn search(&self, query: &str) -> Vec<Match> {
323 self.term.search(query)
324 }
325
326 /// Search with explicit [`SearchOptions`] — regex, whole-word, and a case-sensitivity override
327 /// beyond the literal + smart-case [`search`](Self::search) (#314).
328 pub fn search_with(&self, query: &str, opts: SearchOptions) -> Vec<Match> {
329 self.term.search_with(query, opts)
330 }
331
332 /// The viewport's logical lines (#113/ADR-0017): each soft-wrap-joined line's
333 /// text plus a per-char map to its viewport `(row, col)`. The buffer-wide
334 /// mechanism for consumer-side URL detection — the consumer runs its own
335 /// regex / `new URL()` over the text and maps matches back through `cells`.
336 /// Also serves the a11y mirror (#119).
337 pub fn viewport_logical_lines(&self) -> Vec<LogicalLine> {
338 self.term.viewport_logical_lines()
339 }
340
341 /// The whole buffer (scrollback + screen) as one text document for a
342 /// screen-reader accessible view (#150) — soft-wrap-joined, wide-spacers
343 /// skipped, trailing blanks trimmed at the logical end, `\n` between logical
344 /// lines. A query seam the consumer summons (frame mode: over IPC, like
345 /// [`selection_text`](Self::selection_text)); no wire-format change. On the
346 /// alt screen only the alt buffer is shown.
347 pub fn accessible_text(&self) -> String {
348 self.term.accessible_text()
349 }
350
351 /// Scroll the viewport so `m` is visible (next/prev navigation: the consumer
352 /// picks the match, the engine scrolls to it).
353 pub fn scroll_to_match(&mut self, m: &Match) {
354 self.term.search_scroll_to(m);
355 }
356
357 /// The match projected onto the viewport as inclusive-column spans per
358 /// visible row, for the renderer to highlight.
359 pub fn match_spans(&self, m: &Match) -> Vec<SelectionSpan> {
360 self.term.match_spans(m)
361 }
362
363 /// Set the search highlights the frame should carry (#108). The
364 /// consumer owns match navigation, so it hands the set to highlight back
365 /// here; [`Engine::frame`] then projects them onto the viewport overlay
366 /// alongside the selection. An empty vec clears the highlights.
367 pub fn set_search_highlights(&mut self, matches: Vec<Match>) {
368 self.term.set_search_highlights(matches);
369 }
370
371 /// Designate which member of the held highlight set is the *active* match
372 /// (#428) — the one next/prev navigation currently points at (that choice is
373 /// the consumer's policy). [`Engine::frame`] projects it into the overlay's
374 /// `active_match` group; it also stays in `matches`, and the renderer's
375 /// highlight ranking resolves the overlap (#424). `None` or an out-of-range
376 /// index projects nothing. Passing a new set to
377 /// [`set_search_highlights`](Self::set_search_highlights) resets the
378 /// designation, so re-designate after every hand-over.
379 pub fn set_active_search_highlight(&mut self, index: Option<usize>) {
380 self.term.set_active_search_highlight(index);
381 }
382
383 /// Designate the *active* match by its absolute span (#436), independent of
384 /// the held highlight set — the past-cap path. A backend that caps its
385 /// hand-over (the documented 1000, xterm's `highlightLimit`) can still give
386 /// the current match its active emphasis: xterm builds its active
387 /// decoration from the found result *outside* the capped list, and this is
388 /// that model. The span projects through the same wrap-aware viewport math
389 /// as any match; past the cap it paints the ACTIVE colour only (no plain
390 /// highlight underneath — honest about the cap). `None` clears. Same
391 /// lifecycle as the index form: reset on every
392 /// [`set_search_highlights`](Self::set_search_highlights) hand-over and on
393 /// any coordinate-shifting invalidation (eviction, region scroll, reflow,
394 /// alt-screen swaps), so re-designate after each hand-over.
395 pub fn set_active_search_match(&mut self, m: Option<Match>) {
396 self.term.set_active_search_match(m);
397 }
398
399 /// Register a decoration marker at viewport `row`, returning its stable id
400 /// (#118). The marker anchors the content currently on that row and tracks
401 /// it through scroll/eviction/reflow; [`Engine::frame`] reports its viewport
402 /// position while visible. Use the id to remove it or to match the
403 /// `TermEvent::MarkerDisposed` fired when its line leaves the buffer.
404 pub fn add_marker(&mut self, row: usize) -> MarkerId {
405 self.term.add_marker(row)
406 }
407
408 /// Remove a marker by id (#118), firing `TermEvent::MarkerDisposed`. A no-op
409 /// for an unknown or already-disposed id.
410 pub fn remove_marker(&mut self, id: MarkerId) {
411 self.term.remove_marker(id);
412 }
413
414 /// The OSC 133 shell-integration command marks in buffer order — `(id,
415 /// absolute line, kind)` (#158). Excludes plain `add_marker` decorations.
416 /// The consumer pairs prompt/command/finished marks to drive prompt-to-prompt
417 /// navigation and command/exit announcements (#160); the engine only parses
418 /// the `133;A/B/C/D` sequences and anchors the marks.
419 pub fn command_marks(&self) -> Vec<(MarkerId, usize, MarkerKind)> {
420 self.term.command_marks()
421 }
422
423 /// The executed shell commands recovered from OSC-133 marks, in buffer order
424 /// (#166) — the query behind screen-reader command navigation. Each
425 /// [`CommandLine`] carries the typed command text (prompt/output excluded via
426 /// the captured columns), its jump line (CommandStart), and the exit code.
427 /// This is a full-buffer query, wired to the frame-mode consumer over IPC like
428 /// [`Engine::accessible_text`]; the web side has no scrollback cells to derive
429 /// it (ADR-0017 — buffer-wide text is core's).
430 pub fn command_lines(&self) -> Vec<CommandLine> {
431 self.term.command_lines()
432 }
433}