Files
synchronicity/docs/notes-markup-rendering.md
Greg ShuflinandClaude Opus 5.5 5fbb0beec5 pdf-render: move the desktop's PDF render thread into its own crate
The thread that owns a parsed mupdf::Document, its page cache, prefetch and
tile rendering moves out of gui-app's pdf_viewer.rs into rust/pdf-render, so
the TUI's PDF viewer can share it. gui-app keeps RenderDispatch (getting the
bytes to the thread from the store or another node).

The crate is generic over the frontend's image type, through a PageImage
trait: the frontend names its pixel order, mupdf renders straight into it,
and the thread wraps the bytes. That keeps what the desktop already had,
pages built as gpui images on the render thread with no pixel pass on the
UI thread, without the crate knowing about gpui. AtlasImage implements it
for the desktop (BGRA); Arc<RgbaImage> is provided for everyone else.

Other API changes made along the way: RenderPurpose::Thumbnail { max_edge }
replaces recognizing a thumbnail by its magic scale, and errors are a
thiserror RenderError rather than String. The thread is started with
thread::Builder, so a failed spawn surfaces as a disconnected sender rather
than a panic.

pdf-render stays out of default-members, like gui-app, because it builds
MuPDF's C source; unit-tests-gui now runs its tests too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 04:10:47 -08:00

47 KiB
Raw Permalink Blame History

Notes: markup authoring and rendering

Status: Phases 0–7 implemented — the gpui desktop app (including inline math within prose, §5.5) and, as of Phase 7, the Android app, both rendering the same shared IR. Scope: the Notes agent, shared across the gpui desktop app and the Android app — the core (IR, markup/typst/math engines, wikilink resolution) lives in rust/lib, computed once, so neither renderer reimplements the markup semantics.

Goal

A note is a plain-text body plus a TextFormat (Markdown | Typst | PlainText, already in the data model). The user types raw markup in a monospace editor and can switch between three view modes with a single control, Joplin-style:

Mode Layout
Edit source only, monospace
Preview rendered only
Split source left, rendered right, 50/50

The rendered output should read like Obsidian/Joplin: comfortable measure, clear heading hierarchy, tinted code blocks, real tables.

Non-goals (for this plan)

  • WYSIWYG / live-preview-in-the-editor (Obsidian's "Live Preview"). We render a separate pane, not styled-in-place source.
  • Typst as a general document-authoring environment (packages, multi-file projects, #import from disk). Notes compile as a single in-memory file.
  • HTML embedded in markdown. Raw HTML blocks and inline HTML are shown as literal text; we never build a HTML engine into the renderer.

1. The central decision: a flat, platform-neutral IR in synchronicity_lib

The markup semantics (what is a heading, what is emphasized, where a link points) get computed once, in Rust, and both GPUI and Compose consume the same result. Neither platform ever sees a markdown token.

The shape of that result is chosen to match what both UI toolkits actually want to be handed:

  • gpui: StyledText::with_runs(Vec<TextRun>) — one string plus a list of styled runs, each covering a byte range.
  • Compose: AnnotatedString — one string plus a list of SpanStyles over ranges.

These are the same model. So the IR flattens the inline tree into text + spans rather than exposing a recursive Inline enum. Nested emphasis (**bold *and italic***) becomes overlapping/merged spans, computed in Rust once. This also sidesteps recursive-enum friction in UniFFI and means neither renderer has to walk a tree to lay out a paragraph.

// rust/lib/src/markup/ir.rs  (sketch)

/// A parsed document, ready to render. Carries no pixel values, colors, or
/// font sizes — styling is each platform's theme's business. Semantics only.
pub struct MarkupDoc {
    pub blocks: Vec<Block>,
    /// Raw YAML frontmatter, if the source opened with one.
    pub frontmatter: Option<String>,
    /// Non-fatal notes from the parser (e.g. an unresolved wikilink target).
    pub diagnostics: Vec<Diagnostic>,
}

/// Blocks are a *flat* list: nesting is expressed as two integers rather than
/// as a tree, because every renderer only uses nesting for indentation and
/// quote decoration. Flat keeps the FFI surface trivial and lets both
/// renderers emit a simple vertical list of elements.
pub struct Block {
    pub kind: BlockKind,
    /// List/indent depth (0 = top level).
    pub indent: u8,
    /// Number of enclosing block quotes (0 = not quoted).
    pub quote_depth: u8,
    /// Byte range in the source, for scroll-sync and error mapping.
    pub source: Range<u32>,
}

pub enum BlockKind {
    Heading { level: u8, anchor: String, text: InlineText },
    Paragraph(InlineText),
    CodeBlock { language: Option<String>, code: String },
    ListItem { marker: ListMarker, text: InlineText },
    Table { header: Vec<InlineText>, rows: Vec<Vec<InlineText>>, alignment: Vec<ColumnAlign> },
    ThematicBreak,
    MathBlock(String),
    Image { target: LinkTarget, alt: String },
    FootnoteDefinition { label: String, text: InlineText },
}

pub enum ListMarker { Bullet, Ordered(u32), Task { checked: bool } }

/// One paragraph's worth of text, pre-flattened into a *partition*: the spans
/// are non-overlapping, consecutive, and together cover the whole string. See
/// the note below on why a partition rather than ranges.
pub struct InlineText {
    pub text: String,
    pub spans: Vec<Span>,
}

pub struct Span {
    /// utf-8 byte length. Spans are consecutive, so no start offset is needed.
    pub len: u32,
    pub style: SpanStyle,    // bitflags: BOLD | ITALIC | STRIKETHROUGH | CODE | MATH
    pub link: Option<LinkTarget>,
}

/// Where a link goes. Resolution of wiki/document links happens in the lib,
/// not the UI, so both platforms navigate identically.
pub enum LinkTarget {
    Url(String),
    /// A note in the same notebook, already resolved to its id.
    Document(DocumentID),
    /// A `[[wikilink]]` that matched nothing — rendered as a "broken link".
    UnresolvedNote(String),
    /// `#some-heading` within this note.
    Anchor(String),
}

Two consequences worth stating plainly:

  1. The IR carries no styling. No px, no color, no font name. A heading says level: 1; the desktop theme decides that's 28px semibold and Compose decides it's MaterialTheme.typography.headlineLarge. This is what makes the same IR serve two very different design systems.
  2. Spans are a partition, not a set of ranges. This is forced by the asymmetry between the two targets: gpui's TextRun carries only a len, so runs are a consecutive partition and overlap is unrepresentable, while Compose's AnnotatedString accepts arbitrary overlapping Ranges and merges them. A partition satisfies both exactly; a range set satisfies only Compose and would leave gpui re-flattening every paragraph on every frame — precisely the per-platform work this IR exists to eliminate. So nested emphasis is resolved into partition boundaries in the lib, once.
  3. Offsets are bytes into the flattened string, not into the source. Block::source separately keeps the tie back to the editor for scroll-sync and error mapping.

Where it lives

  • rust/lib/src/markup/mod.rs — the module, feature-gated? No: it's cheap (pulldown-cmark is small and pure Rust) and every frontend wants it, so it is unconditional like documents.
  • #[derive(uniffi::Record)] / uniffi::Enum on the IR types directly in markup/, following the LogVerbosity precedent, with the entry-point functions exported from ffi.rs like the rest.

2. Markdown dialect

pulldown-cmark 0.13 — the best-maintained Rust markdown parser, and the only one that offers, in one crate, every extension a notes app wants.

The dialect is CommonMark 0.31 plus exactly these extensions, pinned in one place (markup::OPTIONS) so it is a specification and not an accident. "GFM baseline" below means the extension is part of GitHub Flavored Markdown (GFM), the superset of CommonMark whose ubiquity makes those constructs the ones a note pasted in from elsewhere is most likely to contain:

Extension pulldown-cmark option Why
Tables ENABLE_TABLES GFM baseline
Strikethrough ENABLE_STRIKETHROUGH GFM baseline
Task lists ENABLE_TASKLISTS notes are full of checklists
Footnotes ENABLE_FOOTNOTES GFM baseline
Wikilinks [[Note]] ENABLE_WIKILINKS the notes-app idiom; resolves to a DocumentID
Math $x$ / $$x$$ ENABLE_MATH delimiters only; the notation inside is a setting (§5)
YAML frontmatter ENABLE_YAML_STYLE_METADATA_BLOCKS note metadata/tags later
Heading anchors ENABLE_HEADING_ATTRIBUTES #heading links

Deliberately off: ENABLE_SMART_PUNCTUATION (silently rewriting the user's quotes and dashes in a notes app is hostile), ENABLE_OLD_FOOTNOTES.

Rejected alternatives: comrak (more literally GFM-conformant, but heavier and its arena AST is a worse fit for producing a flat IR); markdown-rs (nice owned mdast, but slower and less used).

Round-tripping is not a goal — we parse for display; the source file is the source of truth and is never rewritten by the renderer.


3. Rendering markdown in GPUI

New component rust/gui-app/src/components/markup_view.rs, driven by a MarkupStyle struct that lives with the theme:

/// Per-level heading sizes, code-block padding, blockquote rule width, list
/// indent step, and the max line measure. Named constants, one place, so the
/// look is tunable without touching the renderer.
pub struct MarkupStyle { /* ... */ }

Block dispatch, one small function per BlockKind (per CLAUDE.md's "functional subcomponents with meaningful names" rule):

  • render_paragraph — StyledText::with_runs(runs). gpui's StyledText wraps to the available width (shape_text with wrap_width), so paragraphs reflow for free. When the paragraph contains any Span with a link, wrap it in InteractiveText and hook on_click per range → emit a MarkupEvent::LinkClicked(LinkTarget) the Notes view handles.
  • Inline code and math spans get StyledText::with_font_family_overrides to swap in the monospace family for just that range — no extra element needed.
  • render_heading — size/weight from MarkupStyle, plus a bottom rule for level <= 2 (the Obsidian/Joplin look).
  • render_code_block — monospace on theme.bg_card, rounded_md, horizontal scroll, language label in the corner. Syntax highlighting is a later phase (§8).
  • render_list_item — indent by indent * MarkupStyle::indent_step, bullet / number / checkbox glyph per ListMarker.
  • render_table — reuse components/table.rs.
  • render_block_quote_decoration — a left rule per quote_depth, wrapping the block; because nesting is flat, this is a when(quote_depth > 0) wrapper rather than a recursive call.

The whole pane is a scrolling column with a max-width measure (~72ch) centered in the pane, which is most of what makes Obsidian read well.

Text must stay selectable/copyable (CLAUDE.md). StyledText participates in gpui text selection within an element; verify selection across sibling blocks early — if it doesn't work, that is a known limitation to record here, not to discover at the end.


4. Typst

4.1 Fix the world first

rust/lib/src/typst/world.rs is written for one-shot export and is not usable behind a live preview. Before anything is wired to the UI:

  1. Font loading is the blocker. TypstWorld::new() currently walks every system font directory and fs::reads every face into a Vec<u8> — on every compile. Replace with typst-cli's FontSlot approach: build the FontBook from fontdb's face metadata (no file reads), and load each Font lazily in World::font(index) behind a OnceLock. Hold the resulting book/slot table in a process-global LazyLock<Arc<FontCache>> so the second compile pays nothing.
  2. Embed the default fonts via typst-assets (features = ["fonts"]). Typst's defaults (Libertinus Serif, New Computer Modern Math, DejaVu Sans Mono) currently don't resolve at all, so every document silently falls back to whatever the system happens to have — and on Android to almost nothing. This also lets us drop the compile_typst_with_fonts / bundled-asset dance on the Android side.
  3. today() returns a hardcoded 2024-01-01. Return the real date, with the requested UTC offset applied.
  4. Call comemo::evict after each compile (comemo is already a workspace dependency but unused here). Without it, typst's incremental cache grows unboundedly across a preview session.
  5. Structured diagnostics. Replace format!("{e:?}") with a TypstDiagnostic { severity, message, hints, span: Option<Range<u32>> } mapped back to source byte offsets, so the preview pane can show a real error next to the line that caused it. SourceDiagnostic carries the span; Source::range(span) converts it.

4.2 Render to pixels, not through PDF

Add typst-render (0.15) and expose:

pub struct TypstPage { pub width_px: u32, pub height_px: u32, pub rgba: Vec<u8> }

pub fn render_pages(source: &str, pixels_per_pt: f32)
    -> Result<Vec<TypstPage>, Vec<TypstDiagnostic>>;

This replaces the PDF round-trip for preview on both platforms: typst → tiny-skia pixmap → RGBA. It is pure Rust, so it works identically on Android and on a headless desktop, and it removes MuPDF from Android's typst path entirely. compile_to_pdf stays, but is repurposed as Export to PDF, which is what it should have been all along.

GPUI side: RGBA → BGRA RenderImage (the exact conversion already exists in agents/pdf_viewer.rs — extract it into a small shared helper rather than copying it), then a scrolling column of page images. Reuse components/zoomable_image.rs for zoom/fit so typst preview gets the same zoom controls as the PDF viewer.

4.3 Compilation is async and debounced

Typst compilation is tens-to-hundreds of milliseconds and must never run on the UI thread. Reuse the pattern already in agents/notes/mod.rs::schedule_save: a Task held in the view, dropped and re-armed on each keystroke, so a compile only fires once the user pauses (~400ms; separate from the 600ms save debounce). While a compile is in flight, keep showing the previous page images rather than blanking the pane — a flashing preview is the main way these panes feel bad.


5. Math in markdown

ENABLE_MATH gives us $…$ and $$…$$ spans in the IR. It is worth being precise about what that option does and does not do: pulldown-cmark recognizes the delimiters only and hands back the enclosed string verbatim as Event::InlineMath / Event::DisplayMath. It has no math grammar and no opinion about the notation inside. (Its only cleverness is tracking brace nesting so a stray $ in prose can't pair with a distant one — see the $}$2+2$ cases in firstpass.rs.)

So the notation between the dollar signs is our choice, and it is a real one: typst's math syntax is not LaTeX.

LaTeX:  $\frac{x^2}{3} + \sum_{i=1}^{n} \alpha_i$
Typst:  $x^2/3 + sum_(i=1)^n alpha_i$

5.1 It's a setting

The math dialect used inside $…$ in markdown notes is a Notes-agent setting, persisted per ADR 0018 (so it syncs across nodes):

pub enum MathDialect { Latex, Typst }   // default: Latex

Latex is the default because a note written that way still renders in GitHub, Obsidian, Pandoc, and every static-site generator — which matters for a project whose premise is that your documents outlive any one program. Typst is there for users who'd rather write one syntax across both note formats.

This setting applies only to markdown notes. A Typst-format note is typst all the way down and its math is typst math by definition; the setting doesn't enter into it.

5.2 Two engines behind one interface

Both dialects resolve to the same output type, so the renderers never branch on dialect:

/// A rendered math snippet. `baseline_px` is the distance from the top of the
/// bitmap down to the text baseline, so inline math sits on the surrounding
/// line's baseline instead of being pasted in as a floating image.
pub struct MathRender {
    pub width_px: u32,
    pub height_px: u32,
    pub baseline_px: f32,
    pub rgba: Vec<u8>,
}

pub trait MathEngine {
    fn render(&self, src: &str, display: bool, font_size_px: f32, dpr: f32)
        -> Result<MathRender, MathError>;
}
  • Typst dialect — compile the snippet as a single auto-sized page and take page 0's Frame, which carries baseline() directly. Reuses the world, fonts, and diagnostics from §4.1, so it costs almost nothing beyond what typst preview already needs.
  • LaTeX dialect — RaTeX (ratex-parser → ratex-layout → ratex-render, currently 0.1.x). It is a native Rust reimplementation of KaTeX's typesetting — KaTeX's font set, KaTeX's supported-command surface — which is exactly the bar asked for: "reasonable for most users broadly familiar with LaTeX math", not literal TeX compatibility.

Explicitly rejected: mitex (LaTeX→typst source transpilation — an extra lossy hop, and its failure modes surface as confusing typst errors about code the user never wrote); pulldown-latex, math-core, latex2mathml (all emit MathML, and neither GPUI nor Compose has a MathML renderer — that road ends at a WebView); katex-rs (a faithful port of KaTeX's internals, but its output is HTML+CSS, which is only useful if you have a browser to lay it out).

5.3 Why RaTeX's layout output is the good part

RaTeX's layout stage produces a resolution-independent, absolutely-positioned display list before anything is rasterized:

pub struct DisplayList { pub items: Vec<DisplayItem>, pub width: f64,
                         pub height: f64, pub depth: f64 }

pub enum DisplayItem {
    GlyphPath { x, y, scale, font: String, char_code: u32, color },
    Line { x, y, width, thickness, color, dashed },   // fraction bars, overlines
    Rect { x, y, width, height, color },
    Path { x, y, commands: Vec<PathCommand>, fill, color },  // radicals, big delimiters
}

That's TeX box metrics (height above the baseline, depth below) plus a flat list of glyph and path draws in em units — and it's Serialize. Two things follow:

  1. depth gives us correct inline baseline alignment for free, which is the difference between math that sits in the sentence and math that floats in it.
  2. Rasterizing via ratex-render is the starting point, not the ceiling. The display list could later be painted natively — gpui glyph draws, Compose drawPath — so math scales with text and stays crisp at any zoom without re-rendering bitmaps. Worth designing toward; not worth doing first.

5.4 Caching and sizing

Math renders are pure functions of (dialect, source, font_size_px, dpr), so key an LRU on the hash of exactly that. Without it, every keystroke in a formula-heavy note re-rasterizes every formula on screen. The cache must be invalidated on window scale-factor change, not just on edit.

Update: done, as math::cache::CachedMathEngine<E> (rust/lib/src/math/cache.rs) — an LRU (the lru crate, already in the dependency tree transitively via iroh-relay, so this just makes it a direct dependency rather than reaching for a second implementation) keyed on (source, display, font_size_px.to_bits(), dpr.to_bits()); dialect isn't in the key because one CachedMathEngine instance already wraps one concrete engine. .to_bits() on the floats rather than the floats themselves, since f32 isn't Hash/Eq. Returns Arc<MathRender> so a cache hit clones a pointer, not a multi-KB bitmap. No explicit scale-factor invalidation was needed: dpr being part of the key already makes a monitor change produce fresh misses at the new resolution, while the old entries just go cold and age out under the LRU's normal capacity pressure — one fewer moving part than an explicit clear() path.

This intentionally doesn't share the PDF viewer's page cache (pdf-render/src/state.rs's RenderState::page_cache): that one evicts by distance from the currently-viewed page, which only makes sense because PDF pages have prefetch locality (the next few pages are likely to be viewed next); math formulas on screen have no such ordering; recency (LRU) is the right policy for one and not for the other, so unifying them would mean threading a page-viewer-specific eviction strategy through a cache that has no concept of "pages" at all. The genuine shared piece already exists precisely where the two do overlap — gui-app/src/components/render_image.rs's RGBA→BGRA RenderImage conversion, used by both the PDF viewer and the notes typst preview — and MathRender's premultiplied-RGBA contract (§1) is designed to feed the same helper once math rendering is wired into the UI.

5.5 Risk

RaTeX is a young single-author crate (0.1.x). This plan therefore puts our MathEngine trait in front of it rather than letting ratex_* types leak into the IR or the renderers — which is required regardless, since the typst dialect is a second implementation of the same trait. If RaTeX stalls or its coverage disappoints, the blast radius is one impl behind a trait we already needed. Phase 5 should start by throwing a corpus of representative formulas at it and looking at the output before committing.

Update: done. A 21-formula corpus (fractions, sums/products, roots, matrices, cases, accents, blackboard-bold, mixed text/math mode, subscript/superscript combinations) rendered correctly and matched KaTeX's look once the crate's embed-fonts feature was enabled (without it, ratex-render has no fonts to draw with and every formula fails to render — worth calling out since the crate itself doesn't default this on). Performance after warmup: ~3ms per formula (parse+layout+render+PNG-encode) for a moderately complex expression, comfortably inside an interactive debounce. ratex-render's only public entry point (render_to_png) returns encoded PNG bytes rather than a raw pixmap + baseline the way crate::typst::render_pages does, so RatexMathEngine decodes the PNG back to RGBA and recomputes baseline_px from the same font_size/padding/dpr inputs render_to_png uses internally (§5.4's cache key already covers exactly those inputs, so this isn't extra state). Committed: MathEngine trait plus both impls now live in rust/lib/src/math/, evaluated corpus included as ratex_engine's regression test.

Since committed: the render cache (§5.4, math::cache::CachedMathEngine) and display/block math wiring into components::markup_view's BlockKind::MathBlock — see that module's docs and MathContext. NotesView holds one long-lived CachedMathEngine per engine (so the LRU actually survives across renders/keystrokes) and picks whichever matches the note's MathDialect setting, loaded at startup the same way NotesViewMode is. Object-safety needed one small addition beyond §5.2's plan: CachedMathEngine isn't itself generic-friendly for a caller that picks an engine at runtime, so math::cache::MathRenderer is a small dyn-compatible wrapper trait (Arc<dyn MathRenderer>) blanket-implemented for any CachedMathEngine<E>. Rendering is synchronous in the render path (unlike typst's whole-document preview, which needed §4.3's debounced background compile) — RaTeX's ~3ms and the LRU's cache-hit steady state make that fine for now; if a formula-heavy document with a cold cache turns out to visibly stutter on first open, that's the point to revisit and move to the same async debounce pattern.

Not yet done: inline math (SpanStyle::MATH spans within prose) still renders as literal monospace source — gpui's StyledText has no notion of an image sitting inline within shaped text at a specific baseline, so this needs real layout work in MultilineTextElement/StyledText first, which is exactly why the phasing (§8) put it after display math.

Update: done, for paragraphs and list items (the two block kinds that actually render inline math — see below). components::markup_view::render_inline_text now takes a math: Option<&MathContext>: headings, table cells, and footnote definitions still pass None (inline math there stays literal monospace source, unchanged — a deliberate scope cut, not an oversight, since it's a genuinely rare case not worth the extra threading), but render_paragraph/ render_list_item pass Some, and when text actually has a MATH span, render_inline_text hands off to render_inline_text_with_math instead of building one StyledText.

Since StyledText can't embed an image mid-line, that function splits the InlineText at math-span boundaries (group_inline_spans) into a sequence of text/formula runs and lays them out as its own flex_row().flex_wrap() row: each text run renders through the original single-StyledText path (so bold/links/code around a formula keep working exactly as before, just scoped to a sub-range), each formula renders as an img() shifted down by inline_baseline_from_top - baseline_px so its own baseline lines up with the surrounding text's, using RaTeX's/Typst's MathRender::baseline_px the way §5.3 always intended ("the difference between math that sits in the sentence and math that floats in it"). inline_baseline_from_top isn't a guessed ratio — it's gpui's own font metrics (window.text_system().baseline_offset(font_id, prose_font_size, prose_line_height)), resolved once per render in NotesView::render_preview_pane and threaded down through MathContext, which is also why render_content/ render_note_body/render_preview_pane all gained a window: &Window parameter they didn't need before.

This is a real, stated compromise, not a hidden one: gpui/Taffy measures each text run's own wrapping correctly (a flex-wrap child is still a proper text node, not a fixed box), but two runs never reflow into one shared line the way words within a single paragraph would — each run is its own flex item that either fits on the current line whole or wraps to the next. Short runs around one or two formulas (the common case) read as ordinary wrapped prose; a paragraph built from many short text/math alternations could show more line breaks than a true inline layout would. Natively painting RaTeX's display list (§5.3's "worth designing toward; not worth doing first") is the eventual fix for that — this pass intentionally didn't reach for it.

Update: the settings-screen entry is done, as a small settings screen inside the Notes agent itself (NotesView::render_settings_screen), reached via a gear icon (Icon::Settings) at the right edge of the Notes header (NotesView::render_header) rather than a tab on the global Settings screen. A first pass put it there instead (one more settings.rs tab, since that's where every other setting already lived), but a setting that's entirely about how one agent's notes are written reads oddly parked next to Sync policy and Ensemble — and living inside NotesView means a change takes effect immediately (same Entity, same math_dialect field the preview already reads), no cross-screen resync needed the way a global-Settings tab would have required. NotesScreen (Notebook/Settings) is the enum that picks between this and the normal notebook/note browser, deliberately distinct from NotesViewMode (Edit/Preview/Split), which only ever picks how the open note's body renders. NotebookManager's existing get_math_dialect/set_math_dialect back it directly, persisted the same best-effort way set_view_mode already persists the view mode (update state and repaint immediately, write through on the background executor).

The chrome (gear button, back-button header) was pulled out into components::agent_settings once it was clear this wasn't going to be a Notes-only pattern — every agent should get its own settings screen this way rather than a tab on the shared Settings screen, per that module's doc comment, which is the canonical description of the pattern going forward. NotesView is its reference implementation: a screen: NotesScreen field, settings_gear_button in the header, and an early Render::render branch to settings_screen_header plus the settings content.


6. The mode switcher and the format selector

Two controls in the note meta row (render_note_meta_row), right-aligned:

  • Format: a small dropdown, Markdown / Typst / Plain text, reusing the existing DropdownMenu. Changing it needs a new NotebookManager::set_note_format(&DocumentID, TextFormat); the format is already stored on the body artifact and already returned by get_note, the GPUI view just discards it today (let (body, _) = ...) and create_item hardcodes TextFormat::Markdown.
  • View mode: a three-position icon segmented control — Pencil / Eye / Columns from the Lucide set, with tooltips.

A note on the CLAUDE.md iconicity rule: it says within-screen sub-view switching should use components::tabs::{tab_bar, tab_pill} on desktop and a Compose TabRow on Android. This control is deliberately a compact segmented icon control instead, because it is a toolbar affordance sitting beside the note title rather than a full-width view switcher, and because that is the Joplin affordance being asked for. The cross-platform counterpart is Compose's SingleChoiceSegmentedButtonRow — which SourceCodeInput.kt already uses — so iconicity across platforms is preserved. This warrants a new shared components/segmented_control.rs and a one-line amendment to the CLAUDE.md rule recording the exception.

Split mode reuses components/resizable.rs so the divider is draggable, same as the sidebar. Persist the chosen mode (and split ratio) as an agent setting per ADR 0018 so it survives a restart and syncs across nodes; per-note format is already persisted with the note.

The Notes agent's settings screen gains one more entry alongside these: Math syntax in markdown notes — LaTeX (default) or Typst, per §5.1. It belongs in settings rather than the note toolbar because it's a statement about how the user writes, not about an individual document.


7. Editor gaps this exposes

The current NoteEditor is a solid plain-text editor but has two gaps that a markup-authoring workflow makes untenable:

  1. No soft wrapping. MultilineTextElement shapes one shape_line per source line, so a long markdown paragraph runs off the right edge with no way to see it. Fixing this means shaping with shape_text(..., wrap_width) and reworking the offset↔position math (vertical_offset, index_for_mouse_position_multiline, bounds_for_range) to operate on visual lines while selection/editing stays in source offsets. This is the single largest piece of work in the plan and it also affects TextArea, which shares the element.
  2. No undo/redo. EditableText has no history. Table stakes for anything people write prose in. A simple coalescing undo stack (group consecutive insertions, break on newline/navigation/paste) on EditableText serves both the editor and every form field.

Also worth doing while in here: Tab inserts indentation rather than moving focus, and ctrl-shift-z / ctrl-y for redo.


8. Phasing

Each phase is independently shippable and independently reviewable. The numbering is a suggested order, not a dependency chain — the actual dependencies fan out from two lib-only roots:

Phase 0 (typst world) ─┬─→ Phase 3 (GPUI typst preview)
                       └─┬→ Phase 5 (math)
Phase 1 (markup IR) ─────┼→ Phase 2 (GPUI markdown preview)
                         ├→ Phase 6 (links and images)
                         └→ Phase 7 (Android)

Phase 4 (editor quality) — depends on nothing here; can land at any point.

Phases 2 and 7 are sibling consumers of the IR, not sequential. Phase 7 is listed last because it's the largest, not because anything but Phase 1 blocks it (and its typst half needs Phase 0; its math needs Phase 5).

There is a case for pulling Phase 7's markdown half forward to sit directly beside Phase 2: §1's central claim — that one flattened IR serves both design systems — is only really tested once a second renderer consumes it, and the cost of finding a flaw grows with every phase built on top. The TextRun partition constraint in §1 was found exactly that way. The counterweight is that Android's markdown rendering currently works (via compose-markdowntext), so moving it onto the shared IR early trades a working renderer for a less complete one until the IR reaches parity.

Phase 0 — typst groundwork (lib only, no UI) Font cache + lazy FontSlot + typst-assets, real today(), comemo::evict, structured TypstDiagnostic, render_pages via typst-render, compile_to_pdf retained as export. Benchmark: second compile of a small document should be single-digit milliseconds, not seconds. Add a regression test asserting repeat-compile latency, in the spirit of bench_blob_decrypt_throughput.

Phase 1 — the markup IR (lib only) markup module, OPTIONS dialect constant, pulldown-cmark → MarkupDoc. Golden tests: a corpus of markdown snippets → expected IR, plus the CommonMark constructs we claim to support. No UI, no FFI yet.

Phase 2 — GPUI markdown preview components/markup_view.rs, MarkupStyle in the theme, the segmented view-mode control, split mode via resizable. Preview is read-only; links are inert except external URLs (open in browser).

Phase 3 — GPUI typst preview Format dropdown + set_note_format, debounced background compile, page images via ZoomableImage, diagnostics panel that maps errors to editor lines, Export to PDF.

Phase 4 — editor quality Soft wrapping, undo/redo, Tab handling. Optionally source syntax highlighting (pulldown-cmark gives source ranges; typst::syntax exposes a typed tree to walk) once MultilineTextElement supports per-run styling.

Phase 5 — math The MathEngine trait and both impls (typst; RaTeX for the LaTeX dialect), the MathDialect setting, the render cache, inline baseline alignment via depth / Frame::baseline(). Start with an evaluation corpus of representative formulas run through RaTeX and looked at before committing to it (§5.5). Display math lands first (a block-level image is easy); inline math second, since that's where baseline alignment has to be right.

Phase 6 — links and images Wikilink resolution against the notebook ([[Note title]] → DocumentID), click-to-navigate, broken-link styling, #heading anchors, images resolved from the blob store.

Update: done. synchronicity::markup::resolve_wikilinks (rust/lib/src/markup/resolve.rs) is the second, optional IR pass §1's LinkTarget::Document doc comment always pointed at: given a title→DocumentID lookup, it turns every UnresolvedNote it can match into a Document and leaves the rest alone — an UnresolvedNote that has been through this pass means "genuinely broken", not "not yet looked up". It walks every InlineText (headings, paragraphs, list items, table cells, footnote definitions) and Image block targets alike, since ![[img]] resolves through the same wikilink machinery as [[Note]]. Kept in the lib, not the GUI, per §1's original framing ("resolution... happens in the lib, not the UI, so both platforms navigate identically") — Android gets this for free in Phase 7.

NotesView::render_preview_pane builds the title index from self.items (lowercased, scoped to the current notebook — cross-notebook wikilinks don't resolve, a deliberate scope cut) and calls resolve_wikilinks before handing the doc to markup_view. components::markup_view gained two small per-render contexts alongside MathContext to carry the rest: LinkContext (Rc<dyn Fn> callbacks, since they end up inside InteractiveText::on_click's 'static listener) for on_navigate (Document clicks call NotesView::select_note through a cloned Entity handle) and on_anchor (looked up against a HashMap<anchor, block index> built alongside the wikilink resolve, then ScrollHandle::scroll_to_top_of_item); and ImageContext (a plain borrowed closure, since it's only ever called synchronously within the same render pass) for looking up a Document-image block's load state. Broken wikilinks get their own look in span_highlights — color_error plus a wavy underline, versus resolved links' solid accent underline — and are excluded from the clickable ranges entirely (is_actionable), since there's nowhere to navigate.

Jump-to-heading forced markup_view to start owning its own scroll region (id/ScrollHandle params) rather than leaving that to the caller as originally designed in §3: ScrollHandle::scroll_to_top_of_item addresses a direct child of whatever element it tracks, which has to be markup_view's own block list, not a wrapper placed around it — so each block's measure-constrained/centered wrapper moved from being one shared wrapper around the whole column to one per block, keeping the visual result identical while making blocks direct children of the tracked/scrollable div. NotesView owns one long-lived ScrollHandle (preview_scroll), reset via scroll_to_top_of_item(0) whenever a different note is selected.

Images resolved from the blob store reuse the same async pattern as the Pictures agent's select_image (agents/pictures.rs) and the same RGBA→RenderImage conversion the PDF viewer and typst preview already share (components::render_image::rgba_to_render_image) — load_image_bytes + image::load_from_memory off the background executor, folded back via Entity::update. Since markup_view is a stateless function (§3: "nothing here holds state across renders"), the load state itself lives on NotesView — image_cache: RefCell<HashMap<DocumentID, ImageState>>. The RefCell (rather than a plain field) is because render_preview_pane takes &self, but still needs to claim an id as Loading and kick off its fetch the first time that id is seen (NotesView::ensure_images_loading), which is otherwise indistinguishable from a "not requested yet" absence to a bare immutable read. Cleared on every select_note — deliberately not an LRU like the math render cache (§5.4): only the currently open note's images are ever looked up, so the cache never needs to be larger than that.

Phase 7 — Android UniFFI-export MarkupDoc + render_pages + the math engine. A Compose renderer over the same IR (InlineText → AnnotatedString is nearly mechanical), replacing dev.jeziellago.compose.markdowntext and SourceCodeInput.kt's compile-to-PDF-then-MuPDF path. At that point both platforms share the dialect, the semantics, the link resolution, the math engines, and the typst pipeline; only styling and element construction are per-platform.

Update: done. All of markup::ir, math::{MathDialect, MathRender}, typst::{TypstPage, TypstDiagnostic, TypstDiagnosticSeverity}, agents::notebook::NotesViewMode, and documents::TextFormat now derive uniffi::Record/uniffi::Enum directly on their existing lib-internal definitions — no FFI mirror types needed, following the precedent §1 already set with ThemeMode/LogVerbosity. The one non-obvious piece was SpanStyle (a bitflags! u8, so neither a plain enum nor a record): uniffi::custom_type!(SpanStyle, u8, ...) crosses it as a raw UByte, exactly the way DocumentID already crosses as a String (documents::document::DocumentID's own custom_type!) — Kotlin decodes the bits back into flags itself (notes/markup/SpanStyleBits.kt's hasStyle), since UniFFI 0.31 has no bitflags support of its own. New free functions in ffi.rs: parse_markup, resolve_wikilinks (taking a Vec<WikilinkTitle> title index built by the caller — UniFFI has no tuple support, same reason FontData exists), render_typst_preview (wraps render_merged_pages, returning a TypstPreviewOutcome{ page: Option<TypstPage>, diagnostics } record rather than a Result, since UniFFI has no clean way to make a Vec the error side of one), and render_math, backed by a module-level LazyLock<MathEngines> holding one Arc<dyn MathRenderer> per dialect — a process-global mirror of gui-app's NotesView::math_ratex/math_typst fields, needed because there's no long-lived view object on the FFI side to hold them (same shape as TypstWorld's font cache). SyncNode gained notebook_get_note (replacing notebook_get_note_body, now returning body

  • format together — Android's renderer needs both to pick a renderer) plus notebook_set_note_format/get_view_mode/set_view_mode/ get_math_dialect/set_math_dialect, all thin wrappers over NotebookManager methods that already existed pre-Phase-7.

On Android (android/app/src/main/java/com/gregshuflin/synchronicity/notes/): markup/MarkupRenderer.kt dispatches per BlockKind to small named composables exactly like components::markup_view's block dispatch, styled from MaterialTheme.typography/colorScheme rather than a ported MarkupStyle token struct (Android already has its own theme system). markup/InlineTextRenderer.kt is the "nearly mechanical" InlineText/Span → AnnotatedString conversion §1 predicted, using the classic pushStringAnnotation/getStringAnnotations + tap-position lookup for links (version-safe against the BOM in use, rather than the newer LinkAnnotation API). Inline math turned out to need less compromise than desktop: Compose's InlineTextContent/Placeholder embeds an image inside shaped text natively, so there's no equivalent of §5.4's flex_row row-per-run workaround — one Text call handles a paragraph with formulas in it directly. Baseline alignment reuses the same idea as gpui's manual img() offset, expressed through Compose's placeholder mechanics instead: the reserved placeholder height is only baseline_px (the ascent-to-baseline part) with PlaceholderVerticalAlign.AboveBaseline, and the full-height bitmap is drawn unclipped from the top of that shorter box, so its own baseline — not its bottom edge — lands on the placeholder's bottom, which AboveBaseline pins to the text line's baseline.

markup/TypstPreview.kt replaces SourceCodeInput.kt's compile-to-PDF-then- MuPDF path outright: render_typst_preview (wrapping render_merged_pages, the same single-merged-image entry point gpui's preview uses) returns RGBA pixels directly, converted to an Android Bitmap with no channel swizzling (ui/RgbaBitmap.kt — despite the "ARGB_8888" name, Bitmap's copyPixelsFromBuffer byte order is already R,G,B,A). The pinch/pan/ double-tap-zoom gesture logic previously duplicated inline in pdfs/PdfViewer.kt was pulled out into ui/ZoomableBitmap.kt (ZoomableBitmap/ZoomState), which the Typst preview and the PDF viewer both now use — PdfViewerState keeps its existing scale/offset/ resetTransform/isZoomedIn API by delegating to an embedded ZoomState, so PdfStatusBar/PdfToolbar needed no changes. Compilation is debounced (~400ms, snapshotFlow + collectLatest) and keeps the previous render visible while a new one compiles, per §4.3.

NoteEditorPane.kt gained the three-way Edit/Preview/Split view-mode control (a SingleChoiceSegmentedButtonRow, generalizing the two-item pattern SourceCodeInput.kt already proved) and a format dropdown, both persisted via the new notebookGetViewMode/SetViewMode/GetMathDialect/SetMathDialect calls (ADR 0018, same as desktop). Split mode is a bespoke draggable-divider Row (detectDragGestures adjusting a fraction state), not a port of components/resizable.rs — Android doesn't have a second consumer for a general resizable-sidebar abstraction yet, so building one preemptively would be exactly the premature abstraction CLAUDE.md warns against. One honest gap from desktop parity: the split fraction isn't persisted (local remember state only) — Phase 7 didn't add a dedicated FFI setting for it, unlike NotesViewMode itself, which is synced.

Wikilink/image resolution mirrors gpui's approach exactly: NotesScreen.kt flattens the currently open notebook's NoteTreeItem tree into WikilinkTitles (NotesModels.kt's toWikilinkTitles) — cross-notebook wikilinks don't resolve, the identical scope cut §6's desktop write-up describes — and calls resolveWikilinks before handing the doc to MarkupView. LinkContext/ImageContext (notes/markup/MarkupContexts.kt) are the Compose analogues of gpui's same-named types: LinkContext also carries onOpenUrl (external links open via Intent.ACTION_VIEW, per §2's Phase 2 note). Images resolve through the existing blob-store FFI (getDocumentBlobBytes) into a mutableStateMapOf<String, Bitmap?> cache cleared on every note switch, the same non-LRU reasoning §6 gives for gpui's image_cache. MathContext layers a small per-render Kotlin-side cache in front of render_math (RenderedMath) purely to avoid re-decoding a bitmap on every recomposition — the LRU that actually matters is still the one inside the Rust call.

The Notes agent also gained the first per-agent settings screen on Android (NotesSettingsScreen.kt, reached via the gear icon in the Notes header, with a private NotesScreenPane enum in NotesScreen.kt picking between it and the notebook browser — distinct from NotesViewMode, exactly the same Notebook/Settings-vs-Edit/Preview/Split distinction §5.5 draws on desktop). Unlike gpui's components::agent_settings, this isn't factored into a shared module yet — Android has only this one instance so far, so extracting a pattern now would be guessing at its shape from a single example; the doc comment on NotesSettingsScreen notes it as the reference point for the next agent that needs one.

Cleanup: SourceCodeInput.kt (confirmed unreferenced outside itself) and the com.github.jeziellago:compose-markdown Gradle dependency are gone, along with the bundled-DejaVu-font-loading dance (NativeLib.compileTypstWithBundledFonts, plus the assets/fonts/*.ttf files it read) — render_merged_pages uses the same embedded typst-assets fonts every other Typst path already relies on, so per-call font bytes are no longer needed on Android either. The jitpack Maven repository in settings.gradle.kts was only ever there for compose-markdown and is removed too. compile_typst/compile_typst_with_fonts themselves — Rust and their thin NativeLib wrappers alike — are left in place per §4.2's "Export to PDF" framing, just uncalled from Kotlin for now.

9. Risks

  • Soft wrapping (Phase 4) is underestimated by everyone, including this document. Every offset↔pixel mapping in the editor assumes one shaped line per source line. If Phase 2/3 land first, they're usable but paragraphs overflow horizontally in the editor pane — acceptable, but say so out loud rather than shipping it quietly.
  • UniFFI and Range<u32>: UniFFI has no Range type. Span avoids this by carrying a len (§1), but Block::source still needs a small ByteRange record with start/end fields. Cheaper to do in Phase 1 than to migrate later.
  • Text selection across blocks in gpui may not work across sibling StyledText elements. Verify in Phase 2, early.
  • RaTeX is 0.1.x and single-author. Contained behind the MathEngine trait (§5.5), which we need anyway for the two dialects — but the evaluation corpus at the start of Phase 5 is what decides whether it's viable, and that evaluation should happen before any UI work in that phase.
  • typst is currently compiled unconditionally into synchronicity_lib for every binary and for Android, despite having zero non-test callers in Rust today. Once it has real callers this is fine; if the compile-time cost bites, a typst feature gate (like multimedia/cbr) is the escape hatch, with cli-app/gui-app/Android opting in.