rich/protocol.rs
1//! Rendering & extension protocols.
2//!
3//! Port of upstream `rich/protocol.py` + `rich/abc.py` + the highlighter
4//! interface. **These traits are the sanctioned extension points of the port.**
5//! Extensions in `rich-ext` (and, later, third-party plugins) implement them;
6//! the faithful core only ever ships upstream's built-in implementations. See
7//! docs/PLUGINS.md.
8
9use crate::console::{Console, ConsoleOptions};
10use crate::measure::Measurement;
11use crate::segment::Segment;
12use crate::text::Text;
13
14/// Anything that can be rendered to a stream of [`Segment`]s within a width.
15///
16/// The Rust equivalent of upstream's `__rich_console__(console, options)`
17/// protocol. Implement it to make a custom type printable by [`Console`]. The
18/// `options` carry the available width (and, later, height/justify) the
19/// renderable must fit into. Newlines between lines are emitted as ordinary
20/// segments containing `\n`.
21pub trait Renderable {
22 fn rich_render(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment>;
23
24 /// The `(minimum, maximum)` cell width this renderable wants. The default
25 /// assumes the renderable fills the available width (e.g. `Panel`, `Table`);
26 /// `Text` overrides it with its content width so the top-level print path can
27 /// shrink to fit. Port of `__rich_measure__` / `Measurement.get`.
28 fn measure(&self, _console: &Console, options: &ConsoleOptions) -> Measurement {
29 Measurement::new(options.max_width, options.max_width)
30 }
31
32 /// Whether a top-level `Console::print` shrinks this renderable to its
33 /// measured width. Upstream renders every top-level renderable at the full
34 /// console width, so the default is `false`; an extension may opt in.
35 fn fit_to_measurement(&self) -> bool {
36 false
37 }
38
39 /// The `Text` a top-level print renders in place of this renderable.
40 ///
41 /// Upstream's `Console._collect_renderables` rebuilds printed `str`/`Text`
42 /// values through `Text(sep, end=end).join(...)`, whose `blank_copy` takes
43 /// `justify`, `overflow` and `no_wrap` from the separator. Only `Text`
44 /// overrides this.
45 #[doc(hidden)]
46 fn printed_text(&self) -> Option<Text> {
47 None
48 }
49
50 /// The vertical alignment a `Table` cell holding this renderable uses in
51 /// place of its column's. Upstream reads `getattr(renderable, "vertical",
52 /// None)`; [`Align`](crate::align::Align) sets it.
53 fn vertical(&self) -> Option<crate::align::VerticalAlign> {
54 None
55 }
56}
57
58/// Optional line-streaming extension point for renderables.
59///
60/// Mirrors the incremental consumption of upstream's rendering generators.
61/// Consumers can write each visual line immediately instead of collecting the
62/// complete segment stream. Implementations may still retain source data for
63/// measurement. This trait keeps streaming hooks out of inherent core APIs.
64pub trait LineRenderable: Renderable {
65 /// Emit styled visual lines without trailing newlines, stopping immediately
66 /// on the callback's first error. An empty segment represents a blank line;
67 /// calling the callback zero times represents no output.
68 fn try_for_each_line<E>(
69 &self,
70 console: &Console,
71 options: &ConsoleOptions,
72 emit: impl FnMut(Vec<Segment>) -> Result<(), E>,
73 ) -> Result<(), E>;
74}
75
76/// Transfer already-owned table rows without cloning every cell string.
77///
78/// This extension point changes ownership only. Column definitions, measurement
79/// and rendering follow the table's existing rules, including missing/extra cells.
80/// Producers that parse into owned strings can release their row collection as
81/// they populate a table instead of retaining a second complete copy.
82pub trait OwnedTableRows {
83 fn extend_owned_rows(&mut self, rows: Vec<Vec<String>>) -> &mut Self;
84}
85
86/// A transformer that adds style spans to [`Text`] (e.g. syntax/number/URL
87/// highlighting). The Rust equivalent of upstream's `Highlighter` ABC.
88///
89/// This is the primary *plugin* seam for the first slice: `rich-ext` registers
90/// [`Highlighter`]s onto a [`Console`] without the core knowing they exist.
91pub trait Highlighter {
92 /// Inspect `text` and apply any style spans in place.
93 fn highlight(&self, text: &mut Text);
94}
95
96/// One styled byte range of a highlighted line.
97#[derive(Clone, Debug, PartialEq)]
98pub struct HighlightSpan {
99 /// Byte range within the line (the line's text, without its `\n`).
100 pub range: std::ops::Range<usize>,
101 pub style: crate::style::Style,
102}
103
104/// The spans of one source line, plus the style of the line break after it.
105#[derive(Clone, Debug, Default, PartialEq)]
106pub struct HighlightedLine {
107 /// Sorted, non-overlapping spans. Bytes no span covers take
108 /// [`HighlightedCode::default_style`].
109 pub spans: Vec<HighlightSpan>,
110 /// The style an engine gives the `\n` ending this line (for example, inside a
111 /// multi-line string). `None` when the engine does not style line breaks.
112 pub newline_style: Option<crate::style::Style>,
113}
114
115/// What a [`CodeHighlighter`] returns: one [`HighlightedLine`] per element of
116/// `code.split('\n')`, so a trailing newline yields a final empty line.
117#[derive(Clone, Debug, Default, PartialEq)]
118pub struct HighlightedCode {
119 pub lines: Vec<HighlightedLine>,
120 /// The theme's background, if it has one. `Syntax` paints its block with it.
121 pub background: Option<crate::color::Color>,
122 /// The style for text no span covers.
123 pub default_style: crate::style::Style,
124}
125
126/// Why a [`CodeHighlighter`] could not highlight. An unknown *language* is not an
127/// error: highlighters fall back to plain text.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub enum HighlightError {
130 /// The theme name is not one this highlighter provides.
131 UnknownTheme(String),
132 /// The engine failed on this input.
133 Engine(String),
134}
135
136impl std::fmt::Display for HighlightError {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 match self {
139 HighlightError::UnknownTheme(name) => write!(f, "unknown syntax theme {name:?}"),
140 HighlightError::Engine(message) => write!(f, "syntax highlighting failed: {message}"),
141 }
142 }
143}
144
145impl std::error::Error for HighlightError {}
146
147/// A syntax-highlighting engine behind [`Syntax`](crate::syntax::Syntax) and
148/// Markdown code blocks.
149///
150/// Upstream highlights with Pygments; the port's default is
151/// [`SyntectHighlighter`](crate::syntax::SyntectHighlighter), and anything that
152/// implements this trait can replace it (see [`Syntax::highlighter`](crate::syntax::Syntax::highlighter)).
153///
154/// # Contract
155///
156/// - `lines` has one entry per element of `code.split('\n')`.
157/// - Spans are sorted, do not overlap, stay inside their line and start and end
158/// on UTF-8 character boundaries.
159/// - An unknown language highlights as plain text rather than failing.
160///
161/// Core validates what an implementation returns: out-of-range, overlapping or
162/// misaligned spans are dropped, missing lines render unstyled, and span styles
163/// lose any hyperlink. The rendered characters always come from the source, so
164/// a highlighter cannot add text or terminal control sequences.
165///
166/// ```
167/// use rich::protocol::{CodeHighlighter, HighlightError, HighlightSpan, HighlightedCode, HighlightedLine};
168/// use rich::{Console, Style, Syntax};
169/// use std::sync::Arc;
170///
171/// /// Makes every line bold.
172/// struct Bold;
173///
174/// impl CodeHighlighter for Bold {
175/// fn highlight(&self, code: &str, _language: Option<&str>, _theme: &str)
176/// -> Result<HighlightedCode, HighlightError>
177/// {
178/// let bold = Style::parse("bold").unwrap();
179/// let lines = code
180/// .split('\n')
181/// .map(|line| HighlightedLine {
182/// spans: vec![HighlightSpan { range: 0..line.len(), style: bold.clone() }]
183/// .into_iter()
184/// .filter(|span| !span.range.is_empty())
185/// .collect(),
186/// newline_style: None,
187/// })
188/// .collect();
189/// Ok(HighlightedCode { lines, ..Default::default() })
190/// }
191/// fn default_theme(&self) -> &str { "bold" }
192/// fn themes(&self) -> Vec<String> { vec!["bold".into()] }
193/// fn languages(&self) -> Vec<String> { Vec::new() }
194/// }
195///
196/// let console = Console::builder().width(20).force_terminal(true).build();
197/// let out = console.render_to_string(&Syntax::new("x = 1", "python").highlighter(Arc::new(Bold)));
198/// assert!(out.contains("\x1b[1mx = 1"));
199/// ```
200pub trait CodeHighlighter: Send + Sync {
201 /// Highlight `code`. `language` is a name or file extension (`"rust"`,
202 /// `"rs"`); `None` means plain text. `theme` is one of [`themes`](Self::themes).
203 fn highlight(
204 &self,
205 code: &str,
206 language: Option<&str>,
207 theme: &str,
208 ) -> Result<HighlightedCode, HighlightError>;
209
210 /// The theme used when none is chosen.
211 fn default_theme(&self) -> &str;
212
213 /// Every theme name `highlight` accepts.
214 fn themes(&self) -> Vec<String>;
215
216 /// Language names this highlighter knows, for help text and completion.
217 fn languages(&self) -> Vec<String>;
218
219 /// The language for a file path, if the highlighter recognises it.
220 fn language_for_path(&self, _path: &std::path::Path) -> Option<String> {
221 None
222 }
223
224 /// `theme`'s style for a Pygments token type — `"Text"` or `"Comment"` —
225 /// as upstream's `SyntaxTheme.get_style_for_token`. `Syntax` colours its
226 /// line numbers and indent guides with it; `None` (the default) means the
227 /// theme sets nothing for the token.
228 fn token_style(&self, _theme: &str, _token: &str) -> Option<crate::style::Style> {
229 None
230 }
231}
232
233/// Renders fenced Markdown code blocks of particular languages (for example
234/// ```` ```mermaid ````) in place of the usual highlighted code.
235///
236/// Upstream always renders a fence through `Syntax`, and so does
237/// [`Markdown`](crate::markdown::Markdown) unless a renderer is added with
238/// [`Markdown::fence_renderer`](crate::markdown::Markdown::fence_renderer).
239/// Markdown asks each renderer in turn; the first to return `Some` wins, and if
240/// none does the block is highlighted as code as before.
241///
242/// The fence body comes from the document, so treat it as untrusted: whatever
243/// text of it an implementation echoes must not carry terminal control
244/// sequences.
245pub trait FenceRenderer: Send + Sync {
246 /// Render the body of a fence whose info string starts with `language`, or
247 /// return `None` to decline. The returned segments fit `options.max_width`
248 /// and separate lines with `\n` segments, like [`Renderable::rich_render`].
249 fn render_fence(
250 &self,
251 language: &str,
252 code: &str,
253 console: &Console,
254 options: &ConsoleOptions,
255 ) -> Option<Vec<Segment>>;
256}
257
258/// A console-wide default [`CodeHighlighter`] and the theme to use with it.
259/// See [`ConsoleCodeHighlighting`].
260#[derive(Clone)]
261pub struct CodeHighlighting {
262 pub highlighter: std::sync::Arc<dyn CodeHighlighter>,
263 /// One of `highlighter`'s themes; `None` is its default theme.
264 pub theme: Option<String>,
265}
266
267impl std::fmt::Debug for CodeHighlighting {
268 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269 f.debug_struct("CodeHighlighting")
270 .field("default_theme", &self.highlighter.default_theme())
271 .field("theme", &self.theme)
272 .finish()
273 }
274}
275
276/// Attach/query a console's default code highlighter.
277///
278/// A [`Syntax`](crate::syntax::Syntax) without a highlighter of its own, and
279/// so Markdown code blocks, highlights with the console's when it renders;
280/// the console's theme applies when the `Syntax` names none. Without one,
281/// the default [`SyntectHighlighter`](crate::syntax::SyntectHighlighter) is
282/// used, as before: upstream has no such setting.
283pub trait ConsoleCodeHighlighting {
284 fn set_code_highlighting(&mut self, value: Option<CodeHighlighting>);
285 fn code_highlighting(&self) -> Option<&CodeHighlighting>;
286}
287
288/// Evidence for an optional output protocol; inference is not confirmation.
289#[derive(Clone, Copy, Debug, PartialEq, Eq)]
290pub enum Support {
291 Unsupported,
292 Inferred,
293 Confirmed,
294}
295
296/// Immutable destination capabilities supplied by an extension. No detection or I/O.
297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298pub struct TargetCapabilities {
299 pub width: usize,
300 pub height: usize,
301 pub color_system: Option<crate::color::ColorSystem>,
302 pub interactive: bool,
303 pub unicode: bool,
304 pub hyperlinks: bool,
305 pub sixel: Support,
306}
307
308/// Optional context shared by nested renderables without changing their protocol.
309pub trait RenderEnvironment: Send + Sync {
310 fn capabilities(&self) -> TargetCapabilities;
311}
312
313/// Attach/query a per-console immutable extension environment.
314pub trait ConsoleEnvironment {
315 fn set_render_environment(&mut self, value: Option<std::sync::Arc<dyn RenderEnvironment>>);
316 fn render_environment(&self) -> Option<&dyn RenderEnvironment>;
317}