Skip to content

Architecture

Jordi vidal edited this page Feb 28, 2026 · 2 revisions

Architecture

Unidirectional pipeline

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 responsibilities

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 —

Module boundary rule

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.


RenderedBlock — the semantic IR

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 block type

Adding a new variant requires changes in exactly four files:

  1. parser.rs — add a match arm for the new pulldown-cmark event(s) that produce this block
  2. layout.rs — add a match arm to flatten the new block into display lines
  3. renderer.rs — add a match arm to draw the new block variant
  4. theme.rs (if it needs styling) — add a new style struct and conversion helper

No other files need changing.


Layout word-wrap algorithm

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:

  1. Build a plain String by concatenating all span texts.
  2. Build a parallel Vec<Style> indexed by byte offset into that string.
  3. Call textwrap::wrap() on the plain string to get wrapped lines.
  4. 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.


Table layout

GFM tables go through a multi-stage layout pipeline inside layout.rs:

Column width calculation

  1. Measure the natural width of every cell (unwrapped text length or image width).
  2. Sum natural widths. If total fits within the terminal, use natural widths directly.
  3. If total exceeds available space, shrink columns proportionally — wider columns give up more space, with a minimum of 3 characters per column.

Cell flattening and word-wrapping

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 to col_width with 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.

Multi-line rows

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 (│).

Row 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.


Key invariants

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.

Resize handling

On Event::Resize(cols, _rows):

  1. layout::flatten(&blocks, cols, &app.theme) is called again with the new width.
  2. The result replaces app.document.
  3. app.scroll_offset is clamped to the new max_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.


Terminal initialization sequence

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

Clone this wiki locally