返回 CodeWhale
transcript.rs
根目录 / vendor / codewhale-ratatui / src / components / transcript.rs
1 //! A caller-authored transcript: headings, prose with semantic spans,
2 //! quotes, lists, tables and inset code.
3 //!
4 //! The host owns the parser, the clipboard and the scroll position. This kit
5 //! owns wrapping, clipping and honesty: a link target is metadata that never
6 //! reaches the screen, `copy_text` is the exact original source, and a
7 //! caller's semantic role is painted as the caller asked. No syntax parser,
8 //! no OSC sequence, no file access.
9
10 use std::borrow::Cow;
11
12 use ratatui::{
13 buffer::Buffer,
14 layout::Rect,
15 style::{Modifier, Style},
16 text::{Line, Span},
17 widgets::{
18 Block, BorderType, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
19 StatefulWidget, Widget, Wrap,
20 },
21 };
22 use unicode_segmentation::UnicodeSegmentation;
23
24 use crate::{Paint, Role, Theme, text};
25
26 use super::workbench::row;
27
28 /// One atom of painted ink: a grapheme and the style it was asked to carry.
29 type Atom = (String, Style);
30
31 fn push_atom(row: &mut Vec<Atom>, grapheme: &str, style: Style) {
32 row.push((grapheme.to_string(), style));
33 }
34
35 fn row_width(row: &[Atom]) -> usize {
36 row.iter().map(|(text, _)| text::width(text)).sum()
37 }
38
39 /// Split a row at its last whitespace atom: everything before stays, the
40 /// remainder carries to the next row. Without whitespace the row is kept
41 /// whole and the caller breaks it hard.
42 fn split_at_space(row: &[Atom]) -> (Vec<Atom>, Vec<Atom>) {
43 let Some(index) = row
44 .iter()
45 .rposition(|(text, _)| !text.is_empty() && text.chars().all(char::is_whitespace))
46 else {
47 return (row.to_vec(), Vec::new());
48 };
49 (row[..index].to_vec(), row[index + 1..].to_vec())
50 }
51
52 /// Word-aware wrapping over grapheme atoms. `first` budgets the first row and
53 /// `rest` every continuation; a grapheme wider than the budget still lands.
54 fn wrap_atoms(atoms: &[Atom], first: usize, rest: usize) -> Vec<Vec<Atom>> {
55 let mut rows: Vec<Vec<Atom>> = Vec::new();
56 let mut row: Vec<Atom> = Vec::new();
57 let mut width = 0usize;
58 let mut budget = first.max(1);
59 for (grapheme, style) in atoms {
60 let glyph = text::width(grapheme);
61 if width > 0 && width + glyph > budget {
62 let (keep, carry) = split_at_space(&row);
63 if !keep.is_empty() && !carry.is_empty() {
64 rows.push(keep);
65 row = carry;
66 width = row_width(&row);
67 } else {
68 rows.push(std::mem::take(&mut row));
69 width = 0;
70 }
71 budget = rest.max(1);
72 }
73 push_atom(&mut row, grapheme, *style);
74 width += glyph;
75 }
76 if !row.is_empty() {
77 rows.push(row);
78 }
79 if rows.is_empty() {
80 rows.push(Vec::new());
81 }
82 rows
83 }
84
85 fn row_line(row: &[Atom]) -> Line<'static> {
86 let mut spans: Vec<Span<'static>> = Vec::new();
87 for (text, style) in row {
88 if let Some(last) = spans.last_mut().filter(|last| last.style == *style) {
89 last.content.to_mut().push_str(text);
90 } else {
91 spans.push(Span::styled(text.clone(), *style));
92 }
93 }
94 Line::from(spans)
95 }
96
97 fn prefixed(prefix: &str, style: Style, line: Line<'static>) -> Line<'static> {
98 let mut spans = Vec::with_capacity(line.spans.len() + 1);
99 spans.push(Span::styled(prefix.to_string(), style));
100 spans.extend(line.spans);
101 Line::from(spans)
102 }
103
104 /// Wrap logical lines behind a prefix. The first visual row carries `prefix`;
105 /// every later row carries `indent`, which is the same rail for a quote and
106 /// blank gutter or list padding elsewhere.
107 fn flow(
108 logical: Vec<Vec<Atom>>,
109 first: usize,
110 rest: usize,
111 prefix: &str,
112 prefix_style: Style,
113 indent: &str,
114 ) -> Vec<Line<'static>> {
115 let mut out = Vec::new();
116 let mut leading = true;
117 for (index, atoms) in logical.into_iter().enumerate() {
118 let budget = if index == 0 { first } else { rest };
119 for (row_index, atoms) in wrap_atoms(&atoms, budget, rest).into_iter().enumerate() {
120 let line = row_line(&atoms);
121 if leading && row_index == 0 {
122 out.push(prefixed(prefix, prefix_style, line));
123 leading = false;
124 } else if indent.is_empty() {
125 out.push(line);
126 } else {
127 out.push(prefixed(indent, Style::default(), line));
128 }
129 }
130 }
131 out
132 }
133
134 fn wrapped(logical: Vec<Vec<Atom>>, first: usize, rest: usize) -> Vec<Line<'static>> {
135 flow(logical, first, rest, "", Style::default(), "")
136 }
137
138 /// Sanitized single-style text, split into logical lines on `\n`.
139 fn ink_atoms(value: &str, style: Style) -> Vec<Vec<Atom>> {
140 // Split structural newlines before filtering hidden controls. The generic
141 // single-line sanitizer intentionally removes every control, including LF.
142 value
143 .split('\n')
144 .map(|line| {
145 let expanded = line.replace('\t', " ");
146 let safe = text::display_safe(&expanded);
147 let mut atoms = Vec::new();
148 for grapheme in safe.graphemes(true) {
149 push_atom(&mut atoms, grapheme, style);
150 }
151 atoms
152 })
153 .collect()
154 }
155
156 /// Sanitized caller spans, split into logical lines on `\n`.
157 fn span_atoms<'a>(spans: &[TranscriptSpan<'a>], theme: &Theme) -> Vec<Vec<Atom>> {
158 let mut lines: Vec<Vec<Atom>> = vec![Vec::new()];
159 for span in spans {
160 let style = span.style(theme);
161 for (index, piece) in span.text.split('\n').enumerate() {
162 if index > 0 {
163 lines.push(Vec::new());
164 }
165 let expanded = piece.replace('\t', " ");
166 let safe = text::display_safe(&expanded);
167 for grapheme in safe.graphemes(true) {
168 push_atom(
169 lines.last_mut().expect("one line is always present"),
170 grapheme,
171 style,
172 );
173 }
174 }
175 }
176 lines
177 }
178
179 fn paint_lines(area: Rect, buf: &mut Buffer, lines: &[Line<'static>], offset: usize) {
180 for (index, line) in lines
181 .iter()
182 .skip(offset)
183 .take(usize::from(area.height))
184 .enumerate()
185 {
186 let y = area
187 .y
188 .saturating_add(u16::try_from(index).unwrap_or(u16::MAX));
189 if line.style.bg.is_some() {
190 buf.set_style(Rect::new(area.x, y, area.width, 1), line.style);
191 }
192 row(Rect::new(area.x, y, area.width, 1), buf, line);
193 }
194 }
195
196 fn table_row_line(
197 cells: &[String],
198 widths: &[usize],
199 separator: &str,
200 separator_style: Style,
201 cell_style: Style,
202 ascii: bool,
203 ) -> Line<'static> {
204 let mut spans = Vec::new();
205 for (index, cell) in cells.iter().enumerate() {
206 if index > 0 {
207 spans.push(Span::styled(separator.to_string(), separator_style));
208 }
209 let width = widths.get(index).copied().unwrap_or(0);
210 spans.push(Span::styled(text::pad(cell, width, ascii), cell_style));
211 }
212 Line::from(spans)
213 }
214
215 /// A narrow table reads as one `column: value` entry per row rather than
216 /// columns squeezed past legibility.
217 fn stacked_lines(
218 header: &[String],
219 body: &[Vec<String>],
220 width: usize,
221 theme: &Theme,
222 ) -> Vec<Line<'static>> {
223 let mut out = Vec::new();
224 for cells in body {
225 for (index, cell) in cells.iter().enumerate() {
226 let name = header.get(index).map(String::as_str).unwrap_or("");
227 let entry = if name.is_empty() {
228 cell.clone()
229 } else {
230 format!("{name}: {cell}")
231 };
232 out.extend(wrapped(
233 ink_atoms(&entry, theme.fg(Role::Foreground)),
234 width,
235 width,
236 ));
237 }
238 }
239 out
240 }
241
242 fn table_lines<'a>(
243 columns: &[Cow<'a, str>],
244 rows: &[Vec<Cow<'a, str>>],
245 width: usize,
246 theme: &Theme,
247 ) -> Vec<Line<'static>> {
248 let ascii = theme.ascii();
249 let col_count = columns
250 .len()
251 .max(rows.iter().map(Vec::len).max().unwrap_or(0));
252 if col_count == 0 {
253 return Vec::new();
254 }
255 let header: Vec<String> = (0..col_count)
256 .map(|index| {
257 columns
258 .get(index)
259 .map(|cell| text::display_safe(&cell.replace(['\n', '\r', '\t'], " ")).into_owned())
260 .unwrap_or_default()
261 })
262 .collect();
263 let body: Vec<Vec<String>> = rows
264 .iter()
265 .map(|row| {
266 (0..col_count)
267 .map(|index| {
268 row.get(index)
269 .map(|cell| {
270 text::display_safe(&cell.replace(['\n', '\r', '\t'], " ")).into_owned()
271 })
272 .unwrap_or_default()
273 })
274 .collect()
275 })
276 .collect();
277 let separator = if ascii { " | " } else { " │ " };
278 let separator_width = text::width(separator);
279 let fixed = separator_width * col_count.saturating_sub(1);
280 let mut widths: Vec<usize> = (0..col_count)
281 .map(|index| {
282 let header_width = text::width(&header[index]);
283 let body_width = body
284 .iter()
285 .map(|row| text::width(&row[index]))
286 .max()
287 .unwrap_or(0);
288 header_width.max(body_width).min(32)
289 })
290 .collect();
291 while widths.iter().sum::<usize>() + fixed > width && widths.iter().any(|w| *w > 3) {
292 let widest = widths
293 .iter()
294 .enumerate()
295 .max_by_key(|(_, width)| **width)
296 .map(|(index, _)| index)
297 .unwrap_or(0);
298 widths[widest] = widths[widest].saturating_sub(1);
299 }
300 if widths.iter().sum::<usize>() + fixed > width {
301 return stacked_lines(&header, &body, width, theme);
302 }
303 let mut out = vec![table_row_line(
304 &header,
305 &widths,
306 separator,
307 theme.fg(Role::Border),
308 theme.fg(Role::Muted).add_modifier(Modifier::BOLD),
309 ascii,
310 )];
311 for row in &body {
312 out.push(table_row_line(
313 row,
314 &widths,
315 separator,
316 theme.fg(Role::Border),
317 theme.fg(Role::Foreground),
318 ascii,
319 ));
320 }
321 out
322 }
323
324 /// The semantic role a caller gave one span. The kit paints this role; it
325 /// never inspects the text to guess a different one.
326 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
327 pub enum TranscriptSpanRole {
328 Text,
329 Strong,
330 Emphasis,
331 Code,
332 Link,
333 Muted,
334 Success,
335 Warning,
336 }
337
338 impl TranscriptSpanRole {
339 pub const ALL: [Self; 8] = [
340 Self::Text,
341 Self::Strong,
342 Self::Emphasis,
343 Self::Code,
344 Self::Link,
345 Self::Muted,
346 Self::Success,
347 Self::Warning,
348 ];
349
350 #[must_use]
351 pub const fn role(self) -> Role {
352 match self {
353 Self::Text | Self::Strong | Self::Emphasis => Role::Foreground,
354 Self::Code | Self::Success => Role::Live,
355 Self::Link => Role::Accent,
356 Self::Muted => Role::Muted,
357 Self::Warning => Role::Attention,
358 }
359 }
360
361 #[must_use]
362 pub fn style(self, theme: &Theme) -> Style {
363 let base = theme.fg(self.role());
364 match self {
365 Self::Strong => base.add_modifier(Modifier::BOLD),
366 Self::Emphasis => base.add_modifier(Modifier::ITALIC),
367 // Underline is the only link mark: the target is never an escape
368 // sequence, an OSC 8 hyperlink or a file destination.
369 Self::Link => base.add_modifier(Modifier::UNDERLINED),
370 _ => base,
371 }
372 }
373 }
374
375 /// One run of text with the semantic role its author gave it. `target` is
376 /// link metadata for the host; it is never painted.
377 #[derive(Clone, Debug, PartialEq, Eq)]
378 pub struct TranscriptSpan<'a> {
379 pub text: Cow<'a, str>,
380 pub role: TranscriptSpanRole,
381 pub target: Option<Cow<'a, str>>,
382 }
383
384 impl<'a> TranscriptSpan<'a> {
385 #[must_use]
386 pub fn new(text: impl Into<Cow<'a, str>>, role: TranscriptSpanRole) -> Self {
387 Self {
388 text: text.into(),
389 role,
390 target: None,
391 }
392 }
393
394 #[must_use]
395 pub fn plain(text: impl Into<Cow<'a, str>>) -> Self {
396 Self::new(text, TranscriptSpanRole::Text)
397 }
398
399 #[must_use]
400 pub fn strong(text: impl Into<Cow<'a, str>>) -> Self {
401 Self::new(text, TranscriptSpanRole::Strong)
402 }
403
404 #[must_use]
405 pub fn emphasis(text: impl Into<Cow<'a, str>>) -> Self {
406 Self::new(text, TranscriptSpanRole::Emphasis)
407 }
408
409 #[must_use]
410 pub fn code(text: impl Into<Cow<'a, str>>) -> Self {
411 Self::new(text, TranscriptSpanRole::Code)
412 }
413
414 #[must_use]
415 pub fn muted(text: impl Into<Cow<'a, str>>) -> Self {
416 Self::new(text, TranscriptSpanRole::Muted)
417 }
418
419 #[must_use]
420 pub fn success(text: impl Into<Cow<'a, str>>) -> Self {
421 Self::new(text, TranscriptSpanRole::Success)
422 }
423
424 #[must_use]
425 pub fn warning(text: impl Into<Cow<'a, str>>) -> Self {
426 Self::new(text, TranscriptSpanRole::Warning)
427 }
428
429 /// A link whose visible text is painted and whose target stays out of
430 /// band for the host's own dispatch.
431 #[must_use]
432 pub fn link(text: impl Into<Cow<'a, str>>, target: impl Into<Cow<'a, str>>) -> Self {
433 let mut span = Self::new(text, TranscriptSpanRole::Link);
434 span.target = Some(target.into());
435 span
436 }
437
438 #[must_use]
439 pub fn target(mut self, target: impl Into<Cow<'a, str>>) -> Self {
440 self.target = Some(target.into());
441 self
442 }
443
444 #[must_use]
445 pub fn style(&self, theme: &Theme) -> Style {
446 self.role.style(theme)
447 }
448 }
449
450 /// One action a code block reports to the host. The kit never copies.
451 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
452 pub enum TranscriptAction {
453 Copy,
454 }
455
456 impl TranscriptAction {
457 #[must_use]
458 pub const fn word(self) -> &'static str {
459 match self {
460 Self::Copy => "Copy",
461 }
462 }
463 }
464
465 const COPY_ACTIONS: [TranscriptAction; 1] = [TranscriptAction::Copy];
466 const NO_ACTIONS: [TranscriptAction; 0] = [];
467
468 /// Inset code with a language, an optional gutter and exact copy text.
469 ///
470 /// `source` is the original, verbatim: `source()` and `copy_text()` return it
471 /// unchanged, newlines included. Painting uses `display`, when given, or the
472 /// sanitized source, and never mutates what a host would copy.
473 #[derive(Clone, Debug)]
474 pub struct CodeBlock<'a> {
475 pub language: Cow<'a, str>,
476 pub source: Cow<'a, str>,
477 pub display: Option<Cow<'a, str>>,
478 pub gutter: bool,
479 pub inset: u16,
480 pub copy: bool,
481 pub copy_label: Cow<'a, str>,
482 /// Optional caller semantic spans over the display text.
483 pub spans: Vec<TranscriptSpan<'a>>,
484 /// Render a full-width docked header (`language · N lines` left, `Copy` right).
485 pub docked_header: bool,
486 }
487
488 impl<'a> CodeBlock<'a> {
489 #[must_use]
490 pub fn new(language: impl Into<Cow<'a, str>>, source: impl Into<Cow<'a, str>>) -> Self {
491 Self {
492 language: language.into(),
493 source: source.into(),
494 display: None,
495 gutter: true,
496 inset: 2,
497 copy: true,
498 copy_label: Cow::Borrowed("Copy"),
499 spans: Vec::new(),
500 docked_header: false,
501 }
502 }
503
504 /// Render a full-width docked header (`language · N lines` left, `Copy`
505 /// right-aligned) instead of the default inline header.
506 #[must_use]
507 pub fn docked_header(mut self, docked: bool) -> Self {
508 self.docked_header = docked;
509 self
510 }
511
512 /// A separate display copy. The original `source` is still what is copied.
513 #[must_use]
514 pub fn display(mut self, display: impl Into<Cow<'a, str>>) -> Self {
515 self.display = Some(display.into());
516 self
517 }
518
519 #[must_use]
520 pub fn gutter(mut self, gutter: bool) -> Self {
521 self.gutter = gutter;
522 self
523 }
524
525 #[must_use]
526 pub fn inset(mut self, inset: u16) -> Self {
527 self.inset = inset;
528 self
529 }
530
531 #[must_use]
532 pub fn copyable(mut self, copy: bool) -> Self {
533 self.copy = copy;
534 self
535 }
536
537 #[must_use]
538 pub fn copy_label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
539 self.copy_label = label.into();
540 self
541 }
542
543 /// Caller-owned semantic spans for the display text. The kit paints these
544 /// roles and never classifies the code itself.
545 #[must_use]
546 pub fn spans(mut self, spans: Vec<TranscriptSpan<'a>>) -> Self {
547 self.spans = spans;
548 self
549 }
550
551 /// The exact original text, newlines included.
552 #[must_use]
553 pub fn source(&self) -> &str {
554 &self.source
555 }
556
557 /// The exact original text a host would put on the clipboard.
558 #[must_use]
559 pub fn copy_text(&self) -> &str {
560 &self.source
561 }
562
563 /// What this block paints, sanitized at paint time.
564 #[must_use]
565 pub fn display_text(&self) -> &str {
566 self.display.as_deref().unwrap_or(&self.source)
567 }
568
569 #[must_use]
570 pub fn copy_action(&self) -> Option<TranscriptAction> {
571 self.copy.then_some(TranscriptAction::Copy)
572 }
573
574 #[must_use]
575 pub fn actions(&self) -> &'static [TranscriptAction] {
576 if self.copy {
577 &COPY_ACTIONS
578 } else {
579 &NO_ACTIONS
580 }
581 }
582
583 /// The block's painted rows at `width`: an optional language and Copy
584 /// header, then the wrapped, gutter-numbered body.
585 #[must_use]
586 pub fn lines(&self, width: u16, theme: &Theme) -> Vec<Line<'static>> {
587 let cells = usize::from(width);
588 if cells == 0 {
589 return Vec::new();
590 }
591 let ascii = theme.ascii();
592 let logical = if self.spans.is_empty() {
593 ink_atoms(self.display_text(), theme.fg(Role::Foreground))
594 } else {
595 span_atoms(&self.spans, theme)
596 };
597 let count = logical.len().max(1);
598 let mut out = Vec::new();
599 let language = text::display_safe(&self.language);
600 let copy_label = text::display_safe(&self.copy_label);
601 if self.docked_header {
602 let line_word = if count == 1 { "line" } else { "lines" };
603 let sep = if ascii { " - " } else { " · " };
604 let count_text = format!("{count} {line_word}");
605 let suffix = format!("{sep}{count_text}");
606 let fit_left = |budget: usize| -> String {
607 if language.is_empty() {
608 text::truncate(&count_text, budget, ascii).into_owned()
609 } else {
610 let full = format!("{language}{suffix}");
611 if text::width(&full) <= budget {
612 full
613 } else if budget > text::width(&suffix) + 2 {
614 let lang_fit =
615 text::truncate(&language, budget - text::width(&suffix), ascii);
616 format!("{lang_fit}{suffix}")
617 } else {
618 text::truncate(&full, budget, ascii).into_owned()
619 }
620 }
621 };
622 let right_plain = if self.copy { copy_label.as_ref() } else { "" };
623 let right_w = text::width(right_plain);
624 let mut spans: Vec<Span<'static>> = Vec::new();
625 if !right_plain.is_empty() && cells > right_w + 2 {
626 let left_fit = fit_left(cells - right_w - 1);
627 let left_w = text::width(&left_fit);
628 let pad = cells.saturating_sub(left_w + right_w);
629 spans.push(Span::styled(
630 left_fit,
631 theme.fg(Role::Muted).add_modifier(Modifier::BOLD),
632 ));
633 if pad > 0 {
634 spans.push(Span::raw(" ".repeat(pad)));
635 }
636 spans.push(Span::styled(right_plain.to_owned(), theme.fg(Role::Accent)));
637 } else {
638 spans.push(Span::styled(
639 fit_left(cells),
640 theme.fg(Role::Muted).add_modifier(Modifier::BOLD),
641 ));
642 }
643 out.push(Line::from(spans));
644 } else if !language.is_empty() || self.copy {
645 let mut spans: Vec<Span<'static>> = Vec::new();
646 let lang_w = text::width(&language);
647 let copy_w = if self.copy {
648 text::width(&copy_label)
649 } else {
650 0
651 };
652 if !language.is_empty() && self.copy {
653 if lang_w + 2 + copy_w <= cells {
654 spans.push(Span::styled(
655 language.into_owned(),
656 theme.fg(Role::Muted).add_modifier(Modifier::BOLD),
657 ));
658 spans.push(Span::raw(" "));
659 spans.push(Span::styled(
660 copy_label.into_owned(),
661 theme.fg(Role::Accent),
662 ));
663 } else if cells > copy_w + 3 {
664 let clipped = text::truncate(&language, cells - copy_w - 2, ascii);
665 spans.push(Span::styled(
666 clipped.into_owned(),
667 theme.fg(Role::Muted).add_modifier(Modifier::BOLD),
668 ));
669 spans.push(Span::raw(" "));
670 spans.push(Span::styled(
671 copy_label.into_owned(),
672 theme.fg(Role::Accent),
673 ));
674 } else {
675 let clipped = text::truncate(&language, cells, ascii);
676 spans.push(Span::styled(
677 clipped.into_owned(),
678 theme.fg(Role::Muted).add_modifier(Modifier::BOLD),
679 ));
680 }
681 } else if !language.is_empty() {
682 let clipped = text::truncate(&language, cells, ascii);
683 spans.push(Span::styled(
684 clipped.into_owned(),
685 theme.fg(Role::Muted).add_modifier(Modifier::BOLD),
686 ));
687 } else if self.copy {
688 let clipped = text::truncate(&copy_label, cells, ascii);
689 spans.push(Span::styled(clipped.into_owned(), theme.fg(Role::Accent)));
690 }
691 out.push(Line::from(spans));
692 }
693 let digits = count.to_string().len().max(2);
694 let rail = if ascii { "| " } else { "│ " };
695 let gutter = self.gutter && cells >= digits + 1 + text::width(rail) + 2;
696 let gutter_width = if gutter {
697 digits + 1 + text::width(rail)
698 } else {
699 0
700 };
701 let inset = usize::from(self.inset).min(cells.saturating_sub(gutter_width + 2));
702 let lead = " ".repeat(inset);
703 let indent = " ".repeat(gutter_width + inset);
704 let prefix_width = gutter_width + inset;
705 let budget = cells.saturating_sub(prefix_width).max(1);
706 for (index, atoms) in logical.into_iter().enumerate() {
707 let prefix = if gutter {
708 format!("{:>width$} {}{}", index + 1, rail, lead, width = digits)
709 } else {
710 lead.clone()
711 };
712 out.extend(flow(
713 vec![atoms],
714 budget,
715 budget,
716 &prefix,
717 theme.fg(Role::Border),
718 &indent,
719 ));
720 }
721 for line in &mut out {
722 line.style = line.style.patch(theme.bg(Role::Surface));
723 }
724 out
725 }
726
727 #[must_use]
728 pub fn height(&self, width: u16, theme: &Theme) -> u16 {
729 u16::try_from(self.lines(width, theme).len()).unwrap_or(u16::MAX)
730 }
731 }
732
733 impl Paint for CodeBlock<'_> {
734 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
735 let area = area.intersection(buf.area);
736 if area.is_empty() {
737 return;
738 }
739 let lines = self.lines(area.width, theme);
740 paint_lines(area, buf, &lines, 0);
741 }
742
743 fn height(&self, width: u16, theme: &Theme) -> u16 {
744 u16::try_from(self.lines(width, theme).len()).unwrap_or(u16::MAX)
745 }
746 }
747
748 /// One structured block a caller authored. The host parses; the kit paints.
749 #[derive(Clone, Debug)]
750 pub enum TranscriptBlock<'a> {
751 /// A heading, `1` through `6`.
752 Heading { level: u8, text: Cow<'a, str> },
753 /// Prose with caller semantic spans.
754 Paragraph { spans: Vec<TranscriptSpan<'a>> },
755 /// A quote with an optional attribution line.
756 Quote {
757 text: Cow<'a, str>,
758 attribution: Option<Cow<'a, str>>,
759 },
760 /// A list; `ordered` numbers the items.
761 List {
762 items: Vec<TranscriptSpan<'a>>,
763 ordered: bool,
764 },
765 /// A table whose first row is `columns`.
766 Table {
767 columns: Vec<Cow<'a, str>>,
768 rows: Vec<Vec<Cow<'a, str>>>,
769 },
770 /// Inset code with a language, a gutter and copy metadata.
771 Code(CodeBlock<'a>),
772 }
773
774 impl<'a> TranscriptBlock<'a> {
775 #[must_use]
776 pub fn heading(level: u8, text: impl Into<Cow<'a, str>>) -> Self {
777 Self::Heading {
778 level,
779 text: text.into(),
780 }
781 }
782
783 #[must_use]
784 pub fn paragraph(spans: Vec<TranscriptSpan<'a>>) -> Self {
785 Self::Paragraph { spans }
786 }
787
788 /// A paragraph of plain prose.
789 #[must_use]
790 pub fn prose(text: impl Into<Cow<'a, str>>) -> Self {
791 Self::Paragraph {
792 spans: vec![TranscriptSpan::plain(text)],
793 }
794 }
795
796 #[must_use]
797 pub fn quote(text: impl Into<Cow<'a, str>>) -> Self {
798 Self::Quote {
799 text: text.into(),
800 attribution: None,
801 }
802 }
803
804 #[must_use]
805 pub fn quote_by(text: impl Into<Cow<'a, str>>, attribution: impl Into<Cow<'a, str>>) -> Self {
806 Self::Quote {
807 text: text.into(),
808 attribution: Some(attribution.into()),
809 }
810 }
811
812 #[must_use]
813 pub fn list(items: Vec<TranscriptSpan<'a>>) -> Self {
814 Self::List {
815 items,
816 ordered: false,
817 }
818 }
819
820 #[must_use]
821 pub fn ordered(items: Vec<TranscriptSpan<'a>>) -> Self {
822 Self::List {
823 items,
824 ordered: true,
825 }
826 }
827
828 #[must_use]
829 pub fn table(columns: Vec<Cow<'a, str>>, rows: Vec<Vec<Cow<'a, str>>>) -> Self {
830 Self::Table { columns, rows }
831 }
832
833 #[must_use]
834 pub fn code(block: CodeBlock<'a>) -> Self {
835 Self::Code(block)
836 }
837
838 /// The block's painted rows at `width`.
839 #[must_use]
840 pub fn lines(&self, width: u16, theme: &Theme) -> Vec<Line<'static>> {
841 let cells = usize::from(width).max(1);
842 let ascii = theme.ascii();
843 match self {
844 Self::Heading { level, text } => {
845 let style = match level {
846 1 => theme.fg(Role::Accent).add_modifier(Modifier::BOLD),
847 2 => theme.fg(Role::Foreground).add_modifier(Modifier::BOLD),
848 _ => theme.fg(Role::Muted).add_modifier(Modifier::BOLD),
849 };
850 wrapped(ink_atoms(text, style), cells, cells)
851 }
852 Self::Paragraph { spans } => wrapped(span_atoms(spans, theme), cells, cells),
853 Self::Quote { text, attribution } => {
854 let rail = if ascii { "| " } else { "▏ " };
855 let ink = theme.fg(Role::Foreground).add_modifier(Modifier::ITALIC);
856 let inner = cells.saturating_sub(2).max(1);
857 let mut out = flow(
858 ink_atoms(text, ink),
859 inner,
860 inner,
861 rail,
862 theme.fg(Role::Border),
863 rail,
864 );
865 if let Some(attribution) = attribution {
866 let dash = if ascii { "- " } else { "— " };
867 let line = format!("{dash}{}", text::display_safe(attribution));
868 out.extend(flow(
869 ink_atoms(&line, theme.fg(Role::Muted)),
870 inner,
871 inner,
872 rail,
873 theme.fg(Role::Border),
874 rail,
875 ));
876 }
877 out
878 }
879 Self::List { items, ordered } => {
880 let mut out = Vec::new();
881 for (index, item) in items.iter().enumerate() {
882 let prefix = if *ordered {
883 format!("{}. ", index + 1)
884 } else if ascii {
885 "- ".to_string()
886 } else {
887 "• ".to_string()
888 };
889 let prefix_width = text::width(&prefix);
890 let inner = cells.saturating_sub(prefix_width).max(1);
891 let indent = " ".repeat(prefix_width);
892 out.extend(flow(
893 span_atoms(std::slice::from_ref(item), theme),
894 inner,
895 inner,
896 &prefix,
897 theme.fg(Role::Muted),
898 &indent,
899 ));
900 }
901 out
902 }
903 Self::Table { columns, rows } => table_lines(columns, rows, cells, theme),
904 Self::Code(block) => block.lines(width, theme),
905 }
906 }
907
908 #[must_use]
909 pub fn height(&self, width: u16, theme: &Theme) -> u16 {
910 u16::try_from(self.lines(width, theme).len()).unwrap_or(u16::MAX)
911 }
912 }
913
914 impl Paint for TranscriptBlock<'_> {
915 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
916 let area = area.intersection(buf.area);
917 if area.is_empty() {
918 return;
919 }
920 let lines = self.lines(area.width, theme);
921 paint_lines(area, buf, &lines, 0);
922 }
923
924 fn height(&self, width: u16, theme: &Theme) -> u16 {
925 u16::try_from(self.lines(width, theme).len()).unwrap_or(u16::MAX)
926 }
927 }
928
929 /// A link the host may dispatch: the visible text and the out-of-band target.
930 /// The target is never painted, opened or written to a file by the kit.
931 #[derive(Clone, Debug, PartialEq, Eq)]
932 pub struct TranscriptLink {
933 pub text: String,
934 pub target: String,
935 }
936
937 fn collect_links(spans: &[TranscriptSpan<'_>], links: &mut Vec<TranscriptLink>) {
938 for span in spans {
939 if let Some(target) = &span.target {
940 links.push(TranscriptLink {
941 text: text::display_safe(&span.text).into_owned(),
942 target: target.to_string(),
943 });
944 }
945 }
946 }
947
948 /// A caller-authored transcript. `offset` is the host's scroll position in
949 /// painted rows: paint clips to it and to the given height.
950 #[derive(Clone, Debug, Default)]
951 pub struct Transcript<'a> {
952 pub blocks: Vec<TranscriptBlock<'a>>,
953 pub offset: usize,
954 }
955
956 impl<'a> Transcript<'a> {
957 #[must_use]
958 pub fn new(blocks: Vec<TranscriptBlock<'a>>) -> Self {
959 Self { blocks, offset: 0 }
960 }
961
962 #[must_use]
963 pub fn offset(mut self, offset: usize) -> Self {
964 self.offset = offset;
965 self
966 }
967
968 #[must_use]
969 pub fn block(mut self, block: TranscriptBlock<'a>) -> Self {
970 self.blocks.push(block);
971 self
972 }
973
974 /// Every painted row at `width`, before the host's offset clips it.
975 #[must_use]
976 pub fn lines(&self, width: u16, theme: &Theme) -> Vec<Line<'static>> {
977 let mut out = Vec::new();
978 for block in &self.blocks {
979 out.extend(block.lines(width, theme));
980 }
981 out
982 }
983
984 #[must_use]
985 pub fn height(&self, width: u16, theme: &Theme) -> u16 {
986 u16::try_from(self.lines(width, theme).len()).unwrap_or(u16::MAX)
987 }
988
989 /// Every link in the transcript, in reading order. Out-of-band metadata
990 /// for the host; nothing here paints.
991 #[must_use]
992 pub fn links(&self) -> Vec<TranscriptLink> {
993 let mut links = Vec::new();
994 for block in &self.blocks {
995 match block {
996 TranscriptBlock::Paragraph { spans } => collect_links(spans, &mut links),
997 TranscriptBlock::List { items, .. } => collect_links(items, &mut links),
998 TranscriptBlock::Code(block) => collect_links(&block.spans, &mut links),
999 _ => {}
1000 }
1001 }
1002 links
1003 }
1004 }
1005
1006 impl Paint for Transcript<'_> {
1007 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
1008 let area = area.intersection(buf.area);
1009 if area.is_empty() {
1010 return;
1011 }
1012 let lines = self.lines(area.width, theme);
1013 paint_lines(area, buf, &lines, self.offset);
1014 }
1015
1016 fn height(&self, width: u16, theme: &Theme) -> u16 {
1017 u16::try_from(self.lines(width, theme).len()).unwrap_or(u16::MAX)
1018 }
1019 }
1020
1021 // Native viewport and selection adapted from Codewhale TUI presentation.
1022 // Adapted from Codewhale, licensed under the MIT License:
1023 // Copyright (c) 2024-2025 DeepSeek-TUI Contributors
1024 //
1025 // Permission is hereby granted, free of charge, to any person obtaining a
1026 // copy of this software and associated documentation files (the "Software"),
1027 // to deal in the Software without restriction, including without limitation
1028 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
1029 // and/or sell copies of the Software, and to permit persons to whom the
1030 // Software is furnished to do so, subject to the following conditions:
1031 //
1032 // The above copyright notice and this permission notice shall be included
1033 // in all copies or substantial portions of the Software.
1034 //
1035 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1036 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1037 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1038 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1039 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1040 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
1041 // DEALINGS IN THE SOFTWARE.
1042
1043 /// Caller-owned scroll facts. This never changes a session's scroll state.
1044 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1045 pub struct TranscriptScrollFacts {
1046 pub top: usize,
1047 pub visible: usize,
1048 pub total: usize,
1049 }
1050
1051 /// Exact caller styles for the native transcript's independent chrome slots.
1052 #[derive(Clone, Copy, Debug, Default)]
1053 pub struct TranscriptViewportStyles {
1054 pub background: Style,
1055 pub track: Style,
1056 pub thumb: Style,
1057 pub jump_border: Style,
1058 pub jump_arrow: Style,
1059 }
1060
1061 /// One pure projection of already parsed/wrapped host rows. The parser, raw
1062 /// copy source, streaming/cache receipts, selection endpoints and scroll intent
1063 /// remain with the host. Targets never enter this type or its painted cells.
1064 /// Metadata must describe guarded, prewrapped display rows; `offset` counts
1065 /// logical rows after the pinned prefix. Optional wrapping is Ratatui-owned.
1066 #[derive(Clone, Debug)]
1067 pub struct TranscriptViewport<'a> {
1068 pub rows: &'a [Line<'static>],
1069 pub offset: usize,
1070 pub pinned_rows: u16,
1071 pub wrap: bool,
1072 pub fill: bool,
1073 pub ascii: bool,
1074 pub style: Style,
1075 pub styles: TranscriptViewportStyles,
1076 pub scrollbar: Option<TranscriptScrollFacts>,
1077 pub jump_to_latest: bool,
1078 }
1079
1080 /// Final clipped content/chrome rectangles and guarded styled rows.
1081 #[derive(Clone, Debug)]
1082 pub struct TranscriptViewportPlan {
1083 pub area: Rect,
1084 pub body_area: Rect,
1085 pub link_area: Rect,
1086 pub jump: Option<Rect>,
1087 rows: Vec<Line<'static>>,
1088 wrap: bool,
1089 fill: bool,
1090 ascii: bool,
1091 style: Style,
1092 styles: TranscriptViewportStyles,
1093 scrollbar: Option<TranscriptScrollFacts>,
1094 }
1095
1096 fn safe_transcript_line(line: &Line<'static>) -> Line<'static> {
1097 let mut safe = line.clone();
1098 safe.spans = line
1099 .spans
1100 .iter()
1101 .map(|span| Span::styled(text::display_safe(&span.content).into_owned(), span.style))
1102 .collect();
1103 safe
1104 }
1105
1106 impl<'a> TranscriptViewport<'a> {
1107 pub fn new(rows: &'a [Line<'static>]) -> Self {
1108 Self {
1109 rows,
1110 offset: 0,
1111 pinned_rows: 0,
1112 wrap: false,
1113 fill: false,
1114 ascii: false,
1115 style: Style::default(),
1116 styles: TranscriptViewportStyles::default(),
1117 scrollbar: None,
1118 jump_to_latest: false,
1119 }
1120 }
1121 pub fn plan(&self, area: Rect) -> TranscriptViewportPlan {
1122 let pinned = self.pinned_rows.min(area.height);
1123 let body_area = Rect::new(
1124 area.x,
1125 area.y.saturating_add(pinned),
1126 area.width,
1127 area.height.saturating_sub(pinned),
1128 );
1129 let scrollbar = self.scrollbar.filter(|facts| {
1130 facts.total > facts.visible && body_area.width > 1 && body_area.height > 0
1131 });
1132 let link_area = Rect::new(
1133 area.x,
1134 area.y,
1135 area.width.saturating_sub(u16::from(scrollbar.is_some())),
1136 area.height,
1137 );
1138 let prefix = usize::from(pinned).min(self.rows.len());
1139 let mut rows: Vec<_> = self.rows[..prefix]
1140 .iter()
1141 .map(safe_transcript_line)
1142 .collect();
1143 rows.extend(
1144 self.rows
1145 .iter()
1146 .skip(prefix.saturating_add(self.offset))
1147 .take(usize::from(body_area.height))
1148 .map(safe_transcript_line),
1149 );
1150 TranscriptViewportPlan {
1151 area,
1152 body_area,
1153 link_area,
1154 jump: self
1155 .jump_to_latest
1156 .then(|| transcript_jump_rect(body_area, scrollbar.is_some()))
1157 .flatten(),
1158 rows,
1159 wrap: self.wrap,
1160 fill: self.fill,
1161 ascii: self.ascii,
1162 style: self.style,
1163 styles: self.styles,
1164 scrollbar,
1165 }
1166 }
1167 /// Paint content first. A host's existing semantic Ocean finishing may run
1168 /// before `plan.paint_chrome`; it does not need another text compositor.
1169 pub fn render_content(&self, area: Rect, buf: &mut Buffer) -> TranscriptViewportPlan {
1170 let plan = self.plan(area.intersection(buf.area));
1171 plan.paint_content(buf);
1172 plan
1173 }
1174 pub fn render(&self, area: Rect, buf: &mut Buffer) -> TranscriptViewportPlan {
1175 let plan = self.render_content(area, buf);
1176 plan.paint_chrome(buf);
1177 plan
1178 }
1179 }
1180
1181 impl TranscriptViewportPlan {
1182 /// The exact display-safe, pinned/offset rows used by this plan's content
1183 /// painter. Hosts may derive frame-only semantic masks from these facts
1184 /// without repeating the viewport projection or touching raw copy source.
1185 #[must_use]
1186 pub fn display_rows(&self) -> &[Line<'static>] {
1187 &self.rows
1188 }
1189
1190 /// Visible hyperlink cells, excluding scroll chrome and the opaque jump button.
1191 /// Hosts retain the corresponding target outside these rectangles.
1192 pub fn link_rects(&self, row: usize, start: usize, end: usize) -> Vec<Rect> {
1193 let Some(rect) = transcript_link_rect(self.link_area, row, start, end) else {
1194 return Vec::new();
1195 };
1196 let Some(button) = self
1197 .jump
1198 .filter(|button| !rect.intersection(*button).is_empty())
1199 else {
1200 return vec![rect];
1201 };
1202 let mut visible = Vec::with_capacity(2);
1203 if rect.x < button.x {
1204 visible.push(Rect::new(rect.x, rect.y, button.x - rect.x, 1));
1205 }
1206 if rect.right() > button.right() {
1207 visible.push(Rect::new(
1208 button.right(),
1209 rect.y,
1210 rect.right() - button.right(),
1211 1,
1212 ));
1213 }
1214 visible
1215 }
1216 fn paint_content(&self, buf: &mut Buffer) {
1217 if self.area.is_empty() {
1218 return;
1219 }
1220 if self.fill {
1221 Block::default()
1222 .style(self.styles.background)
1223 .render(self.area, buf);
1224 }
1225 let mut paragraph = Paragraph::new(self.rows.clone()).style(self.style);
1226 if self.wrap {
1227 paragraph = paragraph.wrap(Wrap { trim: false });
1228 }
1229 paragraph.render(self.area, buf);
1230 }
1231 pub fn paint_chrome(&self, buf: &mut Buffer) {
1232 if self.area.intersection(buf.area).is_empty() {
1233 return;
1234 }
1235 if let Some(facts) = self.scrollbar
1236 && facts.total > facts.visible
1237 {
1238 let range = facts.total.saturating_sub(facts.visible);
1239 let mut state = ScrollbarState::new(range.saturating_add(1))
1240 .position(facts.top.min(range))
1241 .viewport_content_length(facts.visible);
1242 Scrollbar::new(ScrollbarOrientation::VerticalRight)
1243 .begin_symbol(None)
1244 .end_symbol(None)
1245 .track_symbol(Some(if self.ascii { "|" } else { "│" }))
1246 .track_style(self.styles.track)
1247 .thumb_symbol(if self.ascii { "|" } else { "┃" })
1248 .thumb_style(self.styles.thumb)
1249 .render(self.body_area.intersection(buf.area), buf, &mut state);
1250 }
1251 if let Some(area) = self.jump {
1252 let mut block = Block::default()
1253 .borders(Borders::ALL)
1254 .border_type(BorderType::Rounded)
1255 .border_style(self.styles.jump_border)
1256 .style(self.styles.background);
1257 if self.ascii {
1258 block = block.border_set(ratatui::symbols::border::Set {
1259 top_left: "+",
1260 top_right: "+",
1261 bottom_left: "+",
1262 bottom_right: "+",
1263 vertical_left: "|",
1264 vertical_right: "|",
1265 horizontal_top: "-",
1266 horizontal_bottom: "-",
1267 });
1268 }
1269 block.render(area.intersection(buf.area), buf);
1270 let arrow = (area.x.saturating_add(1), area.y.saturating_add(1));
1271 if buf.area.contains(arrow.into()) {
1272 buf[arrow]
1273 .set_symbol(if self.ascii { "v" } else { "↓" })
1274 .set_style(self.styles.jump_arrow.add_modifier(Modifier::BOLD));
1275 }
1276 }
1277 }
1278 }
1279 impl Paint for TranscriptViewport<'_> {
1280 fn paint(&self, area: Rect, buf: &mut Buffer, _theme: &Theme) {
1281 self.render(area, buf);
1282 }
1283 fn height(&self, width: u16, _theme: &Theme) -> u16 {
1284 if width == 0 {
1285 return 0;
1286 }
1287 let pinned = usize::from(self.pinned_rows).min(self.rows.len());
1288 if self.wrap {
1289 let rows: Vec<_> = self.rows[..pinned]
1290 .iter()
1291 .chain(self.rows.iter().skip(pinned.saturating_add(self.offset)))
1292 .map(safe_transcript_line)
1293 .collect();
1294 return u16::try_from(
1295 Paragraph::new(rows)
1296 .wrap(Wrap { trim: false })
1297 .line_count(width),
1298 )
1299 .unwrap_or(u16::MAX);
1300 }
1301 u16::try_from(
1302 pinned.saturating_add(
1303 self.rows
1304 .len()
1305 .saturating_sub(pinned.saturating_add(self.offset)),
1306 ),
1307 )
1308 .unwrap_or(u16::MAX)
1309 }
1310 }
1311
1312 /// Native three-cell jump affordance, never overlapping an owned scroll rail.
1313 /// The host decides whether it is appropriate and dispatches the click.
1314 pub fn transcript_jump_rect(area: Rect, scrollbar: bool) -> Option<Rect> {
1315 if area.width < 3 + u16::from(scrollbar) || area.height < 3 {
1316 return None;
1317 }
1318 Some(Rect::new(
1319 area.right()
1320 .saturating_sub(u16::from(scrollbar))
1321 .saturating_sub(3),
1322 area.bottom().saturating_sub(3),
1323 3,
1324 3,
1325 ))
1326 }
1327
1328 /// Project inclusive display-column metadata to a clipped terminal row. The
1329 /// opaque target and terminal/browser opening policy stay entirely with hosts.
1330 pub fn transcript_link_rect(area: Rect, row: usize, start: usize, end: usize) -> Option<Rect> {
1331 if area.is_empty()
1332 || row >= usize::from(area.height)
1333 || end < start
1334 || start >= usize::from(area.width)
1335 {
1336 return None;
1337 }
1338 let end = end.min(usize::from(area.width).saturating_sub(1));
1339 let x = area
1340 .x
1341 .saturating_add(u16::try_from(start).unwrap_or(u16::MAX));
1342 let y = area
1343 .y
1344 .saturating_add(u16::try_from(row).unwrap_or(u16::MAX));
1345 let rect = Rect::new(x, y, u16::try_from(end - start + 1).unwrap_or(u16::MAX), 1);
1346 let clipped = rect.intersection(area);
1347 (!clipped.is_empty()).then_some(clipped)
1348 }
1349
1350 /// Whole-grapheme selection projection, preserving every source span's style
1351 /// facts and applying the supplied selection style only to covered cells.
1352 pub fn transcript_selected_spans(
1353 line: &Line<'static>,
1354 start: usize,
1355 end: usize,
1356 selection: Style,
1357 ) -> Vec<Span<'static>> {
1358 transcript_selected_spans_measured(line, start, end, selection, text::width)
1359 }
1360
1361 /// The host may supply its existing terminal-column grammar (for example CJK
1362 /// ambiguous characters and non-VS keycaps) without another selection painter.
1363 pub fn transcript_selected_spans_measured(
1364 line: &Line<'static>,
1365 start: usize,
1366 end: usize,
1367 selection: Style,
1368 measure_grapheme: impl Fn(&str) -> usize,
1369 ) -> Vec<Span<'static>> {
1370 let mut result = Vec::with_capacity(line.spans.len().saturating_add(2));
1371 let mut column = 0usize;
1372 for span in &line.spans {
1373 let value = text::display_safe(&span.content);
1374 let span_end =
1375 column.saturating_add(value.graphemes(true).fold(0usize, |width, grapheme| {
1376 width.saturating_add(measure_grapheme(grapheme))
1377 }));
1378 if span_end <= start || column >= end {
1379 result.push(Span::styled(value.into_owned(), span.style));
1380 } else if column >= start && span_end <= end {
1381 result.push(Span::styled(
1382 value.into_owned(),
1383 span.style.patch(selection),
1384 ));
1385 } else {
1386 let (mut before, mut selected, mut after) =
1387 (String::new(), String::new(), String::new());
1388 let mut position = column;
1389 for grapheme in value.graphemes(true) {
1390 let next = position.saturating_add(measure_grapheme(grapheme));
1391 if next <= start {
1392 before.push_str(grapheme);
1393 } else if position >= end {
1394 after.push_str(grapheme);
1395 } else {
1396 selected.push_str(grapheme);
1397 }
1398 position = next;
1399 }
1400 for (text, style) in [
1401 (before, span.style),
1402 (selected, span.style.patch(selection)),
1403 (after, span.style),
1404 ] {
1405 if !text.is_empty() {
1406 result.push(Span::styled(text, style));
1407 }
1408 }
1409 }
1410 column = span_end;
1411 }
1412 result
1413 }
1414
1414 lines RUST