Skip to main content

markdown_ratatui/
layout.rs

1use crate::{MarkdownWidget, sanitize_terminal_text};
2use markdown_model::{
3    Alignment, Block, BlockKind, Document, HeadingId, Inline, InlineKind, LinkId, ListKind, Table,
4    TableCell, TableRow, TaskState, plain_text,
5};
6use ratatui_core::style::{Color, Modifier, Style};
7use std::{fmt, ops::Range};
8use unicode_segmentation::UnicodeSegmentation;
9use unicode_width::UnicodeWidthStr;
10
11/// Caller-provided styles used while preparing and rendering a layout.
12///
13/// Inline emphasis and selection are combined with these values using
14/// [`Style::patch`]. The crate never installs a global theme.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct Theme {
17    /// Ordinary text.
18    pub text: Style,
19    /// Heading text.
20    pub heading: Style,
21    /// Link labels.
22    pub link: Style,
23    /// Code and inline code.
24    pub code: Style,
25    /// Rendered Mermaid diagrams, independent of ordinary code blocks.
26    pub diagram: Style,
27    /// Quote/list prefixes and table separators.
28    pub muted: Style,
29    /// Applied to the selected link by the widget.
30    pub selected: Style,
31}
32impl Default for Theme {
33    fn default() -> Self {
34        Self {
35            text: Style::default(),
36            heading: Style::default()
37                .fg(Color::Cyan)
38                .add_modifier(Modifier::BOLD),
39            link: Style::default()
40                .fg(Color::Blue)
41                .add_modifier(Modifier::UNDERLINED),
42            code: Style::default().fg(Color::Yellow),
43            diagram: Style::default().fg(Color::Magenta),
44            muted: Style::default().fg(Color::DarkGray),
45            selected: Style::default().bg(Color::Blue).fg(Color::White),
46        }
47    }
48}
49/// Controls long code-line behavior during layout.
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
51pub enum CodePolicy {
52    /// Wrap long code lines at terminal cell boundaries.
53    #[default]
54    Wrap,
55    /// Clip long lines to the available width without horizontal scrolling.
56    Clip,
57}
58/// Controls table presentation during layout.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum TablePolicy {
61    /// Use aligned columns if they fit, otherwise stack labeled cells.
62    #[default]
63    Auto,
64    /// Always stack each row's labeled cells.
65    Stacked,
66}
67/// A validated maximum number of retained layout rows.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
69pub struct LineLimit(usize);
70impl LineLimit {
71    /// The largest supported retained-row budget.
72    pub const MAX: usize = 200_000;
73    /// The default retained-row budget.
74    pub const DEFAULT: Self = Self(100_000);
75
76    /// Creates a retained-row budget. Zero rejects every non-empty layout.
77    ///
78    /// # Errors
79    /// Returns [`LineLimitError`] when `lines` exceeds [`LineLimit::MAX`].
80    pub const fn new(lines: usize) -> Result<Self, LineLimitError> {
81        if lines <= Self::MAX {
82            Ok(Self(lines))
83        } else {
84            Err(LineLimitError { requested: lines })
85        }
86    }
87
88    /// Returns the maximum retained row count.
89    pub const fn get(self) -> usize {
90        self.0
91    }
92}
93impl Default for LineLimit {
94    fn default() -> Self {
95        Self::DEFAULT
96    }
97}
98impl fmt::Display for LineLimit {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        self.0.fmt(f)
101    }
102}
103/// An attempted line limit exceeded [`LineLimit::MAX`].
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub struct LineLimitError {
106    requested: usize,
107}
108impl LineLimitError {
109    /// Returns the rejected row count.
110    pub const fn requested(self) -> usize {
111        self.requested
112    }
113}
114impl fmt::Display for LineLimitError {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        write!(
117            f,
118            "line limit {} exceeds the maximum of {}",
119            self.requested,
120            LineLimit::MAX
121        )
122    }
123}
124impl std::error::Error for LineLimitError {}
125
126/// Appearance, wrapping, and resource policy for a [`Layout`].
127///
128/// [`crate::MarkdownView`] compares the complete value when deciding whether
129/// its single cached layout can be reused.
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub struct LayoutOptions {
132    /// Styles applied during layout and link selection.
133    pub theme: Theme,
134    /// Code line wrapping.
135    pub code: CodePolicy,
136    /// Table layout and narrow-width fallback.
137    pub tables: TablePolicy,
138    /// Maximum retained rows.
139    pub line_limit: LineLimit,
140}
141impl Default for LayoutOptions {
142    fn default() -> Self {
143        Self {
144            theme: Theme::default(),
145            code: CodePolicy::Wrap,
146            tables: TablePolicy::Auto,
147            line_limit: LineLimit::default(),
148        }
149    }
150}
151/// An error produced while preparing terminal rows.
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub enum LayoutError {
154    /// Prepared text would exceed the row budget.
155    TooManyLines {
156        /// Configured retained-row limit.
157        limit: LineLimit,
158    },
159}
160impl fmt::Display for LayoutError {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        match self {
163            Self::TooManyLines { limit } => write!(
164                f,
165                "layout exceeds {limit} lines; use a wider area or a smaller document"
166            ),
167        }
168    }
169}
170impl std::error::Error for LayoutError {}
171
172/// The terminal cells occupied by one styled run of a link.
173///
174/// Wrapping always produces multiple entries. A style change inside a link can
175/// also produce adjacent entries on the same row with the same ID.
176#[derive(Clone, Debug, PartialEq, Eq)]
177pub struct LinkPosition {
178    id: LinkId,
179    row: DocumentRow,
180    columns: CellRange,
181}
182impl LinkPosition {
183    /// Returns the identity from [`markdown_model::Document::links`].
184    pub const fn link_id(&self) -> LinkId {
185        self.id
186    }
187    /// Returns the zero-based document row before scrolling.
188    pub const fn row(&self) -> DocumentRow {
189        self.row
190    }
191    /// Returns the half-open terminal-cell columns within the row.
192    pub const fn columns(&self) -> CellRange {
193        self.columns
194    }
195}
196/// The document row at which a shared heading anchor starts.
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub struct HeadingPosition {
199    id: HeadingId,
200    row: DocumentRow,
201}
202impl HeadingPosition {
203    /// Returns the anchor ID from [`markdown_model::Document::headings`].
204    pub const fn heading_id(&self) -> &HeadingId {
205        &self.id
206    }
207    /// Returns the zero-based row before scrolling.
208    pub const fn row(&self) -> DocumentRow {
209        self.row
210    }
211}
212/// A zero-based row in a prepared Markdown document.
213#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
214pub struct DocumentRow(usize);
215impl DocumentRow {
216    /// Creates a document-relative row.
217    pub const fn new(index: usize) -> Self {
218        Self(index)
219    }
220    /// Returns the zero-based row index.
221    pub const fn index(self) -> usize {
222        self.0
223    }
224}
225/// A half-open range of terminal cells within one prepared row.
226#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
227pub struct CellRange {
228    start: u16,
229    end: u16,
230}
231impl CellRange {
232    fn new(start: u16, end: u16) -> Self {
233        debug_assert!(start <= end);
234        Self { start, end }
235    }
236    /// Returns the inclusive starting cell.
237    pub const fn start(self) -> u16 {
238        self.start
239    }
240    /// Returns the exclusive ending cell.
241    pub const fn end(self) -> u16 {
242        self.end
243    }
244    /// Returns the number of terminal cells in the range.
245    pub const fn len(self) -> u16 {
246        self.end - self.start
247    }
248    /// Returns whether the range contains no terminal cells.
249    pub const fn is_empty(self) -> bool {
250        self.start == self.end
251    }
252    /// Returns an ordinary cell range.
253    pub const fn range(self) -> Range<u16> {
254        self.start..self.end
255    }
256}
257#[derive(Clone, Debug)]
258pub(crate) struct Run {
259    pub text: String,
260    pub style: Style,
261    pub link: Option<LinkId>,
262}
263/// Prepared terminal rows and document-relative navigation positions.
264///
265/// A layout owns its rendered text and styles, so the source [`Document`] and
266/// [`LayoutOptions`] can be dropped after construction. Rendering never wraps or
267/// reparses it. Prepare a new layout when the content-area width changes.
268#[derive(Clone, Debug)]
269pub struct Layout {
270    width: u16,
271    pub(crate) lines: Vec<Vec<Run>>,
272    links: Vec<LinkPosition>,
273    headings: Vec<HeadingPosition>,
274    pub(crate) selected: Style,
275}
276impl Layout {
277    /// Lays out a parsed document synchronously for `width` terminal cells.
278    ///
279    /// Unicode grapheme clusters are measured by display width. Width zero
280    /// produces an empty layout. A grapheme wider than the available content
281    /// width becomes `�`; a wide grapheme is never split across cells.
282    ///
283    /// # Errors
284    /// Returns [`LayoutError::TooManyLines`] before retaining more than the
285    /// configured [`LayoutOptions::line_limit`] budget.
286    pub fn new(
287        document: &Document,
288        width: u16,
289        options: &LayoutOptions,
290    ) -> Result<Self, LayoutError> {
291        let mut builder = Builder {
292            layout: Self {
293                width,
294                lines: Vec::new(),
295                links: Vec::new(),
296                headings: Vec::new(),
297                selected: options.theme.selected,
298            },
299            options,
300        };
301        if width != 0 {
302            builder.blocks(document.blocks(), "")?;
303        }
304        let mut links = Vec::new();
305        for (row, runs) in builder.layout.lines.iter().enumerate() {
306            let mut column = 0;
307            for run in runs {
308                let end = column + UnicodeWidthStr::width(run.text.as_str()) as u16;
309                if let Some(id) = run.link {
310                    links.push(LinkPosition {
311                        id,
312                        row: DocumentRow::new(row),
313                        columns: CellRange::new(column, end),
314                    });
315                }
316                column = end;
317            }
318        }
319        builder.layout.links = links;
320        Ok(builder.layout)
321    }
322    /// Width in terminal cells for which this layout was prepared.
323    pub fn width(&self) -> u16 {
324        self.width
325    }
326    /// Total row count after wrapping, including block spacing.
327    pub fn line_count(&self) -> usize {
328        self.lines.len()
329    }
330    /// Returns document-relative link cells after wrapping.
331    ///
332    /// Positions use the IDs assigned by [`markdown_model::Document::links`].
333    /// Widget offsets and scroll state are not included.
334    pub fn links(&self) -> &[LinkPosition] {
335        &self.links
336    }
337    /// Returns heading anchors and their document-relative rows.
338    pub fn headings(&self) -> &[HeadingPosition] {
339        &self.headings
340    }
341    /// Allocates the plain text of every prepared row.
342    ///
343    /// This is useful for tests, export, and accessibility adapters. Render
344    /// [`Layout::widget`] when styles are needed or the allocation is unwanted.
345    pub fn plain_lines(&self) -> Vec<String> {
346        self.lines
347            .iter()
348            .map(|line| line.iter().map(|run| run.text.as_str()).collect())
349            .collect()
350    }
351    /// Borrows this layout as a [`MarkdownWidget`].
352    pub fn widget(&self) -> MarkdownWidget<'_> {
353        MarkdownWidget { layout: self }
354    }
355}
356struct Builder<'a> {
357    layout: Layout,
358    options: &'a LayoutOptions,
359}
360fn run(text: impl Into<String>, style: Style) -> Run {
361    Run {
362        text: text.into(),
363        style,
364        link: None,
365    }
366}
367fn push_run(line: &mut Vec<Run>, value: Run) {
368    if let Some(last) = line.last_mut()
369        && last.style == value.style
370        && last.link == value.link
371    {
372        last.text.push_str(&value.text);
373        return;
374    }
375    line.push(value);
376}
377impl Builder<'_> {
378    fn push(&mut self, line: Vec<Run>) -> Result<(), LayoutError> {
379        let limit = self.options.line_limit;
380        if self.layout.lines.len() >= limit.get() {
381            return Err(LayoutError::TooManyLines { limit });
382        }
383        self.layout.lines.push(line);
384        Ok(())
385    }
386    fn text(
387        &mut self,
388        runs: Vec<Run>,
389        first: &str,
390        continuation: &str,
391        clip: bool,
392    ) -> Result<(), LayoutError> {
393        let width = usize::from(self.layout.width);
394        let prefix = |p: &str| -> String {
395            let mut out = String::new();
396            for g in p.graphemes(true) {
397                if out.width() + g.width() > width.saturating_sub(1) {
398                    break;
399                }
400                out.push_str(g);
401            }
402            out
403        };
404        let first = prefix(first);
405        let continuation = prefix(continuation);
406        let mut line = vec![run(first.clone(), self.options.theme.muted)];
407        let mut used = first.width();
408        let mut skipped = false;
409        for segment in runs {
410            let text = sanitize_terminal_text(&segment.text);
411            for word in text.split_word_bounds() {
412                let word_width = word.width();
413                if !clip
414                    && !word.contains('\n')
415                    && word_width <= width.saturating_sub(continuation.width())
416                    && used > first.width()
417                    && used + word_width > width
418                {
419                    self.push(std::mem::take(&mut line))?;
420                    line.push(run(continuation.clone(), self.options.theme.muted));
421                    used = continuation.width();
422                }
423                for g in word.graphemes(true) {
424                    if g == "\n" {
425                        self.push(std::mem::take(&mut line))?;
426                        line.push(run(continuation.clone(), self.options.theme.muted));
427                        used = continuation.width();
428                        skipped = false;
429                        continue;
430                    }
431                    if skipped {
432                        continue;
433                    }
434                    let mut g = g;
435                    let mut cells = g.width();
436                    let available = width.saturating_sub(continuation.width());
437                    if cells > available {
438                        g = "�";
439                        cells = 1;
440                    }
441                    if used + cells > width {
442                        if clip {
443                            skipped = true;
444                            continue;
445                        }
446                        self.push(std::mem::take(&mut line))?;
447                        line.push(run(continuation.clone(), self.options.theme.muted));
448                        used = continuation.width();
449                    }
450                    push_run(
451                        &mut line,
452                        Run {
453                            text: g.to_owned(),
454                            style: segment.style,
455                            link: segment.link,
456                        },
457                    );
458                    used += cells;
459                }
460            }
461        }
462        self.push(line)
463    }
464    fn blocks(&mut self, blocks: &[Block], prefix: &str) -> Result<(), LayoutError> {
465        let theme = &self.options.theme;
466        for block in blocks {
467            match block.kind() {
468                BlockKind::Paragraph(content) => self.text(
469                    inlines(content, theme.text, theme, None),
470                    prefix,
471                    prefix,
472                    false,
473                )?,
474                BlockKind::Heading { id, content, .. } => {
475                    self.layout.headings.push(HeadingPosition {
476                        id: id.clone(),
477                        row: DocumentRow::new(self.layout.lines.len()),
478                    });
479                    self.text(
480                        inlines(content, theme.heading, theme, None),
481                        prefix,
482                        prefix,
483                        false,
484                    )?;
485                }
486                BlockKind::Quote(children) => self.blocks(children, &format!("{prefix}│ "))?,
487                BlockKind::List { kind, items } => {
488                    for (index, item) in items.iter().enumerate() {
489                        let marker = match item.task() {
490                            TaskState::Checked => "[x] ".to_owned(),
491                            TaskState::Unchecked => "[ ] ".to_owned(),
492                            TaskState::Plain => match kind {
493                                ListKind::Unordered => "• ".to_owned(),
494                                ListKind::Ordered { start } => {
495                                    format!("{}. ", start.saturating_add(index as u64))
496                                }
497                            },
498                        };
499                        let first = format!("{prefix}{marker}");
500                        let rest = format!("{prefix}{}", " ".repeat(marker.width()));
501                        if let Some((head, tail)) = item.blocks().split_first() {
502                            if let BlockKind::Paragraph(content) = head.kind() {
503                                self.text(
504                                    inlines(content, theme.text, theme, None),
505                                    &first,
506                                    &rest,
507                                    false,
508                                )?;
509                                self.blocks(tail, &rest)?;
510                            } else {
511                                self.text(Vec::new(), &first, &rest, false)?;
512                                self.blocks(item.blocks(), &rest)?;
513                            }
514                        } else {
515                            self.text(Vec::new(), &first, &rest, false)?;
516                        }
517                    }
518                }
519                BlockKind::Code { kind, text } => {
520                    let info = kind.info().unwrap_or_default();
521                    if info.split_whitespace().next() == Some("mermaid") {
522                        let width = usize::from(self.layout.width).saturating_sub(prefix.width());
523                        match crate::mermaid::render(text, width) {
524                            Ok(lines) => {
525                                for line in lines {
526                                    self.text(
527                                        vec![run(line, theme.diagram)],
528                                        prefix,
529                                        prefix,
530                                        true,
531                                    )?;
532                                }
533                                self.push(Vec::new())?;
534                                continue;
535                            }
536                            Err(reason) => self.text(
537                                vec![run(format!("Mermaid source ({reason})"), theme.muted)],
538                                prefix,
539                                prefix,
540                                false,
541                            )?,
542                        }
543                    }
544                    self.text(
545                        vec![run(
546                            format!("┌ {}", sanitize_terminal_text(info)),
547                            theme.muted,
548                        )],
549                        prefix,
550                        prefix,
551                        false,
552                    )?;
553                    for line in text.lines() {
554                        self.text(
555                            vec![run(line, theme.code)],
556                            &format!("{prefix}│ "),
557                            &format!("{prefix}│ "),
558                            self.options.code == CodePolicy::Clip,
559                        )?;
560                    }
561                    self.text(vec![run("└", theme.muted)], prefix, prefix, false)?;
562                }
563                BlockKind::Literal(text) => {
564                    self.text(vec![run(text, theme.text)], prefix, prefix, false)?
565                }
566                BlockKind::Rule => self.text(
567                    vec![run(
568                        "─".repeat(usize::from(self.layout.width).saturating_sub(prefix.width())),
569                        theme.muted,
570                    )],
571                    prefix,
572                    prefix,
573                    false,
574                )?,
575                BlockKind::Table(table) => self.table(table, prefix)?,
576            }
577            self.push(Vec::new())?;
578        }
579        Ok(())
580    }
581    fn table(&mut self, table: &Table, prefix: &str) -> Result<(), LayoutError> {
582        let theme = &self.options.theme;
583        let header = table.header().cells();
584        let rows = table.rows();
585        let align = table.alignments();
586        let mut widths: Vec<usize> = header
587            .iter()
588            .map(|c| {
589                sanitize_terminal_text(&plain_text(c.inlines()))
590                    .width()
591                    .max(1)
592            })
593            .collect();
594        for row in rows {
595            for (i, cell) in row.cells().iter().enumerate() {
596                if let Some(w) = widths.get_mut(i) {
597                    *w = (*w).max(sanitize_terminal_text(&plain_text(cell.inlines())).width());
598                }
599            }
600        }
601        let total =
602            widths.iter().sum::<usize>() + widths.len().saturating_sub(1) * 3 + prefix.width();
603        if total > usize::from(self.layout.width) || self.options.tables == TablePolicy::Stacked {
604            // Keep headers even in an empty table.
605            self.text(
606                inlines_join(header, theme.heading, theme),
607                prefix,
608                prefix,
609                false,
610            )?;
611            for row in rows {
612                for (i, cell) in row.cells().iter().enumerate() {
613                    let label = header
614                        .get(i)
615                        .map_or_else(|| format!("Column {}", i + 1), |c| plain_text(c.inlines()));
616                    let mut runs = vec![run(format!("{label}: "), theme.heading)];
617                    runs.extend(inlines(cell.inlines(), theme.text, theme, None));
618                    self.text(runs, prefix, prefix, false)?;
619                }
620                self.push(Vec::new())?;
621            }
622        } else {
623            for (index, row) in std::iter::once(header)
624                .chain(rows.iter().map(TableRow::cells))
625                .enumerate()
626            {
627                let mut runs = Vec::new();
628                for (i, cell) in row.iter().enumerate() {
629                    if i > 0 {
630                        runs.push(run(" │ ", theme.muted));
631                    }
632                    let content = inlines(
633                        cell.inlines(),
634                        if index == 0 {
635                            theme.heading
636                        } else {
637                            theme.text
638                        },
639                        theme,
640                        None,
641                    );
642                    let size: usize = content
643                        .iter()
644                        .map(|run| sanitize_terminal_text(&run.text).width())
645                        .sum();
646                    let pad = widths.get(i).copied().unwrap_or(size).saturating_sub(size);
647                    let left = match align.get(i).unwrap_or(&Alignment::None) {
648                        Alignment::Right => pad,
649                        Alignment::Center => pad / 2,
650                        _ => 0,
651                    };
652                    runs.push(run(" ".repeat(left), theme.text));
653                    runs.extend(content);
654                    runs.push(run(" ".repeat(pad - left), theme.text));
655                }
656                self.text(runs, prefix, prefix, false)?;
657                if index == 0 {
658                    self.text(
659                        vec![run(
660                            widths
661                                .iter()
662                                .map(|w| "─".repeat(*w))
663                                .collect::<Vec<_>>()
664                                .join("─┼─"),
665                            theme.muted,
666                        )],
667                        prefix,
668                        prefix,
669                        false,
670                    )?;
671                }
672            }
673        }
674        Ok(())
675    }
676}
677fn inlines_join(cells: &[TableCell], style: Style, theme: &Theme) -> Vec<Run> {
678    let mut runs = Vec::new();
679    for (i, cell) in cells.iter().enumerate() {
680        if i > 0 {
681            runs.push(run(" / ", theme.muted));
682        }
683        runs.extend(inlines(cell.inlines(), style, theme, None));
684    }
685    runs
686}
687fn inlines(content: &[Inline], style: Style, theme: &Theme, link: Option<LinkId>) -> Vec<Run> {
688    let mut out = Vec::new();
689    for inline in content {
690        let (text, style) = match inline.kind() {
691            InlineKind::Text(s) => (s.clone(), style),
692            InlineKind::Code(s) => (s.clone(), style.patch(theme.code)),
693            InlineKind::SoftBreak => (" ".to_owned(), style),
694            InlineKind::HardBreak => ("\n".to_owned(), style),
695            InlineKind::Emphasis(c) => {
696                out.extend(inlines(
697                    c,
698                    style.add_modifier(Modifier::ITALIC),
699                    theme,
700                    link,
701                ));
702                continue;
703            }
704            InlineKind::Strong(c) => {
705                out.extend(inlines(c, style.add_modifier(Modifier::BOLD), theme, link));
706                continue;
707            }
708            InlineKind::Strikethrough(c) => {
709                out.extend(inlines(
710                    c,
711                    style.add_modifier(Modifier::CROSSED_OUT),
712                    theme,
713                    link,
714                ));
715                continue;
716            }
717            InlineKind::Link { id, content } => {
718                let children = if content.is_empty() {
719                    vec![run("[link]", theme.link)]
720                } else {
721                    inlines(content, style.patch(theme.link), theme, Some(*id))
722                };
723                out.extend(children.into_iter().map(|mut r| {
724                    r.link = Some(*id);
725                    r
726                }));
727                continue;
728            }
729            InlineKind::Image { alt, .. } => (
730                format!("[image: {}]", plain_text(alt)),
731                style.patch(theme.muted),
732            ),
733        };
734        out.push(Run { text, style, link });
735    }
736    out
737}