Expand description
§markdown-ratatui
markdown-ratatui renders Markdown inside any caller-owned ratatui area. It
accepts source text or a shared parsed markdown-model document, performs
Unicode display-width-aware layout, exposes typed heading and link positions,
and provides a StatefulWidget with caller-owned scroll and selection state.
The crate is a widget library, not a terminal application. It does not enable raw mode, enter an alternate screen, read input, choose keys, open links, access files or networks, start an async runtime, or terminate a process.
§Status and installation
The API is version 0.2 and follows Cargo SemVer conventions. Types re-exported
from markdown-model and types from ratatui-core are intentional parts of
the public contract.
Within this repository:
[dependencies]
markdown-ratatui = { path = "crates/markdown-ratatui" }After a crates.io release:
[dependencies]
markdown-ratatui = "0.2"No crates.io release is implied by this documentation; release preparation
must verify registry availability and ownership. The minimum supported Rust
version is 1.88. The crate has no Cargo features. Its normal dependency graph
uses ratatui-core, not a terminal backend or the complete ratatui
application crate.
§Render Markdown from memory
MarkdownView combines one shared document with one bounded layout cache.
MarkdownView::new parses source text once; MarkdownView::prepare lays
it out for a terminal width and reuses the result until the document, width, or
options change.
use markdown_ratatui::{MarkdownView, ViewState};
use ratatui_core::{
buffer::Buffer,
layout::Rect,
widgets::StatefulWidget,
};
let mut markdown = MarkdownView::new("# Hello\n\n[Next](next.md)")?;
let area = Rect::new(2, 1, 30, 8);
let mut buffer = Buffer::empty(Rect::new(0, 0, 40, 10));
let mut state = ViewState::default();
let layout = markdown.prepare(area.width)?;
layout.widget().render(area, &mut buffer, &mut state);
assert_eq!(layout.width(), 30);
assert_eq!(layout.headings()[0].heading_id().as_str(), "hello");Parsing and preparation are separate error boundaries:
MarkdownView::new returns ParseError, while preparation returns
LayoutError. Both operations are synchronous and perform no I/O.
§Render an LSP hover or tooltip
Short-lived Markdown supplied by a language server needs no repository or Mira application state. A host such as ChronoGit can retain one view and one state inside its hover overlay:
use markdown_ratatui::{MarkdownView, ViewState};
use ratatui_core::{
buffer::Buffer,
layout::Rect,
widgets::StatefulWidget,
};
let hover_markdown = "`Action` runs the selected **operation**.";
let mut hover = MarkdownView::new(hover_markdown)?;
let mut hover_state = ViewState::default();
let popup = Rect::new(4, 2, 48, 10);
let mut buffer = Buffer::empty(Rect::new(0, 0, 60, 16));
hover
.prepare(popup.width)?
.widget()
.render(popup, &mut buffer, &mut hover_state);
hover_state.scroll_forward(1); // The host owns the key binding.Replacing hover content with MarkdownView::set_document invalidates only
the cached layout. Resetting or retaining ViewState is an application
decision.
§Reuse a parsed document
markdown-ratatui re-exports Document and the navigation identity types,
so a consumer needs only one direct dependency for ordinary embedding:
use std::sync::Arc;
use markdown_ratatui::{Document, MarkdownView};
let document = Arc::new(Document::parse("# Shared\n\nA cached document.")?);
let mut first = MarkdownView::from_document(document.clone());
let mut second = MarkdownView::from_document(document);
assert_eq!(first.prepare(40)?.headings()[0].heading_id().as_str(), "shared");
assert_eq!(second.prepare(80)?.headings()[0].heading_id().as_str(), "shared");MarkdownView::document borrows the document. Use
MarkdownView::shared_document only when the caller needs the exact Arc.
Supplying an already parsed document never reparses it.
§Caller-owned navigation state
ViewState keeps its fields private and exposes intention-revealing methods.
The host decides which keys scroll, select links, and activate destinations:
use markdown_ratatui::{MarkdownView, ViewState};
let mut markdown = MarkdownView::new("[one](one.md) and [two](two.md)")?;
let mut state = ViewState::default();
let first_link = markdown.document().links()[0].id();
state.scroll_forward(1);
state.select_link(Some(first_link));
let layout = markdown.prepare(20)?;
if let Some(position) = layout
.links()
.iter()
.find(|position| position.link_id() == first_link)
{
state.reveal(position.row(), 8);
}
state.clamp(layout, 8);
assert_eq!(markdown.document().link(first_link)
.expect("the ID came from this document")
.destination().as_str(), "one.md");Selection changes style only. The widget never emits OSC 8 links or opens a browser. Destination classification, filesystem containment, and explicit user intent belong to the host application.
§Width, positions, and policy
Call MarkdownView::prepare with the width of the exact area passed to the
widget. The widget clips if rendered into a narrower area; it does not rewrap.
Width zero produces an empty layout. A grapheme that cannot fit is replaced by
� rather than split across terminal cells.
Layout::links uses LinkPosition values containing a typed LinkId,
DocumentRow, and CellRange. Wrapping or an inline style boundary can
produce several positions for one link. Layout::headings uses the same
HeadingId generated by markdown-model, allowing HTML and terminal views
to share anchor identities.
LayoutOptions contains a Theme, CodePolicy, TablePolicy, and a
validated LineLimit. LineLimit::new(0) intentionally rejects non-empty
layouts; values above LineLimit::MAX are rejected during construction.
use markdown_ratatui::{
CodePolicy, LayoutOptions, LineLimit, MarkdownView, TablePolicy, Theme,
};
use ratatui_core::style::{Color, Style};
let mut markdown = MarkdownView::new("```text\na very long line\n```")?;
markdown.set_options(LayoutOptions {
theme: Theme {
heading: Style::default().fg(Color::Magenta),
diagram: Style::default().fg(Color::Green),
..Theme::default()
},
code: CodePolicy::Clip,
tables: TablePolicy::Stacked,
line_limit: LineLimit::new(10_000)?,
});
assert_eq!(markdown.prepare(20)?.width(), 20);sanitize_terminal_text removes control characters, preserves line feeds,
and expands tabs. Layout applies it automatically to model text; hosts can use
it for untrusted titles and status strings rendered outside the widget.
§Mermaid fences
The private mermaid module converts fenced mermaid blocks during layout,
so diagrams share the normal width cache, quote/list indentation, and row
budget. It supports flowcharts (graph / flowchart), sequence diagrams, and
flat state diagrams. Flowcharts and states render one ASCII connection strip
per edge, using repeated node IDs to retain branches and cycles. Node shapes
normalize to boxes. Sequence diagrams use participant lifelines or message
strips when narrow; notes and activation changes remain ordered annotations.
alt / multiple else / end, opt, and loop blocks retain their conditions,
order, and nesting in ASCII frames. Nested frames reserve fixed gutters so
participant lifelines stay aligned across branches.
Labels wrap by grapheme display width; Mermaid colors are ignored.
Theme::diagram
styles diagram labels and lines independently of Theme::code. Its default
is magenta; ordinary code remains yellow. Changing the diagram style invalidates
the cached layout like any other theme change. When upgrading from 0.1 to 0.2,
callers constructing every Theme field explicitly must include diagram,
or use ..Theme::default().
Other diagram types and unsupported syntax (such as subgraphs, nested states,
or other sequence control blocks) retain their source with an explanation, as
do malformed diagrams and areas with fewer than eight cells after indentation
and frame gutters. Missing or unmatched end and else outside alt reject
the entire diagram. Conversion accepts at most 64 KiB of source, 128 nodes,
512 connections, 16 nested sequence blocks, and 256 KiB of expanded labels
before falling back to source. The normal LineLimit still applies to both
diagrams and fallback text. No extra crate, terminal backend, JavaScript
runtime, or I/O is required.
§Complete example
The repository includes a complete host that owns its terminal, panels, event loop, keys, layout, and state:
cargo run -p markdown-ratatui --example embedded -- --bufferThe interactive form is cargo run -p markdown-ratatui --example embedded.
§License
Licensed under either the Apache License, Version 2.0 or the MIT license at your option.
Structs§
- Cell
Range - A half-open range of terminal cells within one prepared row.
- Document
- An owned, immutable Markdown document and its navigation indexes.
- Document
Row - A zero-based row in a prepared Markdown document.
- Heading
Id - A unique document-local heading anchor generated by the parser.
- Heading
Position - The document row at which a shared heading anchor starts.
- Layout
- Prepared terminal rows and document-relative navigation positions.
- Layout
Options - Appearance, wrapping, and resource policy for a
Layout. - Line
Limit - A validated maximum number of retained layout rows.
- Line
Limit Error - An attempted line limit exceeded
LineLimit::MAX. - LinkId
- A contiguous document-local link identifier.
- Link
Position - The terminal cells occupied by one styled run of a link.
- Markdown
View - A parsed document with a single width-dependent layout cache.
- Markdown
Widget - A borrowed, already-wrapped Markdown widget.
- Theme
- Caller-provided styles used while preparing and rendering a layout.
- View
State - Caller-owned scrolling and link-selection state.
Enums§
- Code
Policy - Controls long code-line behavior during layout.
- Layout
Error - An error produced while preparing terminal rows.
- Parse
Error - Resource exhaustion, rather than incomplete Markdown syntax, makes parsing fail.
- Table
Policy - Controls table presentation during layout.
Functions§
- sanitize_
terminal_ text - Returns text with terminal control characters removed.