Skip to main content

markdown_ratatui/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3
4mod layout;
5mod mermaid;
6mod text;
7mod widget;
8
9pub use layout::{
10    CellRange, CodePolicy, DocumentRow, HeadingPosition, Layout, LayoutError, LayoutOptions,
11    LineLimit, LineLimitError, LinkPosition, TablePolicy, Theme,
12};
13pub use markdown_model::{Document, HeadingId, LinkId, ParseError};
14use std::sync::Arc;
15pub use text::sanitize_terminal_text;
16pub use widget::{MarkdownWidget, ViewState};
17
18/// A parsed document with a single width-dependent layout cache.
19///
20/// Construction parses at most once. [`MarkdownView::prepare`] retains one
21/// layout; changing the document, width, or options invalidates it. Scrolling
22/// and link selection live in [`ViewState`] and never parse or lay out content.
23#[derive(Debug)]
24pub struct MarkdownView {
25    document: Arc<Document>,
26    options: LayoutOptions,
27    cached: Option<Layout>,
28}
29impl MarkdownView {
30    /// Parses an in-memory string with [`markdown_model::ParseLimits::default`].
31    ///
32    /// The resulting document owns its content. This method is synchronous and
33    /// performs no I/O.
34    ///
35    /// # Errors
36    /// Returns [`ParseError`] if the source exceeds a parser resource limit.
37    /// Layout errors cannot occur until [`MarkdownView::prepare`] is called.
38    pub fn new(source: &str) -> Result<Self, ParseError> {
39        Ok(Self::from_document(Arc::new(Document::parse(source)?)))
40    }
41    /// Uses an existing shared document without parsing or I/O.
42    pub fn from_document(document: Arc<Document>) -> Self {
43        Self {
44            document,
45            options: LayoutOptions::default(),
46            cached: None,
47        }
48    }
49    /// Returns the document from which headings and links originate.
50    pub fn document(&self) -> &Document {
51        &self.document
52    }
53    /// Returns the exact shared document retained by this view.
54    pub const fn shared_document(&self) -> &Arc<Document> {
55        &self.document
56    }
57    /// Returns the current appearance and wrapping policy.
58    pub const fn options(&self) -> &LayoutOptions {
59        &self.options
60    }
61    /// Replaces the document and unconditionally discards the cached layout.
62    pub fn set_document(&mut self, document: Arc<Document>) {
63        self.document = document;
64        self.cached = None;
65    }
66    /// Replaces appearance and wrapping policy.
67    ///
68    /// A value equal to the current options preserves the cached layout;
69    /// different options discard it.
70    pub fn set_options(&mut self, options: LayoutOptions) {
71        if self.options != options {
72            self.options = options;
73            self.cached = None;
74        }
75    }
76    /// Prepares or reuses the cached layout for `width` terminal cells.
77    ///
78    /// Repeated calls with the same document, options, and width return the
79    /// same retained layout. A different width replaces the previous entry.
80    ///
81    /// # Errors
82    /// Returns [`LayoutError::TooManyLines`] if preparation would exceed the
83    /// configured line budget.
84    pub fn prepare(&mut self, width: u16) -> Result<&Layout, LayoutError> {
85        if self
86            .cached
87            .as_ref()
88            .is_none_or(|layout| layout.width() != width)
89        {
90            self.cached = Some(Layout::new(&self.document, width, &self.options)?);
91        }
92        Ok(self.cached.as_ref().expect("layout was prepared above"))
93    }
94}