fastmarkdown
Blazing fast, cross-platform Markdown renderer — parse once, display everywhere.
fastmarkdown is a Rust-powered Markdown rendering SDK that parses Markdown into platform-native display objects. Designed for mobile AI agent applications (chat interfaces, code assistants), it outputs NSAttributedString on iOS, SpannableString on Android, and HTML everywhere else — all from a single Rust core with a C FFI.
Install
[]
= "0.1"
Optional syntax highlighting for code blocks:
[]
= { = "0.1", = ["highlight"] }
Why
Traditional Markdown rendering on mobile suffers from:
- View explosion — each inline style span becomes a separate UI widget, drowning the main thread.
- Double parsing — HTML output requires a second parse pass (WebKit HTML parser on iOS) before native display.
- Platform divergence — iOS and Android use different parsers with different behaviors.
fastmarkdown solves all three:
- Span binary format — one flat array of
(offset, len, flags, block_type)replaces N per-span widgets with oneNSAttributedString→ oneUITextView. - No double parsing — the Rust core produces platform-native objects directly (Span → NSAttributedString/SpannableString).
- One codebase — the same Rust parser, the same test suite, the same behavior on every platform.
Features
- Full GFM support — headings, bold, italic, strikethrough, inline code, code blocks, links, images, ordered/unordered lists, blockquotes, tables, horizontal rules, task lists, footnotes
- HTML tag passthrough —
<b>,<i>,<a>,<img>,<table>,<details>, etc., with three safety modes (Strip / Safe / AllowAll) $sign pitfalls avoided — literal mode treats$HOME,$5.99as text; optional detect mode for LaTeX math- Optional code highlighting —
highlightfeature flag +MarkdownOptions::highlight = true. Outputs 15-type token stream inextra_data(kind=4). Host maps types to colors. Zero-cost when disabled - Streaming API — native token-level append for real-time AI output
- Dual output — HTML string (WebView/export) and structured Span array (native rendering)
- Block structure for document viewing —
block_seq(unique per block, for LazyVStack splitting),block_depth(nesting level for list/quote indent), table metadata (column count + per-column alignment) in a self-describingextra_databinary format - Self-describing extra_data —
[kind: u8, len: u16 LE, data]chunks for link URLs, image URLs, code languages, table metadata, and code highlighting tokens. Consumers parse without external indexes - C FFI — static/dynamic library compiled from Rust, consumable from Swift, Kotlin, C, Python
- Cross-platform — iOS (aarch64-apple-ios), Android (aarch64-linux-android), macOS/Linux/Windows
Quick Start
Rust
use ;
// Render to HTML
let html = to_html;
assert!;
// Render to structured spans (for native display)
let output = to_spans;
let spans = unsafe ;
assert!;
unsafe
// Extract plain text (search/preview/notifications)
let text = to_plain_text;
assert_eq!;
// Streaming for real-time AI output
let mut stream = new;
stream.append;
stream.append;
C / FFI
// HTML output
char* html = ;
;
;
// Span output for native rendering
FastMarkdownSpanOutput spans = ;
for
;
// Streaming
FastMarkdownStream* stream = ; // Safe HTML, Literal math
;
;
;
iOS (Swift)
// Using the FFI → spans → NSAttributedString pattern
let output = fastmarkdown_to_spans(md)
defer { fastmarkdown_free_spans(&output) }
let text = String(bytesNoCopy: ...)
let attrString = NSMutableAttributedString(string: text)
let spans = UnsafeBufferPointer(start: output.spans, count: Int(output.span_count))
for span in spans {
let range = NSRange(location: Int(span.offset), length: Int(span.length))
if span.flags & FLAG_BOLD != 0 {
attrString.addAttribute(.font, value: boldFont, range: range)
}
}
textView.attributedText = attrString
Android (Kotlin / JNI)
external fun fastmarkdown_to_spans(markdown: String): FastMarkdownSpanOutput
external fun fastmarkdown_free_spans(output: FastMarkdownSpanOutput)
val output = fastmarkdown_to_spans(md)
val text = String(output.text, 0, output.text_len.toInt())
val spannable = SpannableString(text)
for (i in 0 until output.span_count.toInt()) {
val s = output.spans[i]
if ((s.flags and FLAG_BOLD) != 0u) {
spannable.setSpan(StyleSpan(Typeface.BOLD), s.offset.toInt(), ...)
}
}
fastmarkdown_free_spans(output)
textView.text = spannable
API Reference
Rust API
// One-shot rendering
;
;
;
;
;
;
pub unsafe ;
// Streaming
// Configuration
C FFI
// Core
char* ;
char* ;
FastMarkdownSpanOutput ;
FastMarkdownSpanOutput ;
char* ;
void ;
void ;
const char* ;
// Streaming
FastMarkdownStream* ;
FastMarkdownSpanOutput ;
FastMarkdownSpanOutput ;
FastMarkdownSpanDeltaList ;
void ;
void ;
void ;
// Theme
FastMarkdownTheme ;
See the design document for the full architecture, Span binary format specification, and platform integration guides.
Architecture
Markdown String
│
▼
┌─────────────┐ ┌──────────┐ ┌──────────────────┐
│ Parser │───▶│ AST │───▶│ Renderer │
│ pulldown │ │ (内部IR) │ │ │
│ -cmark │ └──────────┘ │ ① HTML String │
└─────────────┘ │ ② Span Array │
│ ③ Plain Text │
└────────┬─────────┘
│
C FFI Layer
│
┌─────────────────┼─────────────────┐
│ │ │
┌────┴────┐ ┌─────┴─────┐ ┌────┴────┐
│ iOS │ │ Android │ │ Desktop │
│ Swift │ │ Kotlin │ │ Rust/C │
└─────────┘ └───────────┘ └─────────┘
Build from Source
# Clone
# Build (library)
# Run tests
# Run benchmarks
# Cross-compile for iOS
# Cross-compile for Android
In the Wild
fastmarkdown powers markdown rendering in:
- AACode — the mobile AI coding agent for iOS
Use Cases
Chat / AI Messages
fastmarkdown is optimized for chat rendering: parse markdown → flat span array → platform adapter → one NSAttributedString/SpannableString → one UITextView. This eliminates View explosion and gives fast, predictable performance.
File Preview / Document Viewing
Span output carries block_seq, block_depth, and self-describing extra_data:
| field | size | purpose |
|---|---|---|
block_seq |
u16 | unique per block; group by seq → N blocks for LazyVStack / lazy loading |
block_depth |
u8 | list/quote nesting level; depth × indentPerLevel → UI indent |
block_type |
u8 | paragraph, heading, code_block, table_cell, list_item, etc. |
extra_data |
bytes | [kind:u8, len:u16 LE, data] chunks for link URLs, code languages, table metadata (column count + alignment + per-column max char width) |
Table metadata chunk (kind=3): [col_count: u8, (align: u8, char_width: u16 LE)*N] — char_width is the maximum character count per column across all rows, useful for host-side column width estimation without measuring text. |
Consumer guide:
// 1. Reconstruct blocks
let mut blocks: = vec!;
let mut current_seq = spans.block_seq;
let mut current: = vec!;
for s in spans
// 2. Parse extra_data chunks
let mut pos = 0;
while pos + 3 <= extra.len
// 3. Rebuild table rows
let col_count = table_meta as usize;
let data_cells: = spans.iter.filter.collect;
for row in data_cells.chunks
See tests/block_structure.rs and tests/consumer_verify.rs for complete working examples.
Code Highlighting (optional)
Enable via features = ["highlight"] in Cargo.toml and set MarkdownOptions::highlight = true.
Token types (15 generic types mapped from syntect scopes):
| id | type | id | type | id | type |
|---|---|---|---|---|---|
| 0 | other | 5 | function | 10 | constant |
| 1 | keyword | 6 | type | 11 | builtin |
| 2 | string | 7 | operator | 12 | entity |
| 3 | comment | 8 | punctuation | 13 | markup |
| 4 | number | 9 | variable | 14 | regex |
Host consumption (Swift example):
// Read extra_data chunk kind=4 after kind=2 (language)
let tokens = parseHighlightChunk(extra)
var pos = 0
for (type, len) in tokens {
let range = NSRange(location: pos, length: Int(len))
attrString.addAttribute(.foregroundColor, value: highlightColors[Int(type)], range: range)
pos += Int(len)
}
Zero-cost when disabled: highlight is a compile-time feature flag. Without it, no syntect dependency, no binary size increase, no runtime overhead.
Supported languages: all in Sublime Text syntax definitions (100+ languages, including rust, python, swift, kotlin, bash, javascript, c, c++, java, go, etc.).
Integration Checklist
When integrating code highlighting, ensure all three steps are done:
-
Enable compile-time feature
cargo build --features highlight --releaseWithout
--features highlight, syntect is not compiled and no highlight chunk is produced. Binary size impact: ~1.2MB (iOS.a). -
Enable runtime option
let mut opts = default; opts.highlight = true; // default is false let output = to_spans_with_options;Or via FFI: pass
highlight=1tofastmarkdown_to_spans_ex. -
Consume the highlight chunk on the host (Swift/Kotlin) The
extra_datacontainskind=4chunks (one per code block, immediately after thekind=2language chunk). Parse the chunk format and apply colors to your attributed text. See the Swift example above.
License
Copyright 2025 xiefujin (490021684@qq.com)
Licensed under the Apache License, Version 2.0. See LICENSE for the full text.