Repository navigation
Architecture
mdink processes markdown through a strict one-way pipeline. Each stage is a pure function of the previous stage's output — no stage imports from a later stage.
&str (markdown source)
│
▼
parser::parse()
│ Input: &str + &Highlighter + &mut ImageManager + &MarkdownTheme
│ Output: Vec<RenderedBlock> (semantic IR)
│
▼
layout::flatten()
│ Input: &[RenderedBlock] + terminal_width + &MarkdownTheme
│ Output: PreRenderedDocument (layout-resolved lines)
│
▼
renderer::draw()
Input: &App (holds PreRenderedDocument + scroll state + theme)
Output: writes to ratatui Frame (pixels)
blocks (the Vec<RenderedBlock>) is kept alive in main.rs. On terminal resize, only layout::flatten() is re-called — parsing is not repeated.
| Module | Input | Output | Key type |
|---|---|---|---|
parser.rs |
&str + &Highlighter + &mut ImageManager + &MarkdownTheme
|
semantic blocks | RenderedBlock |
highlight.rs |
&str (code) + language + syntect theme |
colored spans | Vec<Line<'static>> |
layout.rs |
&[RenderedBlock] + width |
display-ready lines | PreRenderedDocument |
renderer.rs |
&App |
writes to frame | — |
app.rs |
keyboard events | scroll state mutation | App |
theme.rs |
JSON file or built-in | MarkdownTheme |
MarkdownTheme |
config.rs |
~/.config/mdink/config.json |
Config |
Config |
images.rs |
image URL + base path | protocol-encoded image | ImageManager |
cli.rs |
argv |
parsed args | Cli |
main.rs |
all of the above | wires the pipeline | — |
highlight.rs is a leaf module: it never imports from any other mdink module. syntect types must not leak into parser.rs, layout.rs, or renderer.rs. This keeps the highlighting dependency contained so it can be swapped or upgraded without touching the rest of the pipeline.
pub enum RenderedBlock {
Heading { level: u8, content: Vec<StyledSpan> },
Paragraph { content: Vec<StyledSpan> },
CodeBlock { language: String, highlighted_lines: Vec<Line<'static>> },
BlockQuote { content: Vec<StyledSpan> },
List { items: Vec<ListItem>, ordered: bool, start: u64 },
Table { headers: Vec<Vec<StyledSpan>>, rows: Vec<Vec<Vec<StyledSpan>>>, alignments: Vec<Alignment> },
ThematicBreak,
Spacer { lines: u16 },
}StyledSpan carries text: String + style: Style (both owned, no lifetime parameters). This makes Vec<RenderedBlock> 'static and safe to store in main.rs for the lifetime of the session.
Adding a new variant requires changes in exactly four files:
-
parser.rs— add a match arm for the new pulldown-cmark event(s) that produce this block -
layout.rs— add a match arm to flatten the new block into display lines -
renderer.rs— add a match arm to draw the new block variant -
theme.rs(if it needs styling) — add a new style struct and conversion helper
No other files need changing.
layout.rs cannot use ratatui's built-in text wrapping because ratatui has no way to propagate per-character styles across line breaks. Instead, layout.rs implements a byte-indexed style map:
- Build a plain
Stringby concatenating all span texts. - Build a parallel
Vec<Style>indexed by byte offset into that string. - Call
textwrap::wrap()on the plain string to get wrapped lines. - Walk each wrapped line with a byte cursor; look up each character's style from the byte map; reconstruct
Spans with the correct style.
Hard breaks (\n embedded in a StyledSpan.text) are handled by splitting the span at the newline and processing each half independently before merging the results.
Width is clamped to ≥ 1 before calling textwrap; textwrap has undefined behavior at width 0.
GFM tables go through a multi-stage layout pipeline inside layout.rs:
- Measure the natural width of every cell (unwrapped text length or image width).
- Sum natural widths. If total fits within the terminal, use natural widths directly.
- If total exceeds available space, shrink columns proportionally — wider columns give up more space, with a minimum of 3 characters per column.
flatten_cell_to_lines() converts each TableCell into a Vec<Vec<Span>> (multiple lines of styled spans):
-
Text cells are word-wrapped to the computed column width using the same
wrap_styled_spans()function that paragraphs use. Inline styles (bold, italic, code) are preserved across line breaks. Each wrapped line is then padded tocol_widthwith alignment-aware spacing (left, center, or right). - Image cells are rendered as protocol-encoded image spans or ASCII art, potentially spanning multiple lines.
- Empty cells produce a single line of blank padding.
build_multi_line_row() takes the flattened cell lines for a row and equalizes their heights — shorter cells are padded with blank lines to match the tallest cell. This produces the final DocumentLine::Text entries with column separators (│).
When adjacent rows contain multi-line content, a blank separator row (matching the column structure) is inserted between them for readability. Single-line rows do not get separators, so simple tables remain compact.
| Invariant | Location | Details |
|---|---|---|
| File size guard | main.rs |
Rejects files > 100 MB before terminal init. Exit code 65. |
| Highlight size guard | highlight.rs |
Rejects code blocks > 512 KB. Oniguruma (syntect's regex engine) can OOM on large inputs. Returns plain text fallback. |
| Width clamp | layout.rs |
Clamps terminal width to ≥ 1 before calling textwrap. |
| Style stack | parser.rs |
Pushes a Style for each inline format open tag; pops on the matching close tag. All pop sites have debug_assert!(!style_stack.is_empty()). |
TERMINAL_ACTIVE flag |
main.rs |
Set to true immediately after ratatui::init(). The panic hook only calls ratatui::restore() if this flag is true — prevents spurious escape sequences on clean exit or pre-init panics. |
| Leaf module | highlight.rs |
Never imports from other mdink modules. syntect types cannot leak. |
On Event::Resize(cols, _rows):
-
layout::flatten(&blocks, cols, &app.theme)is called again with the new width. - The result replaces
app.document. -
app.scroll_offsetis clamped to the newmax_scroll().
Layout is stateless and idempotent — calling it multiple times with the same arguments produces the same output. blocks (the parsed IR) is kept alive in main.rs precisely for this purpose.
Cli::parse() -- read argv
config::load_config() -- read ~/.config/mdink/config.json
theme::load_theme() -- load theme JSON (or built-in)
crossterm::terminal::size() -- get initial column width
enable_raw_mode() briefly -- query graphics protocol support
disable_raw_mode() -- restore before ratatui takes over
parser::parse() -- build Vec<RenderedBlock> (expensive, once)
layout::flatten() -- build PreRenderedDocument (cheap, repeated on resize)
ratatui::init() -- enter raw mode + alternate screen
TERMINAL_ACTIVE = true -- arm panic hook
run_event_loop() -- main loop
ratatui::restore() -- always called, even on error