diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,11 @@
+# Changelog
+
+## 0.2.0.0 -- 2026-12-02
+
+Initial release.
+
+- CommonMark rendering (`MarkdownDoc`, `parseMarkdown`, `markdown`, `markdownConfigured`) with GitHub tables, task lists, strikethrough, autolinks, code blocks, quotes, headings, and clickable links.
+- Incremental streaming support (`appendMarkdown`): re-parses only the trailing blocks affected by appended text and caches unchanged block rich-text segments in a bounded `MarkdownCache` (`newMarkdownCache`).
+- Customizable block and inline styling via `MarkdownConfig` (`mdBlock`, `mdInlineCode`, `mdInlineCodeBackground`, `mdCodeBlock`, `mdQuote`, `mdTableCell`), plus `markdownSource` and `markdownImages` helpers.
+- The `sdl` Cabal flag (for the streaming example) is off by default so the library requires neither `nano-ui-sdl` nor SDL3.
+- Builds with GHC 9.10 through 9.14 (`base >=4.20 && <4.23`).
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2026 goolord
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,62 @@
+# nano-ui-markdown
+
+CommonMark rendering for [nano-ui](https://github.com/goolord/nano-ui), backed by [commonmark](https://hackage.haskell.org/package/commonmark) (with GitHub tables, task lists, strikethrough, and autolinks) and incremental appends for streamed text. Backend-independent.
+
+```haskell
+{-# LANGUAGE OverloadedStrings #-}
+
+import Control.Monad (unless)
+import Data.Foldable (for_)
+import Data.Text qualified as T
+import NanoUI (NanoUI, label, readVar, useVar, writeVar)
+import NanoUI.Markdown
+
+readme :: MarkdownDoc
+readme = parseMarkdown "# Hello\n\nSome *emphasis*, `code`, and [a link](https://example.com)."
+
+-- Allocate cache <- newMarkdownCache once during setup.
+view :: MarkdownCache -> NanoUI ()
+view cache = do
+  lastLinkVar <- useVar ""
+  clicked <- markdown cache readme
+  for_ clicked (writeVar lastLinkVar)
+  lastLink <- readVar lastLinkVar
+  unless (T.null lastLink) $ label ("Clicked " <> lastLink)
+```
+
+`markdown` returns `Just url` on the frame a link is clicked. Parse static Markdown once and hold the `MarkdownDoc` rather than reparsing every frame.
+
+## Incremental streaming
+
+`appendMarkdown chunk doc` produces the same AST as reparsing from scratch while only reparsing the trailing block (plain words appended to a paragraph skip the parser altogether). Unchanged earlier blocks keep their widget IDs and skip re-measurement and repainting. Concatenate chunks arriving within a single frame into one `appendMarkdown` call.
+
+```haskell
+-- Allocate stream <- newStream once during setup.
+replyView :: MarkdownCache -> Stream Int MarkdownDoc -> Client -> Int -> NanoUI ()
+replyView cache stream client replyId = do
+  doc <- useStream stream replyId emptyMarkdown $ \update ->
+    onToken client (\token -> update (appendMarkdown token))
+  void (markdown cache doc)
+```
+
+## Customization
+
+Use `markdownConfigured cache config doc` to override fonts, colors, images, and block rendering (`Nothing` fields fall back to the active theme):
+
+```haskell
+markdownConfigured
+  cache
+  defaultMarkdownConfig
+    { mdText = fontSize 15
+    , mdImage = \src -> lookup src loadedImages
+    , mdInlineCodeBackground = Just (colorRGBA 60 64 72 255)
+    , mdCodeBlock = background (colorRGBA 30 32 36 255)
+    }
+  doc
+```
+
+Use `markdownImages` to collect image URLs for preloading, and override `mdBlock` to replace specific block types (such as custom syntax highlighting or async image loading) while delegating everything else. See `MarkdownConfig` in `NanoUI.Markdown` for the full list of fields.
+
+## Documentation
+
+- [The nano-ui Book: Markdown](https://goolord.github.io/nano-ui/book/packages/index.html#markdown): Streaming, styling, and custom block renderer examples.
diff --git a/examples/ChatDemo.hs b/examples/ChatDemo.hs
new file mode 100644
--- /dev/null
+++ b/examples/ChatDemo.hs
@@ -0,0 +1,143 @@
+-- | A chat reply streamed into a Markdown widget a few characters at a time
+-- with 'useStream', as a language model's answer arrives.
+module ChatDemo (newChatDemoUi) where
+
+import Control.Concurrent (threadDelay)
+import Control.Monad (forM_, unless, when)
+import Data.Foldable (for_)
+import Data.Text (Text)
+import Data.Text qualified as T
+import NanoUI
+  ( NanoUI
+  , ScrollMetrics (..)
+  , V2 (..)
+  , background
+  , button
+  , card
+  , colorRGBA
+  , columnWith
+  , currentId
+  , fillH
+  , fillW
+  , flex
+  , gap
+  , getScrollMetrics
+  , heading
+  , label
+  , maxW
+  , muted
+  , padAll
+  , padXY
+  , panelStyle
+  , panelWith
+  , rowWith
+  , scrollWith
+  , setScrollOffset
+  , styled
+  , tight
+  , toolbar
+  , useStream
+  , Stream
+  , newStream
+  , modifyVar
+  , readVar
+  , useVar
+  , v2Y
+  , whenM
+  , writeVar
+  )
+import NanoUI.Markdown
+import NanoUI.Var (peekVar)
+
+-- | The reply in 4-character tokens.
+tokens :: [Text]
+tokens = T.chunksOf 4 reply
+
+tokensPerSecond :: Int
+tokensPerSecond = 60
+
+newChatDemoUi :: IO (NanoUI ())
+newChatDemoUi = chatDemoUi <$> newStream <*> newMarkdownCache
+
+chatDemoUi :: Stream Int (Int, MarkdownDoc) -> MarkdownCache -> NanoUI ()
+chatDemoUi stream cache = do
+  -- A worker thread appends tokens; the view reads the token count and the
+  -- document so far. Replay restarts the stream under a new key.
+  replays <- useVar (0 :: Int)
+  replay <- readVar replays
+  (arrived, doc) <- useStream stream replay (0 :: Int, emptyMarkdown) $ \update ->
+    forM_ tokens $ \token -> do
+      threadDelay (1000000 `div` tokensPerSecond)
+      -- Force the document here, so the parse runs on this thread.
+      update (\(n, d) -> let !n' = n + 1; !d' = appendMarkdown token d in (n', d'))
+  let streaming = arrived < length tokens
+  -- Token count shown last frame, used to detect growth. Only this frame's
+  -- scrolling depends on it, so it is peeked, not read.
+  shownCount <- useVar (0 :: Int)
+  grew <- (/= arrived) <$> peekVar shownCount
+  writeVar shownCount arrived
+  lastLink <- useVar ("" :: Text)
+  columnWith (fillW . fillH . padAll 16 . gap 12) $ do
+    toolbar $ do
+      heading "Chat"
+      flex
+      muted (if streaming then "Receiving..." else T.pack (show (length tokens)) <> " tokens")
+      whenM (button "Replay") (modifyVar replays (+ 1))
+    sid <- currentId
+    metrics <- getScrollMetrics sid
+    -- Stick to the bottom as text arrives, unless scrolled up.
+    for_ metrics $ \m ->
+      when (grew && v2Y (scrollOffset m) >= v2Y (scrollRange m) - 24) $
+        setScrollOffset sid (V2 0 1e9)
+    scrollWith (fillW . fillH) $
+      columnWith (fillW . padAll 4 . gap 12) $ do
+        styled (panelStyle (background (colorRGBA 58 64 86 255))) $
+          rowWith (fillW . tight) $ do
+            flex
+            panelWith (padXY 12 8 . maxW 520) $
+              label "How do I stream Markdown into a nano-ui view?"
+        card $ do
+          target <- markdown cache doc
+          for_ target (writeVar lastLink)
+    link <- readVar lastLink
+    unless (T.null link) $ muted ("Clicked link: " <> link)
+
+reply :: Text
+reply =
+  T.unlines
+    [ "## Streaming Markdown"
+    , ""
+    , "Receive the reply in a `useStream` producer, and **append** each token"
+    , "to a `MarkdownDoc` there:"
+    , ""
+    , "```haskell"
+    , "-- Allocate stream <- newStream once during setup."
+    , "doc <- useStream stream replyId emptyMarkdown $ \\update ->"
+    , "  onToken client $ \\token -> update (appendMarkdown token)"
+    , "```"
+    , ""
+    , "`appendMarkdown` keeps the blocks that are already *finished*, so each"
+    , "token re-parses only the unfinished end of the reply, and it does so on"
+    , "the producer's thread."
+    , ""
+    , "### What it draws"
+    , ""
+    , "1. Headings, paragraphs, **strong**, *emphasis* and ~~strikethrough~~"
+    , "2. Lists, tight or loose, nested:"
+    , "   - [x] with task items"
+    , "   - [ ] and ones still to do"
+    , "3. Links such as [the nano-ui repository](https://github.com/goolord/nano-ui)"
+    , "   and bare ones like https://hackage.haskell.org"
+    , ""
+    , "> Block quotes, too.  "
+    , "> Each finished block keeps its widget ids, so its text is not laid out again."
+    , ""
+    , "| Block | Cached |"
+    , "|:------|:------:|"
+    , "| Finished | yes |"
+    , "| Open | no |"
+    , ""
+    , "---"
+    , ""
+    , "Click a link to see its destination below."
+    ]
diff --git a/examples/Main.hs b/examples/Main.hs
new file mode 100644
--- /dev/null
+++ b/examples/Main.hs
@@ -0,0 +1,19 @@
+module Main (main) where
+
+import ChatDemo (newChatDemoUi)
+import NanoUI (Key (KeyEscape), Pressable (..), Size (..), WindowSettings (..), defaultWindowSettings)
+import NanoUI.Backend.Sdl
+  ( SdlOptions (..)
+  , defaultSdlOptions
+  , runSdlApp
+  )
+
+main :: IO ()
+main = do
+  chatDemoUi <- newChatDemoUi
+  runSdlApp
+    defaultSdlOptions
+      { sdlWindowSettings = defaultWindowSettings {wsTitle = "nano-ui-markdown example", wsSize = Size 900 760}
+      , sdlAppShouldQuit = pressedOnceIn KeyEscape
+      }
+    chatDemoUi
diff --git a/lib/NanoUI/Markdown.hs b/lib/NanoUI/Markdown.hs
new file mode 100644
--- /dev/null
+++ b/lib/NanoUI/Markdown.hs
@@ -0,0 +1,81 @@
+-- |
+-- Module      : NanoUI.Markdown
+-- Description : Markdown documents drawn with nano-ui
+-- Copyright   : (c) 2026 Zachary Churchill
+-- License     : MIT
+-- Maintainer  : zacharyachurchill@gmail.com
+--
+-- Markdown drawn with nano-ui's rich text and layout. Parse a document once,
+-- keep it in your model, and draw it every frame. 'markdown' returns the
+-- link clicked this frame, if any:
+--
+-- Allocate @cache <- newMarkdownCache@ during component setup.
+--
+-- > view :: MarkdownCache -> MarkdownDoc -> NanoUI ()
+-- > view cache doc = do
+-- >   lastLink <- useVar ""
+-- >   clicked <- markdown cache doc
+-- >   for_ clicked (writeVar lastLink)
+-- >   link <- readVar lastLink
+-- >   unless (T.null link) $ label ("Clicked " <> link)
+--
+-- Grow a streamed reply with 'appendMarkdown'. When tokens arrive on a
+-- worker thread, nano-ui's @useStream@ can append each one there:
+--
+-- Allocate @stream <- newStream@ once during setup.
+--
+-- > doc <- useStream stream replyId emptyMarkdown $ \update ->
+-- >   onToken client (\token -> update (appendMarkdown token))
+--
+-- On the UI thread, append a frame's tokens in one call:
+--
+-- > onTokens :: [Text] -> MarkdownDoc -> MarkdownDoc
+-- > onTokens tokens = appendMarkdown (T.concat tokens)
+--
+-- The built-in renderer lets users select and copy text in paragraphs,
+-- headings, table cells and code blocks. Select All and Copy act on the
+-- focused text block.
+--
+-- Appending reparses only the last top-level block, or less when the text
+-- ends inside a list, table, fenced code or block quote.
+-- "NanoUI.Markdown.Document" describes when more is reparsed.
+--
+-- 'mdBlock' overrides block drawing at any depth, given the widget's own
+-- drawing to fall back to or wrap:
+--
+-- > highlighted :: MarkdownConfig
+-- > highlighted = defaultMarkdownConfig {mdBlock = \own -> \case
+-- >   CodeBlock "haskell" code -> Nothing <$ panel (richText (highlight code))
+-- >   b -> own b}
+--
+-- Parsing uses @commonmark@ with GitHub tables, task lists (in bullet
+-- lists), strikethrough and autolinks from @commonmark-extensions@. Raw HTML
+-- is shown as text, with comments removed.
+module NanoUI.Markdown
+  ( -- * Documents
+    MarkdownDoc
+  , emptyMarkdown
+  , parseMarkdown
+  , appendMarkdown
+  , markdownBlocks
+  , markdownSource
+  , markdownImages
+  , parseMarkdownBlocks
+
+    -- * Drawing
+  , markdown
+  , markdownWith
+  , MarkdownCache
+  , newMarkdownCache
+  , markdownCacheSize
+  , markdownConfigured
+  , MarkdownConfig (..)
+  , defaultMarkdownConfig
+
+    -- * Syntax
+  , module NanoUI.Markdown.Syntax
+  ) where
+
+import NanoUI.Markdown.Document
+import NanoUI.Markdown.Syntax
+import NanoUI.Markdown.Widget
diff --git a/lib/NanoUI/Markdown/Document.hs b/lib/NanoUI/Markdown/Document.hs
new file mode 100644
--- /dev/null
+++ b/lib/NanoUI/Markdown/Document.hs
@@ -0,0 +1,397 @@
+-- | An incrementally parsed Markdown document, for chat messages that arrive
+-- a few tokens at a time.
+--
+-- Appending gives the same blocks as parsing the whole text:
+--
+-- > markdownBlocks (appendMarkdown b (parseMarkdown a)) == markdownBlocks (parseMarkdown (a <> b))
+--
+-- The document keeps the blocks that appended text cannot change and reparses
+-- only the rest. The rest starts at the last complete line that parses the
+-- same way on its own: a top-level block not directly under a paragraph, or,
+-- inside a top-level block, a list item after the first, a table row, a line
+-- of fenced code (reparsed after the table header or the fence), or a block
+-- quote's block after the first that is not directly under a paragraph. So an
+-- append parses the new text plus the last list item, table row, code line or
+-- quote block, or otherwise the last block. Joining that onto the block's
+-- earlier part still copies the code, or walks the items, rows or quote
+-- blocks, before it: quick next to a parse, but it grows with the block.
+-- Plain words added to a paragraph that ends the text join its last line
+-- without a parse (see 'plainAppend').
+--
+-- The rest is parsed with the link reference definitions before it. If the
+-- rest's new definitions differ from those the closed blocks were parsed
+-- with, the whole text is reparsed, since those blocks may use them. This
+-- happens on every append while a message ends in a definition.
+module NanoUI.Markdown.Document
+  ( MarkdownDoc
+  , emptyMarkdown
+  , parseMarkdown
+  , appendMarkdown
+  , markdownBlocks
+  , markdownSource
+  , markdownImages
+  , parseMarkdownBlocks
+  ) where
+
+import Control.DeepSeq (NFData, deepseq, rnf)
+import Control.Monad (guard)
+import Data.Char (isAlpha, isAlphaNum, isAscii)
+import Data.Containers.ListUtils (nubOrd)
+import Data.Foldable (toList)
+import Data.List (find, unsnoc)
+import Data.Map.Strict qualified as M
+import Data.Maybe (fromMaybe, isJust, listToMaybe, mapMaybe)
+import Data.Sequence (Seq)
+import Data.Sequence qualified as Seq
+import Data.Text (Text)
+import Data.Text qualified as T
+import Data.Text.Normalize (NormalizationMode (NFC), normalize)
+import Data.Text.Lazy qualified as TL
+import GHC.Generics (Generic)
+import NanoUI.Internal.Store (ptrEq)
+import NanoUI.Markdown.Internal.Parse
+import NanoUI.Markdown.Syntax
+
+-- | A parsed document. It keeps the blocks that appending cannot change and
+-- reparses the rest on append. Documents are equal when their texts are.
+data MarkdownDoc = MarkdownDoc
+  { docLength :: !Int
+  -- ^ Length of the text.
+  , docDone :: ![Text]
+  -- ^ Text of the closed blocks, in pieces, newest first.
+  , docClosed :: !(Seq Block)
+  -- ^ The closed blocks.
+  , docOpen :: !Open
+  -- ^ The block the rest starts inside, up to where the rest begins.
+  , docKnown :: !Refs
+  -- ^ Link reference definitions before the rest.
+  , docPending :: !Refs
+  -- ^ Definitions in the rest whose labels are not defined before it. The
+  -- closed blocks were parsed with these.
+  , docRest :: !Text
+  -- ^ The text after the closed blocks.
+  , docLast :: ![Block]
+  -- ^ Blocks of the rest; the first continues 'docOpen'.
+  , docTail :: !Tail
+  -- ^ Whether the rest ends in a paragraph 'plainAppend' can add to.
+  }
+
+instance Eq MarkdownDoc where
+  a == b =
+    docLength a == docLength b
+      && (samePieces || TL.fromChunks (pieces a) == TL.fromChunks (pieces b))
+    where
+      -- A document kept in a model is compared with itself on every update,
+      -- so its pieces are the same objects.
+      samePieces = case (a, b) of
+        (MarkdownDoc {docDone = doneA, docRest = restA}, MarkdownDoc {docDone = doneB, docRest = restB}) ->
+          ptrEq doneA doneB && ptrEq restA restB
+
+instance Show MarkdownDoc where
+  showsPrec d doc = showParen (d > 10) (showString "parseMarkdown " . showsPrec 11 (markdownSource doc))
+
+-- | The text of a document, in pieces.
+pieces :: MarkdownDoc -> [Text]
+pieces doc = reverse (docRest doc : docDone doc)
+
+-- | The part of a block before the rest, when the rest starts inside it.
+data Open
+  = -- | The rest starts at a block boundary.
+    Fresh
+  | -- | A list's items so far, and whether they keep it tight.
+    InList !ListType !Bool ![ListItem]
+  | -- | A block quote's blocks.
+    InQuote ![Block]
+  | -- | A fenced code block's opening fence line, and its code so far with line endings.
+    InCode !Text !Text
+  | -- | A table's header and delimiter lines, and its rows so far.
+    InTable !Text ![[[Span]]]
+  deriving (Generic)
+
+instance NFData Open
+
+-- | Whether 'plainAppend' can add to the end of the rest.
+data Tail
+  = NoTail
+  | -- | The rest ends in a top-level paragraph that defines no link
+    -- references and whose first line does not start with @[@, as it could
+    -- still become a definition whose title closes later. The flag says
+    -- whether the paragraph is one line long.
+    TailPara !Bool
+
+-- | Lines prepended to the rest when parsing it, to restart the block.
+reopen :: Open -> Text
+reopen = \case
+  InCode fence _ -> fence
+  InTable header _ -> header
+  _ -> ""
+
+-- | A document with no text.
+emptyMarkdown :: MarkdownDoc
+emptyMarkdown = MarkdownDoc 0 [] Seq.empty Fresh mempty mempty "" [] NoTail
+
+-- | Parse a whole document. Keep the result in your model rather than
+-- parsing the text again every frame.
+parseMarkdown :: Text -> MarkdownDoc
+parseMarkdown t = fromMaybe unparsed (resume new t)
+  where
+    new = emptyMarkdown {docLength = T.length t}
+    -- If commonmark fails, show the text as is.
+    unparsed = new {docRest = t, docLast = [Paragraph [Str (chomp (unixLines t))]]}
+
+-- | The blocks of a document.
+markdownBlocks :: MarkdownDoc -> [Block]
+markdownBlocks doc = toList (docClosed doc) ++ docLast doc
+
+-- | The document's full text, which '==' compares.
+markdownSource :: MarkdownDoc -> Text
+markdownSource = T.concat . pieces
+
+-- | Image sources in the document, without duplicates, in order of first
+-- appearance, including those in quotes, lists, tables and links. Useful for
+-- loading images before they scroll into view.
+markdownImages :: MarkdownDoc -> [Text]
+markdownImages = nubOrd . concatMap blockImages . markdownBlocks
+  where
+    blockImages = \case
+      Paragraph xs -> spanImages xs
+      Heading _ xs -> spanImages xs
+      BlockQuote bs -> concatMap blockImages bs
+      List _ _ items -> concatMap (concatMap blockImages . itemBlocks) items
+      Table _ header rows -> concatMap spanImages (header ++ concat rows)
+      _ -> []
+    spanImages = concatMap $ \case
+      Image src _ alt -> src : spanImages alt
+      Emph xs -> spanImages xs
+      Strong xs -> spanImages xs
+      Strike xs -> spanImages xs
+      Link _ _ xs -> spanImages xs
+      _ -> []
+
+-- | The blocks of a text: @'markdownBlocks' . 'parseMarkdown'@.
+parseMarkdownBlocks :: Text -> [Block]
+parseMarkdownBlocks = markdownBlocks . parseMarkdown
+
+-- | Append text to a document. This parses the new text plus the rest after
+-- the closed blocks (see "NanoUI.Markdown.Document"), or the whole text when
+-- the rest changes a link reference definition, but nothing for plain words
+-- added to a paragraph. Append a frame's tokens in one call rather than one
+-- at a time.
+appendMarkdown :: Text -> MarkdownDoc -> MarkdownDoc
+appendMarkdown new doc
+  | T.null new = doc
+  | Just doc' <- plainAppend new doc = doc'
+  | otherwise =
+      fromMaybe
+        (parseMarkdown (markdownSource doc <> new))
+        (resume doc {docLength = docLength doc + T.length new} (docRest doc <> new))
+
+-- | Parse a new rest after the document's closed blocks. 'Nothing' means the
+-- whole text must be reparsed: the rest changed a link reference definition
+-- the closed blocks were parsed with, a continued table outgrew 'fits', or
+-- commonmark failed.
+resume :: MarkdownDoc -> Text -> Maybe MarkdownDoc
+resume doc rest = do
+  let open = docOpen doc
+      reopened = reopen open
+      skip = T.count "\n" reopened
+      Parsed input complete parsed = parseLines (docKnown doc) (reopened <> rest)
+  fresh <- parsed
+  rnf (mapMaybe nodeBlock fresh) `seq` pure ()
+  let freshRefs = foldMap nodeRefs fresh
+      refs = freshRefs `M.difference` docKnown doc
+  guard (null (docDone doc) || refs == docPending doc)
+  nodes <- case (fresh, open) of
+    (n : ns, _) -> (: ns) <$> continue open n
+    ([], Fresh) -> Just []
+    _ -> Nothing
+  let usable (Cut line _ _ open') = line <= complete && isJust open'
+      after (Cut line _ _ _) = line > skip + 1
+  pure $ case find usable (takeWhile after (cuts input open nodes)) of
+    Just (Cut line k closingRefs (Just open')) ->
+      let (closing, opened) = splitAt k nodes
+          known = docKnown doc <> foldMap nodeRefs closing <> closingRefs
+          (done, rest') = splitLines (line - skip - 1) rest
+       in open' `deepseq`
+            doc
+              { docDone = done `seq` done : docDone doc
+              , docClosed = docClosed doc <> Seq.fromList (mapMaybe nodeBlock closing)
+              , docOpen = open'
+              , docKnown = known
+              , docPending = freshRefs `M.difference` known
+              , docRest = rest'
+              , docLast = spine (mapMaybe nodeBlock opened)
+              , docTail = tailOf input opened
+              }
+    _ -> doc {docRest = rest, docPending = refs, docLast = spine (mapMaybe nodeBlock nodes), docTail = tailOf input nodes}
+
+-- | The 'Tail' of a rest, given its blocks and the text they were parsed
+-- from.
+tailOf :: Text -> [Node] -> Tail
+tailOf input nodes = case unsnoc nodes of
+  Just (_, Node {nodeLines = (first, end), nodeBlock = Just (Paragraph _), nodeShape = Para})
+    | T.take 1 (T.dropWhile isBlank (snd (splitLines (first - 1) input))) /= "[" ->
+        TailPara (first == end)
+  _ -> NoTail
+
+-- | Add plain words to the paragraph that ends the rest without parsing,
+-- when the parse would only make the paragraph's last 'Str' longer by them.
+-- That holds when the words have no character Markdown gives a meaning to
+-- (such as the @\@@ of an email address or the @/@ of a URL) and no @www@,
+-- which starts a web address (@www.@ or @www-@); the paragraph's last line
+-- starts with a letter, or on its first line also a digit, so the words
+-- cannot turn it into the start of a block; and the words follow a space, or
+-- are letters with closing punctuation after a letter, so they cannot close
+-- or change an inline before them; and they start with an ASCII character
+-- and are in NFC, as the parse leaves text. 'Nothing' when it may not hold.
+plainAppend :: Text -> MarkdownDoc -> Maybe MarkdownDoc
+plainAppend new doc = do
+  TailPara oneLine <- Just (docTail doc)
+  guard (T.all plain new && not ("www" `T.isInfixOf` T.toLower new))
+  -- The parse puts its text in NFC. Words in NFC that start with an ASCII
+  -- character, which nothing before it composes with, join the text before
+  -- them unchanged.
+  (first, _) <- T.uncons new
+  guard (isAscii first && normalize NFC new == new)
+  (blocks, Paragraph xs) <- unsnoc (docLast doc)
+  (before, Str s) <- unsnoc xs
+  -- A space that ends the Str (from an entity, or before an HTML comment the
+  -- parse dropped) is not one the parse strips from the end of the text.
+  (_, end) <- T.unsnoc s
+  guard (not (isBlank end))
+  let line = T.takeWhileEnd (\c -> c /= '\n' && c /= '\r') (docRest doc)
+      spaces = T.takeWhileEnd isBlank line
+  (lead, _) <- T.uncons (T.dropWhile isBlank line)
+  guard (if oneLine then isAlphaNum lead else isAlpha lead)
+  guard $
+    not (T.null spaces)
+      || T.take 1 new == " "
+      || (isAlpha end && joins (T.takeWhile (not . isBlank) new))
+  let !s' = T.dropWhileEnd isBlank (s <> spaces <> new)
+  pure
+    doc
+      { docLength = docLength doc + T.length new
+      , docRest = docRest doc <> new
+      , docLast = spine (blocks ++ [Paragraph (spine (before ++ [Str s']))])
+      }
+  where
+    plain c = isAlphaNum c || c `elem` (" ,;?!:.'\"-" :: String)
+    -- Letters, digits, apostrophes and hyphens, then closing punctuation.
+    joins w =
+      T.all (\c -> isAlphaNum c || c == '\'' || c == '-') $
+        T.dropWhileEnd (`elem` (".,?!:\"" :: String)) w
+
+-- | A space or a tab, which a line's text is indented and ended with.
+isBlank :: Char -> Bool
+isBlank c = c == ' ' || c == '\t'
+
+-- | Force a list's spine and elements so it retains nothing of the parse.
+spine :: [a] -> [a]
+spine xs = foldr seq () xs `seq` xs
+
+-- | Join the rest's first block onto the open block's earlier part. 'Nothing'
+-- if a continued table outgrows 'fits', or if the block does not continue the
+-- open one (which should not happen).
+continue :: Open -> Node -> Maybe Node
+continue open n = case (open, nodeBlock n, nodeShape n) of
+  (Fresh, _, _) -> Just n
+  (InList ty tight items, Just (List _ tight' items'), _) -> joined (List ty (tight && tight') (items ++ items'))
+  (InQuote bs, Just (BlockQuote bs'), _) -> joined (BlockQuote (bs ++ bs'))
+  (InCode _ code, Just (CodeBlock info _), CodeLines more) -> joined (CodeBlock info (chomp (code <> more)))
+  (InTable _ rows, Just (Table aligns header rows'), _)
+    | allRows <- rows ++ rows', fits aligns allRows -> joined (Table aligns header allRows)
+  _ -> Nothing
+  where
+    joined b = b `seq` Just n {nodeBlock = Just b}
+
+-- | Whether commonmark-extensions keeps all of a table's rows. It ends a table
+-- after filling in 200000 missing cells, and a table parsed in parts would
+-- count those per part.
+fits :: [CellAlign] -> [[[Span]]] -> Bool
+fits aligns rows = length rows * length aligns <= 200000
+
+-- | A line where the rest can start.
+data Cut
+  = Cut
+      !Int
+      -- ^ Line number in the parsed text.
+      !Int
+      -- ^ Number of blocks closed before the line.
+      Refs
+      -- ^ Link reference definitions in the next block, before the line.
+      (Maybe Open)
+      -- ^ The next block's part before the line, or 'Nothing' if the rest
+      -- cannot start there.
+
+-- | Lines where the rest can start, last first: at each block after the
+-- first, and inside blocks.
+cuts :: Text -> Open -> [Node] -> [Cut]
+cuts input open nodes =
+  concat
+    [ inside input (if k == 0 then open else Fresh) k n ++ [Cut (start n) k mempty (Just Fresh) | k > 0, opens prev n]
+    | (k, prev, n) <- reverse (withPrev nodes)
+    ]
+
+-- | Lines inside a block where the rest can start, last first: a list item
+-- after the first, a fenced code line, a table row, or a block quote's block
+-- after the first. The block continues @before@.
+inside :: Text -> Open -> Int -> Node -> [Cut]
+inside input before k n = case (nodeBlock n, nodeShape n) of
+  (Just (List ty _ items), Items own) ->
+    [ Cut line k (foldMap nodeRefs (concat (take i own))) $ do
+        tight <- tightTo line
+        Just (InList ty (tight && tightBefore) (take (length items - length own + i) items))
+    | (i, Node {nodeLines = (line, _)} : _) <- reverse (drop 1 (zip [0 ..] own))
+    ]
+  (Just CodeBlock {}, CodeLines code)
+    -- Fenced code spans more lines than its code, counting the fences.
+    | size <- T.count "\n" code
+    , end - first >= size ->
+        [ Cut line k mempty (Just (InCode (linesAt first 1) (codeBefore <> fst (splitLines (line - first - 1) code))))
+        | line <- [first + size, first + size - 1 .. first + 1]
+        ]
+  (Just (Table aligns _ rows), _)
+    | fits aligns rows ->
+        [ Cut line k mempty (Just (InTable (linesAt first 2) (take (length rows - (end - line + 1)) rows)))
+        | line <- [end, end - 1 .. first + 2]
+        ]
+  (Just (BlockQuote bs), Quote own) ->
+    [ Cut (start m) k (foldMap nodeRefs (take j own)) (Just (InQuote (take (length bs - length (mapMaybe nodeBlock (drop j own))) bs)))
+    | (j, prev, m) <- reverse (withPrev own)
+    , j > 0
+    , opens prev m
+    ]
+  _ -> []
+  where
+    (first, end) = nodeLines n
+    linesAt from count = fst (splitLines count (snd (splitLines (from - 1) input)))
+    -- Whether the items before the one on @line@ keep the list tight. Parsed
+    -- up to that line, the list ends with that item, one line long.
+    tightTo line = case parsedNodes (parseLines mempty (fst (splitLines line input))) >>= listToMaybe . reverse of
+      Just Node {nodeBlock = Just (List _ tight _)} -> Just tight
+      _ -> Nothing
+    tightBefore = case before of
+      InList _ tight _ -> tight
+      _ -> True
+    codeBefore = case before of
+      InCode _ code -> code
+      _ -> ""
+
+-- | Whether a block parses the same on its own, given the block before it, so
+-- the rest can start there. A line directly under a paragraph may continue
+-- it, turn it into a heading (@===@, @---@) or a table header (a delimiter
+-- row), or fail to interrupt it (an ordered item not numbered 1, an empty
+-- task item, HTML of type 7). So the paragraph must end before the line
+-- above. Any other previous block has ended by then, or is a list, which only
+-- an item continues.
+opens :: Maybe Node -> Node -> Bool
+opens prev n = case prev of
+  Just Node {nodeShape = Para, nodeLines = (_, end)} -> end < start n - 1
+  _ -> True
+
+start :: Node -> Int
+start = fst . nodeLines
+
+-- | Blocks numbered from 0, each paired with the one before it.
+withPrev :: [Node] -> [(Int, Maybe Node, Node)]
+withPrev ns = zip3 [0 ..] (Nothing : map Just ns) ns
diff --git a/lib/NanoUI/Markdown/Internal/Parse.hs b/lib/NanoUI/Markdown/Internal/Parse.hs
new file mode 100644
--- /dev/null
+++ b/lib/NanoUI/Markdown/Internal/Parse.hs
@@ -0,0 +1,265 @@
+-- | Parse Markdown into "NanoUI.Markdown.Syntax" using @commonmark@ plus the
+-- GitHub extensions from @commonmark-extensions@ (tables, task lists,
+-- strikethrough, autolinks). Also records what "NanoUI.Markdown.Document"
+-- needs to reparse only a text's tail: each block's lines, its children and
+-- its link reference definitions.
+module NanoUI.Markdown.Internal.Parse
+  ( Parsed (..)
+  , Node (..)
+  , Shape (..)
+  , Refs
+  , parseLines
+  , unixLines
+  , splitLines
+  , chomp
+  ) where
+
+import Commonmark qualified as C
+import Commonmark.Blocks (BPState (..), BlockParser)
+import Commonmark.Entity (lookupEntity)
+import Commonmark.Extensions
+  ( ColAlignment (..)
+  , HasPipeTable (..)
+  , HasStrikethrough (..)
+  , HasTaskList (..)
+  , autolinkSpec
+  , pipeTableSpec
+  , strikethroughSpec
+  , taskListSpec
+  )
+import Commonmark.ReferenceMap (LinkInfo (..), ReferenceMap (..), emptyReferenceMap, insertReference)
+import Data.Char (isSpace)
+import Data.Functor.Identity (Identity, runIdentity)
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as M
+import Data.Maybe (fromMaybe, mapMaybe)
+import Data.Monoid (Endo (..))
+import Data.Text (Text)
+import Data.Text qualified as T
+import NanoUI.Markdown.Syntax
+import Text.Parsec (updateState)
+
+data Parsed = Parsed
+  { parsedText :: !Text
+  -- ^ The parsed text, with line endings normalised to @\\n@.
+  , parsedComplete :: !Int
+  -- ^ Number of complete lines: all but a final unterminated one.
+  , parsedNodes :: !(Maybe [Node])
+  -- ^ Top-level blocks, or 'Nothing' if commonmark failed.
+  }
+
+-- | A block with its source lines and children.
+data Node = Node
+  { nodeLines :: !(Int, Int)
+  -- ^ First and last line, 1-based.
+  , nodeBlock :: !(Maybe Block)
+  -- ^ 'Nothing' for link reference definitions and HTML comments, which
+  -- render nothing.
+  , nodeRefs :: !Refs
+  -- ^ Link reference definitions inside the block.
+  , nodeShape :: !Shape
+  }
+  deriving (Show)
+
+-- | What a reparse starting inside a block needs to know about it.
+data Shape
+  = -- | A paragraph or its leading link reference definitions; the next line
+    -- may continue it.
+    Para
+  | -- | Code including the final line ending.
+    CodeLines !Text
+  | -- | Each list item's blocks. They carry the item's line range.
+    Items ![[Node]]
+  | -- | A block quote's blocks.
+    Quote ![Node]
+  | Other
+  deriving (Show)
+
+-- | Link reference definitions: normalised label to destination and title.
+-- The first definition of a label wins, matching left-biased 'M.union'.
+type Refs = Map Text (Text, Text)
+
+-- | Parse a text, given the link reference definitions from the text before
+-- it. Raw HTML is kept as text, minus comments.
+parseLines :: Refs -> Text -> Parsed
+parseLines before src = Parsed unix (T.count "\n" unix) nodes
+  where
+    -- Normalise to @\\n@ so line numbers match commonmark's and code has no
+    -- @\\r@. Terminate the last line: otherwise commonmark drops a final
+    -- table row and adds an empty paragraph after a heading or closing fence.
+    -- 'splitLines' accepts the same line endings.
+    unix = unixLines src
+    text = if "\n" `T.isSuffixOf` unix then unix else T.snoc unix '\n'
+    nodes = case runIdentity (C.commonmarkWith syntax "" text) of
+      Right (Blocks ns) -> Just ns
+      Left _ -> Nothing
+    syntax = extensions <> mempty {C.syntaxFinalParsers = [defined before]}
+
+-- | Normalise @\\r\\n@ and @\\r@ line endings to @\\n@.
+unixLines :: Text -> Text
+unixLines = T.replace "\r" "\n" . T.replace "\r\n" "\n"
+
+-- | CommonMark with GitHub extensions, built once rather than per parse. Task
+-- items must precede core list items and tables follow core blocks.
+extensions :: C.SyntaxSpec Identity Spans Blocks
+extensions = taskListSpec <> strikethroughSpec <> autolinkSpec <> C.defaultSyntaxSpec <> pipeTableSpec
+
+-- | Merge definitions from earlier text into the reference map, taking
+-- priority, before commonmark parses inlines.
+defined :: Monad m => Refs -> BlockParser m Spans Blocks Blocks
+defined before = mempty <$ updateState add
+  where
+    add st = st {referenceMap = ReferenceMap (M.unionWith (++) refs (unReferenceMap (referenceMap st)))}
+    -- Let commonmark own its extension representation; our retained references
+    -- are the concrete Refs map, and enter through its typed insertion API.
+    refs = unReferenceMap $ M.foldlWithKey'
+      (\m label (url, title) -> insertReference label (LinkInfo url title [] Nothing) m)
+      emptyReferenceMap before
+
+-- | Split after the first @n@ lines, each ended by @\\n@, @\\r\\n@ or
+-- @\\r@.
+splitLines :: Int -> Text -> (Text, Text)
+splitLines n t = (T.dropEnd (T.length rest) t, rest)
+  where
+    rest = go n t
+    go k s
+      | k <= 0 = s
+      | otherwise = go (k - 1) (fromMaybe (T.drop 1 r) (T.stripPrefix "\r\n" r))
+      where
+        r = T.dropWhile (\c -> c /= '\n' && c /= '\r') s
+
+newtype Blocks = Blocks [Node]
+  deriving newtype (Semigroup, Monoid, Show)
+
+-- | One block. Its lines are filled in by 'C.ranged' after construction.
+node :: Maybe Block -> Refs -> Shape -> Blocks
+node b refs shape = Blocks [Node (0, 0) b refs shape]
+
+leaf :: Block -> Blocks
+leaf b = node (Just b) mempty Other
+
+blocks :: Blocks -> [Block]
+blocks (Blocks ns) = mapMaybe nodeBlock ns
+
+refsIn :: Blocks -> Refs
+refsIn (Blocks ns) = foldMap nodeRefs ns
+
+-- | Difference list, since the inline parser appends spans one at a time.
+newtype Spans = Spans (Endo [Span])
+  deriving newtype (Semigroup, Monoid)
+
+instance Show Spans where
+  showsPrec d = showsPrec d . spans
+
+-- | The spans with adjacent 'Str's merged.
+spans :: Spans -> [Span]
+spans (Spans f) = go (appEndo f [])
+  where
+    go xs = case span isStr xs of
+      ([], []) -> []
+      ([], x : rest) -> x : go rest
+      (strs, rest) -> [Str t | let t = T.concat [s | Str s <- strs], not (T.null t)] ++ go rest
+    isStr = \case
+      Str _ -> True
+      _ -> False
+
+one :: Span -> Spans
+one x = Spans (Endo (x :))
+
+wrap :: ([Span] -> Span) -> Spans -> Spans
+wrap f = one . f . spans
+
+-- | Drop one trailing line ending.
+chomp :: Text -> Text
+chomp t = fromMaybe t (T.stripSuffix "\n" t)
+
+-- | Strip HTML comments, as a browser hides them. @<!-->@ and @<!--->@ are
+-- empty comments. An unterminated comment runs to the end.
+uncomment :: Text -> Text
+uncomment t = case T.breakOn "<!--" t of
+  (before, "") -> before
+  (before, comment) -> before <> uncomment (afterComment (T.drop 4 comment))
+  where
+    afterComment body
+      | Just rest <- T.stripPrefix ">" body = rest
+      | Just rest <- T.stripPrefix "->" body = rest
+      | otherwise = T.drop 3 (snd (T.breakOn "-->" body))
+
+-- | A list whose items may carry task check boxes.
+listOf :: C.ListType -> C.ListSpacing -> [(Maybe Bool, Blocks)] -> Blocks
+listOf ty spacing items =
+  node
+    (Just (List kind (spacing == C.TightList) [ListItem task (blocks bs) | (task, bs) <- items]))
+    (refsIn (foldMap snd items))
+    (Items [ns | (_, Blocks ns) <- items])
+  where
+    kind = case ty of
+      C.BulletList c -> Bullet c
+      C.OrderedList start _ delim -> Ordered start (if delim == C.Period then '.' else ')')
+
+instance C.Rangeable Blocks where
+  -- Setext headings and tables list their defining line first, hence the
+  -- minimum. End positions are exclusive. commonmark ranges an item's blocks
+  -- again with the item's range, overwriting their own. Leading link
+  -- reference definitions keep their own lines (their second range is
+  -- empty), and the rest of the paragraph starts on the first definition's
+  -- line, so a reparse never starts between them.
+  ranged (C.SourceRange r) (Blocks ns) = case r of
+    [] -> Blocks ns
+    _ -> Blocks [n {nodeLines = (first, lst)} | n <- ns]
+    where
+      first = minimum (map (C.sourceLine . fst) r)
+      lst = maximum [C.sourceLine end - (if C.sourceColumn end == 1 then 1 else 0) | (_, end) <- r]
+
+instance C.Rangeable Spans where
+  ranged _ = id
+
+instance C.HasAttributes Blocks where
+  addAttributes _ = id
+
+instance C.HasAttributes Spans where
+  addAttributes _ = id
+
+instance C.IsBlock Spans Blocks where
+  paragraph s = node (Just (Paragraph (spans s))) mempty Para
+  plain = C.paragraph
+  thematicBreak = leaf ThematicBreak
+  blockQuote bs@(Blocks ns) = node (Just (BlockQuote (blocks bs))) (refsIn bs) (Quote ns)
+  codeBlock info t = node (Just (CodeBlock info (chomp t))) mempty (CodeLines t)
+  heading level = leaf . Heading level . spans
+  rawBlock _ t = node (if T.all isSpace html then Nothing else Just (Paragraph [Str html])) mempty Other
+    where
+      html = chomp (uncomment t)
+  referenceLinkDefinition label (!url, !title) =
+    node Nothing (M.singleton (T.toCaseFold (T.unwords (T.words label))) (url, title)) Para
+  list ty spacing = listOf ty spacing . map (Nothing,)
+
+instance HasTaskList Spans Blocks where
+  taskList ty spacing = listOf ty spacing . map (\(done, bs) -> (Just done, bs))
+
+instance HasPipeTable Spans Blocks where
+  pipeTable aligns header rows = leaf (Table (map align aligns) (map spans header) (map (map spans) rows))
+    where
+      align = \case
+        LeftAlignedCol -> CellLeft
+        CenterAlignedCol -> CellCenter
+        RightAlignedCol -> CellRight
+        DefaultAlignedCol -> CellDefault
+
+instance C.IsInline Spans where
+  lineBreak = one HardBreak
+  softBreak = one SoftBreak
+  str = one . Str
+  entity t = one (Str (fromMaybe t (lookupEntity (T.drop 1 t))))
+  escapedChar = one . Str . T.singleton
+  emph = wrap Emph
+  strong = wrap Strong
+  link url title = wrap (Link url title)
+  image src title = wrap (Image src title)
+  code = one . Code
+  rawInline _ t
+    | "<!--" `T.isPrefixOf` t = mempty
+    | otherwise = one (Str t)
+
+instance HasStrikethrough Spans where
+  strikethrough = wrap Strike
diff --git a/lib/NanoUI/Markdown/Syntax.hs b/lib/NanoUI/Markdown/Syntax.hs
new file mode 100644
--- /dev/null
+++ b/lib/NanoUI/Markdown/Syntax.hs
@@ -0,0 +1,109 @@
+-- | Parsed Markdown: blocks and their inline spans. "NanoUI.Markdown" draws
+-- it; applications can also walk it, for a table of contents or a
+-- plain-text copy.
+module NanoUI.Markdown.Syntax
+  ( Block (..)
+  , Span (..)
+  , ListType (..)
+  , ListItem (..)
+  , CellAlign (..)
+  , spansText
+  ) where
+
+import Control.DeepSeq (NFData)
+import Data.Text (Text)
+import Data.Text qualified as T
+import GHC.Generics (Generic)
+
+-- | A block of a document.
+data Block
+  = -- | Inline text. Raw HTML blocks also become paragraphs, with comments
+    -- removed; a block of only comments is dropped.
+    Paragraph ![Span]
+  | -- | Level 1 to 6: @# Title@, or a line underlined with @===@ (1) or
+    -- @---@ (2).
+    Heading !Int ![Span]
+  | -- | A horizontal rule: @---@, @***@ or @___@.
+    ThematicBreak
+  | -- | Fenced or four-space-indented code: the info string (empty for
+    -- indented code) and the code, without a trailing newline.
+    CodeBlock !Text !Text
+  | -- | Blocks quoted with @>@.
+    BlockQuote ![Block]
+  | -- | Kind, tightness (no blank lines between or inside items), items.
+    List !ListType !Bool ![ListItem]
+  | -- | GitHub table: column alignments, header cells, and rows with one
+    -- cell per column.
+    Table ![CellAlign] ![[Span]] ![[[Span]]]
+  deriving (Eq, Show, Generic)
+
+instance NFData Block
+
+-- | Inline content.
+data Span
+  = -- | Plain text with escapes and entities decoded. Inline raw HTML stays
+    -- as text; HTML comments are dropped.
+    Str !Text
+  | -- | A plain line break inside a paragraph.
+    SoftBreak
+  | -- | A line ending in two spaces or a backslash.
+    HardBreak
+  | -- | @*text*@ or @_text_@.
+    Emph ![Span]
+  | -- | @**text**@ or @__text__@.
+    Strong ![Span]
+  | -- | @~~text~~@.
+    Strike ![Span]
+  | -- | @\`code\`@.
+    Code !Text
+  | -- | Destination, title (empty if none), text. Covers inline and
+    -- reference links, autolinks (@\<https://...\>@), and bare web and
+    -- email addresses.
+    Link !Text !Text ![Span]
+  | -- | Source, title, alt text.
+    Image !Text !Text ![Span]
+  deriving (Eq, Show, Generic)
+
+instance NFData Span
+
+-- | A bullet list's character (@-@, @+@ or @*@), or an ordered list's start
+-- number and delimiter (@.@ or @)@). A list ends when the bullet or
+-- delimiter changes, or where task and non-task items meet.
+data ListType
+  = Bullet !Char
+  | Ordered !Int !Char
+  deriving (Eq, Show, Generic)
+
+instance NFData ListType
+
+-- | A list item. Only bullet items can be tasks: @1. [x] a@ is an ordered
+-- item with the text @[x] a@.
+data ListItem = ListItem
+  { itemTask :: !(Maybe Bool)
+  -- ^ For task items (@[ ]@ or @[x]@), whether checked.
+  , itemBlocks :: ![Block]
+  }
+  deriving (Eq, Show, Generic)
+
+instance NFData ListItem
+
+-- | Column alignment, from the colons in the delimiter row.
+data CellAlign = CellDefault | CellLeft | CellCenter | CellRight
+  deriving (Eq, Show, Enum, Bounded, Generic)
+
+instance NFData CellAlign
+
+-- | Spans as plain text: breaks become spaces, images their alt text.
+spansText :: [Span] -> Text
+spansText = T.concat . map go
+  where
+    go = \case
+      Str t -> t
+      SoftBreak -> " "
+      HardBreak -> " "
+      Emph xs -> spansText xs
+      Strong xs -> spansText xs
+      Strike xs -> spansText xs
+      Code t -> t
+      Link _ _ xs -> spansText xs
+      Image _ _ xs -> spansText xs
diff --git a/lib/NanoUI/Markdown/Widget.hs b/lib/NanoUI/Markdown/Widget.hs
new file mode 100644
--- /dev/null
+++ b/lib/NanoUI/Markdown/Widget.hs
@@ -0,0 +1,481 @@
+-- | The Markdown widget: a document drawn as nano-ui rich text and layout.
+module NanoUI.Markdown.Widget
+  ( MarkdownConfig (..)
+  , defaultMarkdownConfig
+  , MarkdownCache
+  , newMarkdownCache
+  , markdownCacheSize
+  , markdown
+  , markdownWith
+  , markdownConfigured
+  ) where
+
+import Control.Applicative ((<|>))
+import Control.Monad (unless, void, when, zipWithM, (>=>))
+import Data.Char (isSpace)
+import Data.Foldable (asum)
+import Data.Hashable (Hashable, hash)
+import Data.Maybe (fromMaybe, isJust)
+import Data.Text (Text)
+import Data.Text qualified as T
+import NanoUI
+  ( NanoUI
+  , Color
+  , FontMetrics (fmLineHeight)
+  , ImageId
+  , Inline
+  , LayoutModifier
+  , Rect (..)
+  , Size (..)
+  , Style (..)
+  , Theme (..)
+  , V2 (..)
+  , alignCenter
+  , alignEnd
+  , alignMiddle
+  , alignStart
+  , askDefaultLayout
+  , background
+  , borderColor
+  , borderWidth
+  , box
+  , breakAnywhere
+  , buttonWith
+  , columnWith
+  , CanvasConfig (..)
+  , canvasConfigured
+  , cornerRadius
+  , defaultCanvasConfig
+  , defaultLayout
+  , drawCircle
+  , drawRect
+  , drawStrokeCircle
+  , fillH
+  , fillW
+  , fixedW
+  , fixedWH
+  , flex
+  , fontBold
+  , fontColor
+  , fontItalic
+  , fontMono
+  , fontMuted
+  , fontSemiBold
+  , fontSize
+  , fontSizeScale
+  , fontStrike
+  , gap
+  , gridWith
+  , hyperlink
+  , image'
+  , inlineBackground
+  , inlineText
+  , inlineWith
+  , labelWith
+  , lerpColor
+  , lineWidthUi
+  , padAll
+  , padXY
+  , panelStyle
+  , panelWith
+  , resolveFontUi
+  , respClicked
+  , restyle
+  , selectableRichTextWith
+  , rowWith
+  , scope
+  , separator
+  , setClipboard
+  , styled
+  , subtle
+  , tight
+  , tooltip
+  , uiFontSize
+  , uiTheme
+  , whenM
+  , withKey
+  )
+import NanoUI.Backend
+  ( IntGenCache
+  , Layout (..)
+  , colorToWord32
+  , intGenCacheInsert
+  , intGenCacheLookup
+  , intGenCacheSize
+  , intGenCacheStartFrame
+  , intGenCacheTouch
+  , newIntGenCache
+  )
+import NanoUI.Widgets.Custom (checkboxBoxSize, drawCheckbox)
+import NanoUI.Internal.Context (frameNumber, intKey)
+import NanoUI.Internal.Monad (nextId, liftIO, withContext)
+import NanoUI.Internal.Store (eqByPtr, ptrEq)
+import NanoUI.Markdown.Document (MarkdownDoc, markdownBlocks)
+import NanoUI.Markdown.Syntax
+
+-- | How a document is drawn. Colours left 'Nothing' come from the theme.
+-- Each style modifier is applied on top of the default look it names, so
+-- @mdCodeBlock = background c@ changes a code block's background and keeps
+-- its border.
+data MarkdownConfig = MarkdownConfig
+  { mdLayout :: !(Layout -> Layout)
+  -- ^ The document's column.
+  , mdText :: !(Layout -> Layout)
+  -- ^ Body text font, e.g. @fontSize 15 . fontColor c@.
+  , mdHeading :: !(Int -> Layout -> Layout)
+  -- ^ Heading font by level (1 to 6), applied over the body text font.
+  , mdLinkColor :: !(Maybe Color)
+  -- ^ Link colour (default: the theme's).
+  , mdInlineCode :: !(Layout -> Layout)
+  -- ^ Inline code font, over monospace in the theme's orange (default: 'id').
+  , mdInlineCodeBackground :: !(Maybe Color)
+  -- ^ Background behind inline code (default: none).
+  , mdCodeBlock :: !(Style -> Style)
+  -- ^ Code block panel, over the theme's input background with a
+  -- separator-coloured border and rounded corners (default: 'id').
+  , mdQuote :: !(Layout -> Layout)
+  -- ^ Quoted text, over the surrounding text in the theme's muted colour
+  -- (default: 'id').
+  , mdTableCell :: !(Bool -> Style -> Style)
+  -- ^ Table cell panel, given whether it is a header cell, over the flat
+  -- panel colour, tinted for headers (default: @const id@).
+  , mdCopyCode :: !Bool
+  -- ^ Show a copy button on code blocks.
+  , mdImage :: !(Text -> Maybe (ImageId, Size))
+  -- ^ The registered image for a source, and its size in logical pixels.
+  -- Only an image alone in its paragraph (or alone in a link there) is
+  -- drawn. Clicking it returns the link, or else the source; its title, or
+  -- else the link's, is the tooltip. Other images show their alt text as a
+  -- link.
+  , mdBlock :: !((Block -> NanoUI (Maybe Text)) -> Block -> NanoUI (Maybe Text))
+  -- ^ Custom block drawing, given the widget's own drawing to fall back to
+  -- or wrap (default: 'id'). Called for every block at every depth,
+  -- including inside quotes and list items, so it can highlight code, load
+  -- images lazily, or add chrome. The built-in drawing calls it again for
+  -- nested blocks. Return the clicked link, as 'markdown' does. Each block
+  -- is keyed by position and kind, so appending to a block keeps its ids.
+  --
+  -- > mdBlock = \own -> \case
+  -- >   CodeBlock "haskell" code -> Nothing <$ highlighted code
+  -- >   b -> own b
+  }
+
+-- | A full-width column, body text in the theme's font, headings from 1.6x
+-- down to 0.9x its size, theme colours, copy buttons on code blocks, and no
+-- images.
+defaultMarkdownConfig :: MarkdownConfig
+defaultMarkdownConfig =
+  MarkdownConfig
+    { mdLayout = tight . fillW . gap 16
+    , mdText = id
+    , mdHeading = \level ->
+        let scale = case level of
+              1 -> 1.6
+              2 -> 1.35
+              3 -> 1.2
+              4 -> 1.05
+              5 -> 1
+              _ -> 0.9
+         in fontSizeScale scale . (if level <= 4 then fontBold else fontSemiBold)
+    , mdLinkColor = Nothing
+    , mdInlineCode = id
+    , mdInlineCodeBackground = Nothing
+    , mdCodeBlock = id
+    , mdQuote = id
+    , mdTableCell = const id
+    , mdCopyCode = True
+    , mdImage = const Nothing
+    , mdBlock = id
+    }
+
+-- | Draw a document. Returns the destination of a link clicked this frame.
+--
+-- Each top-level block is keyed by its position and kind, so appending to a
+-- document keeps the ids, and the cached text layout, of earlier blocks.
+-- Text in paragraphs, headings, table cells and code blocks can be selected
+-- and copied; code blocks also have a copy button.
+markdown :: MarkdownCache -> MarkdownDoc -> NanoUI (Maybe Text)
+markdown cache = markdownConfigured cache defaultMarkdownConfig
+
+-- | 'markdown' with a layout modifier applied to the document column.
+markdownWith :: LayoutModifier -> MarkdownCache -> MarkdownDoc -> NanoUI (Maybe Text)
+markdownWith f cache =
+  markdownConfigured cache defaultMarkdownConfig {mdLayout = f . mdLayout defaultMarkdownConfig}
+
+-- | 'markdown' with a configuration.
+markdownConfigured :: MarkdownCache -> MarkdownConfig -> MarkdownDoc -> NanoUI (Maybe Text)
+markdownConfigured cache@(MarkdownCache genCache) cfg doc = do
+  withContext (frameNumber >=> intGenCacheStartFrame genCache)
+  theme <- uiTheme
+  size <- uiFontSize
+  -- Pin the body size (the backend default if unset, or scaled if a relative
+  -- fontSizeScale was active) so nested headings and labels share it.
+  let resolveBase l =
+        let sz = layoutFontSize l
+         in if sz > 0
+              then l
+              else if sz < 0
+                then fontSize (max 1 (size * negate sz)) l
+                else fontSize size l
+      text = mdText cfg . resolveBase
+  base <- text <$> askDefaultLayout
+  fm <- resolveFontUi (layoutFontSize base) (layoutFontWeight base) (layoutFontStyle base) (layoutFontVariant base)
+  let env =
+        Env
+          { envCfg = cfg
+          , envCache = cache
+          , envTheme = theme
+          , envText = text
+          , envSize = layoutFontSize base
+          , envDepth = 0
+          , envMetrics = fm
+          }
+  columnWith (mdLayout cfg) (blocks env (markdownBlocks doc))
+
+-- Per-block drawing context. envText is the current text modifier (muted
+-- inside quotes); envMetrics is the body font, which sizes list markers.
+data Env = Env
+  { envCfg :: !(MarkdownConfig)
+  , envCache :: !MarkdownCache
+  , envTheme :: !Theme
+  , envText :: !(Layout -> Layout)
+  , envSize :: !Float
+  , envDepth :: !Int
+  , envMetrics :: !FontMetrics
+  }
+
+-- | Blocks in sequence, each drawn by 'mdBlock' under a key of its position
+-- and kind. A block that changes kind as text streams in (a paragraph
+-- becoming a heading, table or image) gets fresh ids.
+blocks :: Env -> [Block] -> NanoUI (Maybe Text)
+blocks env bs = asum <$> zipWithM draw [0 :: Int ..] bs
+  where
+    own = block env
+    draw i b = withKey (i, blockKind (envCfg env) b) (mdBlock (envCfg env) own b)
+
+-- | A block's kind, for its key. A paragraph drawn as an image is its own
+-- kind.
+blockKind :: MarkdownConfig -> Block -> Int
+blockKind cfg = \case
+  Paragraph xs
+    | isJust (soleImage cfg xs) -> 13
+    | otherwise -> 0
+  Heading level _ -> level
+  ThematicBreak -> 7
+  CodeBlock {} -> 8
+  BlockQuote _ -> 9
+  List (Bullet _) _ _ -> 10
+  List (Ordered _ _) _ _ -> 11
+  Table {} -> 12
+
+-- | The widget's own block drawing. NOINLINE: inlined into 'blocks', its
+-- closures over 'Env' would be allocated on every call.
+{-# NOINLINE block #-}
+block :: Env -> Block -> NanoUI (Maybe Text)
+block env = \case
+  Paragraph xs
+    | Just (target, title, iid, Size w h) <- soleImage (envCfg env) xs -> do
+        resp <- image' (fixedWH w h) iid
+        unless (T.null title) (tooltip resp title)
+        pure (if respClicked resp then Just target else Nothing)
+    | otherwise -> selectableRichTextWith (tight . fillW . envText env) =<< keptInlines env xs
+  Heading level xs ->
+    let title = selectableRichTextWith (tight . fillW . mdHeading (envCfg env) level . envText env) =<< keptInlines env xs
+     in if level <= 2 then columnWith (tight . fillW . gap 6) (title <* separator) else title
+  ThematicBreak -> Nothing <$ separator
+  CodeBlock info code -> Nothing <$ codeBlock env info code
+  BlockQuote bs ->
+    rowWith (tight . fillW . gap 10) $ do
+      box (fixedW 3 . fillH) (themeSeparator (envTheme env))
+      columnWith (tight . fillW . gap 16) $
+        blocks env {envText = mdQuote (envCfg env) . fontColor (themeMuted (envTheme env)) . envText env} bs
+  List ty isTight items -> listBlock env ty isTight items
+  Table aligns header rows -> tableBlock env aligns header rows
+
+-- | The image to draw for a paragraph holding only an image (or only a
+-- linked image) resolved by 'mdImage': click target, title (else the link's),
+-- image and size.
+soleImage :: MarkdownConfig -> [Span] -> Maybe (Text, Text, ImageId, Size)
+soleImage cfg = \case
+  [Image src title _] -> drawn src src title
+  [Link url linkTitle [Image src title _]] -> drawn url src (if T.null title then linkTitle else title)
+  _ -> Nothing
+  where
+    drawn target src title = (\(iid, size) -> (target, title, iid, size)) <$> mdImage cfg src
+
+-- | 'inlines' for spans drawn every frame, the same pieces as last frame's
+-- while the spans are the same list (as a closed block's are) and the theme
+-- and inline styles are unchanged. Rich text then reuses the paragraph's
+-- layout without hashing its text again, so a long document costs little a
+-- frame while a reply streams into its last block.
+keptInlines :: Env -> [Span] -> NanoUI [Inline]
+keptInlines env xs = do
+  wid <- nextId
+  liftIO $ do
+    let MarkdownCache cache = envCache env
+        k = intKey wid
+    intGenCacheLookup cache k >>= \case
+      Just e@(KeptEntry ys theme link codeBg code pieces)
+        | ptrEq xs ys
+        , eqByPtr (envTheme env) theme
+        , mdLinkColor cfg == link
+        , mdInlineCodeBackground cfg == codeBg
+        , ptrEq (mdInlineCode cfg) code ->
+            pieces <$ intGenCacheTouch cache k e
+      _ -> do
+        let pieces = inlines env xs
+            e = KeptEntry xs (envTheme env) (mdLinkColor cfg) (mdInlineCodeBackground cfg) (mdInlineCode cfg) pieces
+        pieces <$ intGenCacheInsert cache k e
+  where
+    cfg = envCfg env
+
+-- | Pieces 'keptInlines' made, by widget key, in two generations.
+newtype MarkdownCache = MarkdownCache (IntGenCache KeptEntry)
+
+-- | Allocate once during component setup. The cache retains only typed
+-- inline data; paragraph layout and interaction state remain in the UI
+-- context. It holds a few frames' worth of blocks, whatever the document's
+-- history, and documents drawn together may share it.
+newMarkdownCache :: IO MarkdownCache
+newMarkdownCache = MarkdownCache <$> newIntGenCache 1024
+
+-- | Blocks the cache holds, for diagnostics.
+markdownCacheSize :: MarkdownCache -> IO Int
+markdownCacheSize (MarkdownCache cache) = intGenCacheSize cache
+
+-- | Spans, what styled them, and their pieces.
+data KeptEntry = KeptEntry [Span] !Theme !(Maybe Color) !(Maybe Color) (Layout -> Layout) [Inline]
+
+-- | Spans as rich-text pieces. Every piece inside a link targets its
+-- destination; an image's alt text targets its enclosing link, else its
+-- source.
+inlines :: Env -> [Span] -> [Inline]
+inlines env = concatMap (go id Nothing)
+  where
+    theme = envTheme env
+    cfg = envCfg env
+    linkColor' = fromMaybe (themeLink theme) (mdLinkColor cfg)
+    codeBackground = maybe id inlineBackground (mdInlineCodeBackground cfg)
+    go style target = \case
+      Str t -> [piece style target t]
+      SoftBreak -> [piece style target " "]
+      HardBreak -> [piece style target "\n"]
+      Emph xs -> concatMap (go (fontItalic . style) target) xs
+      Strong xs -> concatMap (go (fontBold . style) target) xs
+      Strike xs -> concatMap (go (fontStrike . style) target) xs
+      Code t ->
+        -- Code in a link keeps the link's colour.
+        let ink = if isJust target then id else fontColor (themeOrange theme)
+         in [codeBackground (piece (mdInlineCode cfg . fontMono . breakAnywhere . ink . style) target t)]
+      Link url _ xs -> concatMap (go (fontColor linkColor' . style) (target <|> Just url)) xs
+      Image src _ alt ->
+        let txt = if null alt then "image" else spansText alt
+         in [piece (fontItalic . fontColor linkColor' . style) (target <|> Just src) txt]
+    piece style target t = case target of
+      Nothing -> inlineWith style t
+      Just url -> restyle style (hyperlink url t)
+
+-- | Monospace code on a panel, under a row with its language and a copy
+-- button. Long lines wrap, keeping indentation and inner spaces. A
+-- horizontal scroller would steal the wheel from the page and its bar would
+-- cover the last line.
+codeBlock :: Env -> Text -> Text -> NanoUI ()
+codeBlock env info code = do
+  let theme = envTheme env
+      cfg = envCfg env
+      language = T.takeWhile (not . isSpace) info
+  styled (panelStyle (mdCodeBlock cfg . background (styleBg (themeInput theme)) . borderColor (themeSeparator theme) . cornerRadius 6)) $
+    panelWith (padXY 10 8 . gap 4 . fillW) $ do
+      scope $ when (mdCopyCode cfg || not (T.null language)) $
+        rowWith (tight . fillW . alignMiddle) $ do
+          labelWith (tight . fontMuted . fontSizeScale 0.8 . envText env) language
+          flex
+          when (mdCopyCode cfg) $
+            whenM (styled subtle (buttonWith (padXY 6 1 . fontSize (0.8 * envSize env)) "Copy")) $
+              void (setClipboard code)
+      void $
+        selectableRichTextWith
+          (tight . fillW . fontMono . breakAnywhere . fontColor (styleFg (themeInput theme)) . envText env)
+          [inlineText code]
+
+-- | A list: each item's marker beside its blocks; tight lists have less
+-- spacing. Markers take the surrounding text colour. Bullets are a disc,
+-- then a ring one level deeper, then a square. Task items use a nano-ui
+-- checkbox, recoloured to the text colour when that differs from the theme.
+listBlock :: Env -> ListType -> Bool -> [ListItem] -> NanoUI (Maybe Text)
+listBlock env ty isTight items = do
+  let fm = envMetrics env
+      theme = envTheme env
+      lineH = fmLineHeight fm
+      side = checkboxBoxSize fm
+      spacing = if isTight then 6 else 16
+      -- Each item's number, built once for both measuring and drawing.
+      numbers = case ty of
+        Ordered start delim -> [T.pack (show n) <> T.singleton delim | n <- [start ..]]
+        Bullet _ -> repeat ""
+  -- Measure every number: in a proportional font an earlier one can be
+  -- widest ("10." vs "11.").
+  numberWs <- case ty of
+    Ordered _ _ -> mapM (lineWidthUi fm) (take (length items) numbers)
+    Bullet _ -> pure []
+  let markerW = maximum (lineH : [side | any (isJust . itemTask) items] ++ numberWs)
+      ink = fromMaybe (styleFg (themePanel theme)) (layoutFontColor (envText env defaultLayout))
+      marker v h shape = void (canvasConfigured defaultCanvasConfig {canvasLayout = fixedWH markerW h, canvasContent = v} (\(Rect x y _ _) -> shape x y))
+      bullet = marker (version 1 (envDepth env, colorToWord32 ink)) lineH $ \x y ->
+        let c@(V2 cx cy) = V2 (x + markerW / 2) (y + lineH / 2)
+            r = max 2 (lineH * 0.15)
+         in case envDepth env of
+              0 -> drawCircle c r ink
+              1 -> drawStrokeCircle c (r - 0.6) 1.2 ink
+              _ -> drawRect (Rect (cx - r) (cy - r) (2 * r) (2 * r)) ink
+      boxTheme
+        | ink == styleFg (themePanel theme) = theme
+        | otherwise = theme {themeAccent = ink, themeButton = (themeButton theme) {styleBorder = ink}}
+      boxColors = map colorToWord32 [themeAccent boxTheme, themeOnAccent boxTheme, styleBg (themeInput boxTheme), styleBorder (themeButton boxTheme)]
+      boxH = max lineH side
+      checkBox done = marker (version 2 (done, boxColors)) boxH $ \x y ->
+        drawCheckbox boxTheme (Rect (x + (markerW - side) / 2) (y + (boxH - side) / 2) side side) done
+  columnWith (tight . fillW . gap spacing) $
+    asum <$> zipWithM
+      ( \(i, num) (ListItem task bs) -> withKey i $
+          rowWith (tight . fillW . gap 6) $ do
+            case (task, ty) of
+              (Just done, _) -> checkBox done
+              (Nothing, Ordered _ _) -> labelWith (tight . fixedW markerW . alignEnd . envText env) num
+              (Nothing, Bullet _) -> bullet
+            columnWith (tight . fillW . gap spacing) $
+              blocks env {envDepth = envDepth env + 1} bs
+      )
+      (zip [0 :: Int ..] numbers)
+      items
+
+-- | A list marker's canvas content key: a hash of what the drawing depends on
+-- besides size, with the shape tag (1 bullet, 2 checkbox) in the low bits so
+-- an item becoming a task item redraws. Never 0 (uncached).
+version :: Hashable a => Int -> a -> Int
+version tag deps = hash deps * 4 + tag
+
+-- | A table as a grid of equal columns: bold header cells on a tinted row,
+-- one-pixel rules between cells, and each cell aligned per its column.
+tableBlock :: Env -> [CellAlign] -> [[Span]] -> [[[Span]]] -> NanoUI (Maybe Text)
+tableBlock env aligns header rows = do
+  let theme = envTheme env
+      rule = themeSeparator theme
+      bodyBg = styleBg (themePanel theme)
+      headBg = lerpColor bodyBg rule 0.35
+      flat c = background c . borderWidth 0 . cornerRadius 0
+      cell isHeader (align, spans) =
+        styled (panelStyle (mdTableCell (envCfg env) isHeader . flat (if isHeader then headBg else bodyBg))) $
+          panelWith (padXY 8 5 . fillW . fillH) $
+            selectableRichTextWith (tight . alignOf align . (if isHeader then fontBold else id) . envText env)
+              =<< keptInlines env spans
+      alignOf = \case
+        CellCenter -> alignCenter
+        CellRight -> alignEnd
+        _ -> alignStart
+  styled (panelStyle (flat rule)) $
+    panelWith (padAll 1 . fillW) $
+      gridWith (length aligns) (tight . fillW . gap 1) $ do
+        heads <- mapM (cell True) (zip aligns header)
+        cells <- mapM (mapM (cell False) . zip aligns) rows
+        pure (asum heads <|> asum (map asum cells))
diff --git a/nano-ui-markdown.cabal b/nano-ui-markdown.cabal
new file mode 100644
--- /dev/null
+++ b/nano-ui-markdown.cabal
@@ -0,0 +1,113 @@
+cabal-version:      3.4
+name:               nano-ui-markdown
+version:            0.2.0.0
+synopsis:           Markdown rendering for nano-ui, parsed incrementally
+description:
+    A Markdown widget for nano-ui, drawn with its rich text and layout, and
+    documents parsed by the commonmark library that text can be appended to
+    without parsing the whole document again, for chat messages that stream
+    in.
+license:            MIT
+license-file:       LICENSE
+author:             goolord
+maintainer:         zacharyachurchill@gmail.com
+homepage:           https://github.com/goolord/nano-ui
+bug-reports:        https://github.com/goolord/nano-ui/issues
+category:           Graphics, Text
+build-type:         Simple
+tested-with:        GHC ==9.10.3 || ==9.14.1
+extra-doc-files:
+    CHANGELOG.md
+    README.md
+
+source-repository head
+    type:     git
+    location: https://github.com/goolord/nano-ui.git
+    subdir:   packages/nano-ui-markdown
+
+common extensions
+    default-language: GHC2024
+    default-extensions:
+        OverloadedStrings
+
+common warnings
+    ghc-options:
+        -Wall
+        -Wextra
+        -Wcompat
+        -Widentities
+        -Wincomplete-record-updates
+        -Wincomplete-uni-patterns
+        -Wmissing-export-lists
+        -Wmissing-home-modules
+        -Wpartial-fields
+        -Wredundant-constraints
+        -Wunused-packages
+
+library
+    import:           extensions
+    import:           warnings
+    exposed-modules:
+        NanoUI.Markdown
+        NanoUI.Markdown.Document
+        NanoUI.Markdown.Syntax
+        NanoUI.Markdown.Widget
+    other-modules:
+        NanoUI.Markdown.Internal.Parse
+    build-depends:
+        base >=4.20 && <4.23,
+        commonmark ^>=0.3,
+        commonmark-extensions ^>=0.2.7,
+        containers >=0.7 && <0.9,
+        deepseq >=1.4 && <1.7,
+        hashable ^>=1.5,
+        nano-ui ^>=0.2,
+        parsec ^>=3.1,
+        text ^>=2.1,
+        unicode-transforms ^>=0.4
+    hs-source-dirs:   lib
+
+flag sdl
+    description: Build the SDL3 window example. Off by default, so that
+                 depending on the library does not need nano-ui-sdl and SDL3.
+    manual: True
+    default: False
+
+executable nano-ui-markdown-example
+    import:           extensions
+    import:           warnings
+    main-is:          Main.hs
+    other-modules:    ChatDemo
+    ghc-options:      -rtsopts -threaded "-with-rtsopts=-N1 -A64m -T -I0"
+    build-depends:
+        base >=4.20 && <4.23,
+        nano-ui ^>=0.2,
+        nano-ui-markdown,
+        text ^>=2.1
+    if flag(sdl)
+        build-depends:
+            nano-ui-sdl ^>=0.2
+    if os(windows)
+        ghc-options: -optl-mconsole
+    if !flag(sdl)
+        buildable: False
+    hs-source-dirs:   examples
+
+test-suite nano-ui-markdown-test
+    import:           extensions
+    import:           warnings
+    type:             exitcode-stdio-1.0
+    main-is:          Main.hs
+    other-modules:
+        Incremental
+        Parse
+        Render
+    ghc-options:      -rtsopts -threaded "-with-rtsopts=-M512m -N1"
+    build-depends:
+        base >=4.20 && <4.23,
+        hspec ^>=2.11,
+        QuickCheck >=2.15 && <2.19,
+        nano-ui ^>=0.2,
+        nano-ui-markdown,
+        text ^>=2.1
+    hs-source-dirs:   test
diff --git a/test/Incremental.hs b/test/Incremental.hs
new file mode 100644
--- /dev/null
+++ b/test/Incremental.hs
@@ -0,0 +1,219 @@
+-- | Appending text gives the same parse as parsing the whole text.
+module Incremental (spec) where
+
+import Data.List (inits, sort)
+import Data.Text (Text)
+import Data.Text qualified as T
+import NanoUI.Markdown
+import Test.Hspec
+import Test.Hspec.QuickCheck (modifyMaxSuccess)
+import Test.QuickCheck
+
+-- | A document of parser-stressing lines, each with its own line ending:
+-- container markers before block starts, lines that start a block only in
+-- some contexts, inline text dense with delimiters, brackets and links, link
+-- reference definitions, HTML, and blank or indented lines.
+newtype Doc = Doc [(Text, Text)]
+
+instance Show Doc where
+  show = show . docText
+
+docText :: Doc -> Text
+docText (Doc ls) = T.concat [l <> end | (l, end) <- ls]
+
+instance Arbitrary Doc where
+  arbitrary = do
+    ls <- upTo 16 genLine
+    ends <- vectorOf (length ls - 1) genEnding
+    end <- oneof [pure "", genEnding]
+    pure (Doc (zip ls (ends ++ [end])))
+  shrink (Doc ls) = map Doc (shrinkList (const []) ls)
+
+genEnding :: Gen Text
+genEnding = frequency [(6, pure "\n"), (2, pure "\r\n"), (2, pure "\r")]
+
+genLine :: Gen Text
+genLine = do
+  prefixes <- upTo 2 (elements ["> ", ">", "- ", "* ", "1. ", "2) ", "  ", "   ", "    ", "\t", "- [ ] ", "- [x] "])
+  indent <- elements ["", "", "", " ", "  ", "   ", "    "]
+  body <-
+    frequency
+      [ (6, genInline)
+      , (3, pure "")
+      , (1, elements ["   ", "#", "# Title", "## Sub ##", "###### six", "=====", "===", "---", "***", "- - -", "___"])
+      , (2, elements ["```", "```haskell", "~~~", "````", "``` x`y"])
+      , (2, elements ["| a | b |", "|---|:-:|", "|:-:|", "a | b", "--|--", "| `x\\|y` | *z* |", "|:--|"])
+      , (1, elements ["2. ", "10. ", "2. b", "10. b", "1. [x] a"])
+      , (2, elements ["[ref]: /url \"t\"", "[Other]: <u v>", "[ref]:", "[ref]", "[x][ref]", "[other][]", "[OTHER]"])
+      , (2, elements ["<div>", "</div>", "<a href=\"x\">", "<span>", "<x-y>", "<pre>", "<!-- c", "-->", "<!-- c -->", "a <!-- c --> b"])
+      , (1, (<>) <$> elements ["", "    "] <*> genInline)
+      ]
+  pure (T.concat prefixes <> indent <> body)
+
+-- | Between 0 and @k@ generated values.
+upTo :: Int -> Gen a -> Gen [a]
+upTo k g = chooseInt (0, k) >>= (`vectorOf` g)
+
+genInline :: Gen Text
+genInline = T.concat <$> (chooseInt (1, 8) >>= (`vectorOf` genToken))
+
+genToken :: Gen Text
+genToken =
+  frequency
+    [ (8, elements ["word", "text", "a", "b", "snake_case", "x*y", "!", "(", ")", "  ", " ", "'"])
+    , (6, elements ["*", "**", "***", "_", "__", "~", "~~", "~~~"])
+    , (3, elements ["`", "``", "`code`", "\\", "\\*", "\\`", "&amp;", "&#65;", "&nope;", "&"])
+    , (3, elements ["[", "]", "![", "](", "(/u)", "[a](/u \"t\")", "[b]", "<", ">"])
+    , (2, elements ["<https://a.b>", "<me@x.io>", "https://x.org/p.", "www.a.co", "http://h", " https://q.r/(s)"])
+    , (1, elements ["  ", "\\"] >>= \end -> pure (end <> "\n"))
+    ]
+
+-- | Texts a streamed paragraph starts from: plain ones, and ones that words
+-- could still turn into another block or inline.
+openings :: [Text]
+openings =
+  [ "", "Some text", "2024", "a\n1.", "a\n", "a  ", "x\\", "*a", "_a_", "`code", "# h", "- item", "> quote"
+  , "| a | b |", "[a]: /u 'x", "[a]: /u\n'x", "[a]", "<div", "x &amp", "foo<!-- c -->", "see ww", "a@b"
+  ]
+
+-- | Tokens of prose, and a few that are not plain.
+proseTokens :: [Text]
+proseTokens =
+  [ "word", " word", " a", "b", " 42", "7", ",", ".", ";", "?", "!", ":", "'", "\"", "-", " it's", "e.g."
+  , "www", " www", " ", "  ", "\n", "\n\n", "*", "_", "&amp", "`", "["
+  ]
+
+-- | A document and its cut positions; both shrink.
+data Cut = Cut Doc [Int]
+
+instance Show Cut where
+  show (Cut d cuts) = show (chunksAt cuts (docText d))
+
+instance Arbitrary Cut where
+  arbitrary = do
+    d <- arbitrary
+    Cut d <$> upTo 12 (chooseInt (0, T.length (docText d)))
+  shrink (Cut d cuts) = [Cut d cuts' | cuts' <- shrinkList shrink cuts] ++ [Cut d' cuts | d' <- shrink d]
+
+-- | Split the text at the given positions (clamped to its length), keeping
+-- empty pieces.
+chunksAt :: [Int] -> Text -> [Text]
+chunksAt cuts t = zipWith (\from to -> T.take (to - from) (T.drop from t)) bounds (drop 1 bounds)
+  where
+    bounds = 0 : sort (map (min (T.length t)) cuts) ++ [T.length t]
+
+-- | The document after each append, starting with the empty one.
+streams :: [Text] -> [MarkdownDoc]
+streams = scanl (flip appendMarkdown) emptyMarkdown
+
+appendAll :: [Text] -> MarkdownDoc
+appendAll = last . streams
+
+-- | Streaming one character at a time, every step's blocks match a full
+-- parse of the text so far.
+streamsLikeWhole :: Text -> Expectation
+streamsLikeWhole t =
+  map markdownBlocks (streams (T.chunksOf 1 t)) `shouldBe` map parseMarkdownBlocks (T.inits t)
+
+-- | Appending @b@ to @a@, whole and a character at a time, parses to what
+-- the whole text does.
+appendsLikeWhole :: Text -> Text -> Expectation
+appendsLikeWhole a b = do
+  markdownBlocks (appendMarkdown b (parseMarkdown a)) `shouldBe` parseMarkdownBlocks (a <> b)
+  streamsLikeWhole (a <> b)
+
+spec :: Spec
+spec = do
+  describe "appendMarkdown" $ do
+    modifyMaxSuccess (const 400) . it "parses to what the whole text does, in any number of pieces" $
+      property $ \(Cut d cuts) ->
+        markdownBlocks (appendAll (chunksAt cuts (docText d))) === parseMarkdownBlocks (docText d)
+    modifyMaxSuccess (const 60) . it "parses to what the whole text does, a character at a time" $
+      property $ \d ->
+        markdownBlocks (appendAll (T.chunksOf 1 (docText d))) === parseMarkdownBlocks (docText d)
+    it "parses any text" $
+      property $ \s ->
+        let t = T.pack s
+         in length (show (parseMarkdownBlocks t)) `seq` markdownBlocks (appendMarkdown t (parseMarkdown t)) === parseMarkdownBlocks (t <> t)
+
+  let adds name a b = it name (appendsLikeWhole a b)
+  describe "a line right under a paragraph" $ do
+    -- Such a line may underline the paragraph, make it a table header, or
+    -- fail to interrupt it where it would otherwise start a block, so the
+    -- paragraph must be reparsed with it.
+    adds "underlines it into a heading" "a\n---\n" "b"
+    adds "makes it a table's header" "a | b\n--|--\n" "c | d"
+    adds "continues it with an ordered item not numbered 1" "a\n2. b\n" "c"
+    adds "continues it with an ordered item numbered 10" "a\n10. b\n" "c"
+    adds "continues it with HTML of type 7" "a\n<x-y>\n" "b"
+    adds "continues it with a task item with nothing after its box" "a\n- [x] \n" "b"
+    adds "continues link reference definitions" "[r]: /u\n- [x] \n" "b"
+
+  describe "plain words" $ do
+    -- Words added to a paragraph join its last line without a parse, unless
+    -- the text could still become another block or inline.
+    adds "complete a link reference definition" "[foo]:" " bar"
+    adds "close a definition's title" "[a]: /u 'title\nfoo" " bar'"
+    adds "close a definition's title on its own line" "[a]: /u\n'title\nfoo" " bar'"
+    adds "continue an HTML block" "<div" " foo "
+    adds "start a line" "Foo\n" "bar"
+    adds "start a paragraph" "Foo\n\n" " bar"
+    adds "make a list item" "a\n1." " b"
+    adds "end an entity" "x &amp" ";"
+    adds "make a web address" "see" " www.example.com"
+    adds "end a web address's www" "www" "."
+    adds "make a hyphenated web address" "Visit" " www-example.com"
+    adds "follow an HTML comment" "foo<!-- c -->  " "bar"
+    adds "follow a space from an entity" "foo&#32;" " "
+    adds "join a letter the parse normalizes" "\28010" "\63786"
+    adds "combine with the letter before" "cafe" "\769"
+    modifyMaxSuccess (const 150) . it "parse to what the whole text does, one at a time" $
+      property $ forAll ((:) <$> elements openings <*> listOf (elements proseTokens)) $ \tokens ->
+        map markdownBlocks (streams tokens) === map (parseMarkdownBlocks . T.concat) (inits tokens)
+
+  describe "a streamed message" $ do
+    it "continues an open code block, list, table and block quote" $
+      mapM_
+        streamsLikeWhole
+        [ "```hs\nx = 1\n\n  y = 2\n~~~\n````\n```\nafter\n"
+        , "   ~~~\n    a\n  b\n~~~ ~\n   ~~~~"
+        , "- a\n- b\n\n- c\n  more\n\n  > q\n- d\ne\n\npara"
+        , "- a\n\n- b\n- c\n- d"
+        , "1. a\n2. b\n3) c\n4) d"
+        , "- [ ] a\n- [x] b\n- c\n- [x] d"
+        , "| a | b |\n|---|:-:|\n| 1 | 2 |\n| 3 |\n| 4 | 5 | 6 |\nafter"
+        , "> a\n>\n> b\n> - c\n> - d\n>\n> ```\n> e\n\n> f"
+        , "<!-- a -->\n<!-- b -->\n<div>\nc\n</div>\n\nd"
+        ]
+    it "resolves links to definitions before and after them" $
+      mapM_
+        streamsLikeWhole
+        [ "[a] and [b]\n\ntext\n\n[a]: /u\n[b]: /v 'title'\n"
+        , "[a]: /1\n\n[a]\n\n[A]: /2\n\n[a]\n\n- [a]\n- [c]\n\n> [c]: /3\n\n[c]"
+        ]
+
+  describe "MarkdownDoc" $ do
+    it "is equal to another with the same text" $ do
+      appendMarkdown "b" (parseMarkdown "a") `shouldBe` parseMarkdown "ab"
+      parseMarkdown "a" `shouldNotBe` parseMarkdown "a\n"
+      parseMarkdown "a\r\n" `shouldNotBe` parseMarkdown "a\n"
+      emptyMarkdown `shouldBe` parseMarkdown ""
+    modifyMaxSuccess (const 300) . it "hands back its text, however it was built" $
+      property $ \(Cut d cuts) ->
+        markdownSource (appendAll (chunksAt cuts (docText d))) === docText d
+    it "lists its images' sources once each, in order, at any depth" $
+      markdownImages
+        ( parseMarkdown
+            "![a](one.png) and [![b](two.png)](/link)\n\n> - ![c](three.png) *![d](one.png)*\n\n\
+            \| h | ![e](four.png) |\n|---|---|\n| ![f](five.png) | x |\n\n```\n![not](code.png)\n```"
+        )
+        `shouldBe` ["one.png", "two.png", "three.png", "four.png", "five.png"]
+    it "shows as the parse of its text" $
+      show (appendMarkdown "b" (parseMarkdown "*a*\n")) `shouldBe` "parseMarkdown \"*a*\\nb\""
+    it "keeps every token in a store that skips equal documents" $ do
+      -- The store mimics nano-ui's writeVar. A line ending changes no block
+      -- yet, but the doc must still differ or the text after it is lost.
+      let tokens = ["Hello", "\n", "\n", "- one", "\n", "- two", "\n", "\n", "```", "\n", "x", "\n", "```"]
+          store old new = if new == old then old else new
+          kept = scanl (\doc tok -> store doc (appendMarkdown tok doc)) emptyMarkdown tokens
+      map markdownBlocks kept `shouldBe` map (parseMarkdownBlocks . T.concat) (inits tokens)
diff --git a/test/Main.hs b/test/Main.hs
new file mode 100644
--- /dev/null
+++ b/test/Main.hs
@@ -0,0 +1,12 @@
+module Main (main) where
+
+import Incremental qualified
+import Parse qualified
+import Render qualified
+import Test.Hspec
+
+main :: IO ()
+main = hspec $ do
+  describe "parsing" Parse.spec
+  describe "incremental parsing" Incremental.spec
+  describe "drawing" Render.spec
diff --git a/test/Parse.hs b/test/Parse.hs
new file mode 100644
--- /dev/null
+++ b/test/Parse.hs
@@ -0,0 +1,77 @@
+-- | How the commonmark library's parse maps to our blocks and spans.
+-- CommonMark conformance itself is the library's concern.
+module Parse (spec) where
+
+import NanoUI.Markdown
+import Test.Hspec
+
+spec :: Spec
+spec = do
+  describe "blocks" $ do
+    it "parses headings" $ do
+      "## Title ##" `parsesTo` Heading 2 [Str "Title"]
+      "Two\nlines\n---" `parsesTo` Heading 2 [Str "Two", SoftBreak, Str "lines"]
+      "#" `parsesTo` Heading 1 []
+    it "parses paragraphs and thematic breaks" $
+      parseMarkdownBlocks "a\nb\n\n***\n\nc" `shouldBe` [Paragraph [Str "a", SoftBreak, Str "b"], ThematicBreak, para "c"]
+    it "parses code with its info string, without the last line ending" $ do
+      "```hs x\nmain = pure ()\n```" `parsesTo` CodeBlock "hs x" "main = pure ()"
+      "    one\n\n    two\n\n" `parsesTo` CodeBlock "" "one\n\ntwo"
+      "```\r\na\r\nb" `parsesTo` CodeBlock "" "a\nb"
+    it "parses block quotes" $
+      "> a\n> > b" `parsesTo` BlockQuote [para "a", BlockQuote [para "b"]]
+    it "parses bullet and ordered lists, tight or loose" $ do
+      "- a\n  - b\n- c"
+        `parsesTo` List (Bullet '-') True [item [para "a", List (Bullet '-') True [item [para "b"]]], item [para "c"]]
+      "3) c\n\n4) d" `parsesTo` List (Ordered 3 ')') False [item [para "c"], item [para "d"]]
+    it "parses task lists, which an item without a box ends" $ do
+      "- [ ] todo\n- [x] done"
+        `parsesTo` List (Bullet '-') True [ListItem (Just False) [para "todo"], ListItem (Just True) [para "done"]]
+      parseMarkdownBlocks "- [x] done\n- plain"
+        `shouldBe` [List (Bullet '-') True [ListItem (Just True) [para "done"]], List (Bullet '-') True [item [para "plain"]]]
+    it "gives only bullet items check boxes" $
+      "1. [x] done" `parsesTo` List (Ordered 1 '.') True [item [para "[x] done"]]
+    it "parses tables with their alignment, one cell a column" $
+      "| a | b | c | d |\n|---|:--|:-:|--:|\n| 1 | *2* |\n| 1 | 2 | 3 | 4 | 5 |"
+        `parsesTo` Table
+          [CellDefault, CellLeft, CellCenter, CellRight]
+          [[Str "a"], [Str "b"], [Str "c"], [Str "d"]]
+          [[[Str "1"], [Emph [Str "2"]], [], []], [[Str "1"], [Str "2"], [Str "3"], [Str "4"]]]
+    it "keeps raw HTML as text, without its comments" $ do
+      "<div>\n*hi*\n</div>" `parsesTo` para "<div>\n*hi*\n</div>"
+      "a <b>bold</b>" `inlineOf` [Str "a <b>bold</b>"]
+      "<div>\n<!-- note -->\n</div>" `parsesTo` para "<div>\n\n</div>"
+      "<div>\n<!-->\nkept\n</div>" `parsesTo` para "<div>\n\nkept\n</div>"
+      "<div>\n<!--->\nkept\n</div>" `parsesTo` para "<div>\n\nkept\n</div>"
+      "a <!-- note --> b" `inlineOf` [Str "a  b"]
+      parseMarkdownBlocks "<!-- note -->\n<!--\nlonger\n-->\n\nshown" `shouldBe` [para "shown"]
+
+  describe "inlines" $ do
+    it "parses emphasis, strong emphasis and strikethrough" $
+      "*a* **b** ***c*** ~~d~~"
+        `inlineOf` [Emph [Str "a"], Str " ", Strong [Str "b"], Str " ", Emph [Strong [Str "c"]], Str " ", Strike [Str "d"]]
+    it "parses code spans and line breaks" $
+      "`a`  \nb\\\nc\nd" `inlineOf` [Code "a", HardBreak, Str "b", HardBreak, Str "c", SoftBreak, Str "d"]
+    it "parses links and images" $
+      "[a *b*](/u \"t\") ![alt](/i.png)"
+        `inlineOf` [Link "/u" "t" [Str "a ", Emph [Str "b"]], Str " ", Image "/i.png" "" [Str "alt"]]
+    it "resolves reference links" $
+      parseMarkdownBlocks "[a] [text][B]\n\n[a]: /1\n[b]: </2> \"two\""
+        `shouldBe` [Paragraph [Link "/1" "" [Str "a"], Str " ", Link "/2" "two" [Str "text"]]]
+    it "links autolinks and bare web and email addresses" $ do
+      "<https://a.b/c> https://x.org/a. www.x.org"
+        `inlineOf` [ Link "https://a.b/c" "" [Str "https://a.b/c"]
+                   , Str " "
+                   , Link "https://x.org/a" "" [Str "https://x.org/a"]
+                   , Str ". "
+                   , Link "http://www.x.org" "" [Str "www.x.org"]
+                   ]
+      "mail a.b+c@x.org." `inlineOf` [Str "mail ", Link "mailto:a.b+c@x.org" "" [Str "a.b+c@x.org"], Str "."]
+    it "decodes escapes and entities into one piece of text" $
+      "\\*a\\* &amp; &ouml; &#65; &bogus;" `inlineOf` [Str "*a* & \246 A &bogus;"]
+  where
+    -- The single block a text parses to, or the spans of its single paragraph.
+    parsesTo src b = parseMarkdownBlocks src `shouldBe` [b]
+    inlineOf src spans = parsesTo src (Paragraph spans)
+    para t = Paragraph [Str t]
+    item = ListItem Nothing
diff --git a/test/Render.hs b/test/Render.hs
new file mode 100644
--- /dev/null
+++ b/test/Render.hs
@@ -0,0 +1,466 @@
+-- | Drawing documents in a headless context.
+module Render (spec) where
+
+import Control.Concurrent (threadDelay)
+import Control.Monad (forM, forM_, replicateM_, void, when)
+import Data.Foldable (toList)
+import Data.Function (on)
+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)
+import Data.List (find, groupBy, nub, sortOn)
+import Data.Maybe (isJust)
+import Data.Text (Text)
+import Data.Text qualified as T
+import GHC.Clock (getMonotonicTime)
+import NanoUI
+  ( Color, ImageId (..), NanoUI, Rect (..), Size (..), Style (..), TextFont (..), Theme (..)
+  , V2 (..), WidgetId, background, colorRGBA, columnWith, fillW, fixedH, fixedW, fontColor, foreground
+  , label, padAll, panel, rectIntersect, respId, scrollWith', liftIO, tight, withKey
+  )
+import NanoUI.Widgets.Custom (DrawOp (..), checkboxBoxSize, drawCheckbox, runCanvasFor)
+import NanoUI.Backend (FontBackend (..), FontMetrics (..), monospaceMetrics)
+import NanoUI.Internal.Context (Context (..), CustomDrawingEntry (..), getTheme, lookupCustomDrawing)
+import NanoUI.Internal.Layout.Arena (NodeType (..))
+import NanoUI.Internal.Widgets.Custom (mkCustomDrawContext)
+import NanoUI.Markdown
+import NanoUI.Testing
+  ( Damage (..), collectTextSpans, newContext, runFrame, takeDamage, withClipboard
+  , lineWidth, withFontMetrics
+  )
+import NanoUI.Testing.Assert (withInput)
+import NanoUI.Testing.Harness
+  (drawnVertices, hasText, nodesOfType, runClick, spanCenter, spanRect, spanRectOf, vertexColor, warmup2)
+import NanoUI.Testing.Sim hiding (spans)
+import NanoUI.Shortcut (cmdOrCtrl, key)
+import Test.Hspec
+
+-- | A drawn rich-text word: widget, line box origin, font size, text and
+-- colour.
+data Word' = Word' {wWidget :: WidgetId, wPos :: V2, wSize :: Float, wText :: Text, wColor :: Color}
+  deriving (Show)
+
+-- | The frame's custom drawings (rich text and canvases) as id, content key
+-- and ops, in document order.
+drawings :: Context -> IO [(WidgetId, Int, [DrawOp])]
+drawings ctx = do
+  nodes <- nodesOfType NodeDrawing ctx
+  fmap concat . forM nodes $ \(wid, r) -> do
+    entry <- lookupCustomDrawing ctx wid
+    cdc <- mkCustomDrawContext ctx (ctxFontMetrics ctx) wid
+    pure [(wid, cdrContent e, toList (cdrBuild e cdc r)) | Just e <- [entry]]
+
+-- | Every word the frame's rich-text widgets draw, in document order.
+drawnWords :: Context -> IO [Word']
+drawnWords ctx = do
+  ds <- drawings ctx
+  pure [Word' wid (V2 tx ty) (textFontSize font) t c | (wid, _, ops) <- ds, DrawTextStyled tx ty font t c <- ops]
+
+-- | The frame's list markers (drawings with no text), in document order.
+markers :: Context -> IO [(WidgetId, Int, [DrawOp])]
+markers ctx = filter (\(_, _, ops) -> not (any isText ops)) <$> drawings ctx
+  where
+    isText = \case DrawTextStyled {} -> True; DrawText {} -> True; _ -> False
+
+wordNamed :: Text -> [Word'] -> Maybe Word'
+wordNamed t = find ((== t) . wText)
+
+-- | The texts of the frame's drawn words.
+wordTexts :: Context -> IO [Text]
+wordTexts ctx = map wText <$> drawnWords ctx
+
+-- | A point @dx@ in from the left of the drawn word, half a line down.
+inWord :: Context -> Float -> Text -> IO V2
+inWord ctx dx w = do
+  Just (Word' _ (V2 x y) _ _ _) <- wordNamed w <$> drawnWords ctx
+  pure (V2 (x + dx) (y + fmLineHeight (ctxFontMetrics ctx) / 2))
+
+-- | Rects that rich-text widgets fill in a colour: backgrounds and
+-- decorations.
+drawnFills :: Color -> Context -> IO [Rect]
+drawnFills c ctx = do
+  ds <- drawings ctx
+  pure [rect | (_, _, ops) <- ds, FillRect rect c' <- ops, c' == c]
+
+-- | Whether a fully painted frame draws anything in the colour.
+paints :: Color -> NanoUI a -> IO Bool
+paints c ui = do
+  ctx <- drawn 600 400 ui
+  writeIORef (ctxPaintFull ctx) True
+  (_, dd, _) <- runFrame ctx (withInput 600 400) ui
+  elem c . map vertexColor <$> drawnVertices dd
+
+-- | A fresh context that has drawn the view twice in a @w@ by @h@ window.
+drawn :: Float -> Float -> NanoUI a -> IO Context
+drawn w h ui = newContext >>= \ctx -> ctx <$ warmup2 ctx (withInput w h) ui
+
+-- | Run a script against the view in a @w@ by @h@ window of the context,
+-- stopping at the first failed check.
+sim :: Context -> Float -> Float -> NanoUI a -> Sim a r -> IO r
+sim ctx w h ui script = newIORef 0 >>= \failed -> runSimWith opts ctx failed (withInput w h) ui script
+  where
+    opts = defaultSimOptions {simFailFast = True}
+
+-- | A fresh context with a clipboard the returned ref holds.
+copying :: IO (Context, IORef (Maybe Text))
+copying = do
+  copied <- newIORef Nothing
+  base <- newContext
+  pure (withClipboard base (readIORef copied) (\t -> True <$ writeIORef copied (Just t)), copied)
+
+-- | Ctrl (Cmd on macOS) with each key in turn.
+chords :: [Char] -> Sim a ()
+chords = mapM_ (chord . (cmdOrCtrl <>) . key)
+
+-- | 'inWord' in the script's frame.
+wordAt :: Float -> Text -> Sim a Target
+wordAt dx w = At <$> onContext (\ctx -> inWord ctx dx w)
+
+-- | Draw a document, append text and draw again. For each pair, the first
+-- word's id before must equal the second word's id after. The @new@ words
+-- must be drawn.
+idsAcross :: Text -> Text -> [(Text, Text)] -> [Text] -> Expectation
+idsAcross start more same new = do
+  cache <- newMarkdownCache
+  let doc = parseMarkdown start
+  ctx <- drawn 600 600 (view cache doc)
+  was <- drawnWords ctx
+  _ <- warmup2 ctx (withInput 600 600) (view cache (appendMarkdown more doc))
+  now <- drawnWords ctx
+  let idOf w ws = wWidget <$> wordNamed w ws
+  mapM_ (\(w, w') -> (w', isJust (idOf w was), idOf w' now) `shouldBe` (w', True, idOf w was)) same
+  mapM_ (\w -> map wText now `shouldContain` [w]) new
+
+view :: MarkdownCache -> MarkdownDoc -> NanoUI (Maybe Text)
+view cache doc = columnWith (fixedW 500 . padAll 10) (markdown cache doc)
+
+-- | Click a drawn word in a 600 by 400 window and return the reported link.
+clickWord :: NanoUI (Maybe Text) -> Text -> IO (Maybe Text)
+clickWord ui w = newContext >>= \ctx -> sim ctx 600 400 ui $ do
+  p <- wordAt 3 w
+  _ <- moveTo p
+  click p
+
+-- | Resolves only cat.png, at 40 by 30.
+catImages :: MarkdownConfig
+catImages = defaultMarkdownConfig {mdImage = \src -> if src == "cat.png" then Just (ImageId 7, Size 40 30) else Nothing}
+
+-- | Draws Haskell code blocks as a plain label, and every other block as the
+-- default widget does.
+customCode :: MarkdownConfig
+customCode =
+  defaultMarkdownConfig
+    { mdBlock = \own -> \case
+        CodeBlock "hs" code -> Nothing <$ label ("custom " <> code)
+        b -> own b
+    }
+
+spec :: Spec
+spec = before newMarkdownCache $ do
+  it "holds a few passes' blocks however many keys churn, and every block a frame draws" $ \cache -> do
+    ctx <- newContext
+    let
+      doc = parseMarkdown (T.intercalate "\n\n" ["paragraph " <> T.pack (show i) | i <- [1 .. 50 :: Int]])
+      frameOf ui = void (runFrame ctx (withInput 600 400) ui)
+    -- Fresh keys every frame: 6000 blocks over the run, 50 of them live.
+    forM_ [1 .. 120 :: Int] $ \n -> frameOf (void (withKey n (markdown cache doc)))
+    markdownCacheSize cache >>= (`shouldSatisfy` (\n -> n >= 50 && n <= 2048))
+    -- Sixty documents sharing the blocks.
+    replicateM_ 4 (frameOf (forM_ [1 .. 60 :: Int] $ \i -> withKey i (markdown cache doc)))
+    markdownCacheSize cache >>= (`shouldSatisfy` (>= 3000))
+
+  it "scales headings and small text from the backend's default font size" $ \cache -> do
+    -- Text height equals font size in this resolver; the body size is 20.
+    ctx <- (`withFontMetrics` monospaceMetrics 20) <$> newContext
+    _ <- warmup2 ctx (withInput 600 800) . view cache . parseMarkdown $
+      "# h1\n\n## h2\n\n### h3\n\n#### h4\n\n##### h5\n\n###### h6\n\nbody\n\n```\ncode\n```"
+    ws <- drawnWords ctx
+    let size w = maybe 0 wSize (wordNamed w ws)
+    map (round . (* 100) . size) ["body", "h1", "h2", "h3", "h4", "h5", "h6"]
+      `shouldBe` [2000, 3200, 2700, 2400, 2100, 2000, 1800 :: Int]
+    -- The copy button's text is 0.8 times the body size.
+    fmap (\(Rect _ _ _ h) -> h) . spanRect "Copy" <$> collectTextSpans ctx `shouldReturn` Just 16
+
+  it "selects and copies styled Markdown text" $ \cache -> do
+    (ctx, copied) <- copying
+    sim ctx 600 400 (view cache (parseMarkdown "Select **these** words")) $ do
+      start <- wordAt 1 "Select"
+      finish <- wordAt (lineWidth (ctxFontMetrics ctx) "these" - 1) "these"
+      _ <- drag start finish 1
+      selectionColor <- themeSelection <$> liftIO (getTheme ctx)
+      check . not . null =<< liftIO (drawnFills selectionColor ctx)
+      chords ['c']
+      checkEq (Just "Select these") =<< liftIO (readIORef copied)
+      chords ['a', 'c']
+      checkEq (Just "Select these words") =<< liftIO (readIORef copied)
+
+  it "copies code blocks, whitespace kept, by selection and by the copy button" $ \cache -> do
+    (ctx, copied) <- copying
+    sim ctx 600 400 (view cache (parseMarkdown "```hs\tlinenos\n  let x = 1\n```")) $ do
+      -- The language runs up to the first space or tab.
+      check =<< labelShown "hs"
+      _ <- click =<< wordAt 1 "  let x = 1"
+      chords ['a', 'c']
+      checkEq (Just "  let x = 1") =<< liftIO (readIORef copied)
+    sim ctx 600 400 (view cache (parseMarkdown "```\nlet x = 1\n  in x\n```")) $ do
+      _ <- click "Copy"
+      checkEq (Just "let x = 1\n  in x") =<< liftIO (readIORef copied)
+
+  it "keeps earlier blocks' ids while text streams in" $ \_ -> do
+    -- The growing block keeps its id too.
+    idsAcross "para one\n\n- item two\n\nstrea" "ming on\n\n# new block" [("one", "one"), ("two", "two"), ("strea", "streaming")] ["new"]
+    -- A list's second item grows and gains a nested list and a sibling. A
+    -- quote's second paragraph grows and a third follows.
+    idsAcross "- first\n- sec" "ond\n  - nested\n- third" [("first", "first"), ("sec", "second")] ["nested", "third"]
+    idsAcross "> quoted\n>\n> gro" "wing\n>\n> after" [("quoted", "quoted"), ("gro", "growing")] ["after"]
+
+  it "measures and repaints only the block that grew when text is appended" $ \cache -> do
+    base <- newContext
+    measured <- newIORef []
+    inView <- newIORef False
+    -- Record texts measured while the view runs. Rich text lays out its words
+    -- then; painting comes later.
+    let fm = ctxFontMetrics base
+        prepare t = readIORef inView >>= \recording -> fm <$ when recording (modifyIORef' measured (t :))
+        ctx = withFontMetrics base fm {fmBackend = Just (FontBackend prepare (const (pure Nothing)))}
+        inp = withInput 600 600
+        doc1 = parseMarkdown "first alpha\n\nsecond beta\n\nthird gam"
+        doc2 = appendMarkdown "ma delta" doc1
+        measuring doc = do
+          writeIORef measured []
+          void (runFrame ctx inp (liftIO (writeIORef inView True) *> view cache doc <* liftIO (writeIORef inView False)))
+          readIORef measured
+    measuring doc1 >>= (`shouldContain` ["first"])
+    _ <- measuring doc1
+    writeIORef (ctxPaintFull ctx) False
+    words' <- measuring doc2
+    words' `shouldContain` ["delta"]
+    mapM_ (\w -> words' `shouldNotContain` [w]) ["first", "alpha", "second", "beta"]
+    -- The damage covers only the line that grew.
+    damage <- takeDamage ctx
+    ws <- drawnWords ctx
+    let hit w = [isJust (rectIntersect r (Rect 0 y 600 (fmLineHeight fm))) | DamageClip r <- [damage], Word' _ (V2 _ y) _ _ _ <- toList (wordNamed w ws)]
+    map hit ["alpha", "beta", "gamma"] `shouldBe` [[False], [False], [True]]
+    -- Redrawing the same document measures nothing.
+    measuring doc2 `shouldReturn` []
+
+  it "wraps a code line wider than the document, keeping all of it, its indent and its spaces" $ \cache -> do
+    let
+      long = "a_long_identifier_much_wider_than_the_column_it_is_drawn_in"
+      indented = "    x  =  alpha  beta  gamma  delta  epsilon  zeta  eta  theta"
+      -- No fixed-width ancestor: the column fills the window.
+      codeIn w src = drawn w 400 . columnWith (fillW . padAll 10) . markdown cache $
+        parseMarkdown ("```\n" <> src <> "\n```")
+    code <- drawnWords =<< codeIn 400 ("first\n" <> long <> "\nlast")
+    let
+      texts = map wText code
+      middle = takeWhile (/= "last") (drop 1 (dropWhile (/= "first") texts))
+    mapM_ (\t -> texts `shouldContain` [t]) ["first", "last"]
+    T.concat middle `shouldBe` long
+    length middle `shouldSatisfy` (> 1)
+    -- Every wrapped line starts within the code block's available width.
+    mapM_ (\w -> let V2 x _ = wPos w in x < 390 `shouldBe` True) code
+    wrapped <- wordTexts =<< codeIn 300 indented
+    length wrapped `shouldSatisfy` (> 1)
+    take 1 wrapped `shouldSatisfy` all ("    x  =  " `T.isPrefixOf`)
+    -- Each line is a substring of the source line, spaces included.
+    mapM_ (\t -> (t, t `T.isInfixOf` indented) `shouldBe` (t, True)) wrapped
+
+  it "lets the wheel over a code block scroll the page" $ \cache -> do
+    ctx <- newContext
+    let paras n = T.concat ["para " <> T.pack (show i) <> "\n\n" | i <- [1 .. n :: Int]]
+        doc = parseMarkdown (paras 3 <> "```\ncode\n```\n\n" <> paras 30)
+        ui = scrollWith' (fillW . fixedH 280) (columnWith (fillW . padAll 10) (markdown cache doc))
+    sim ctx 400 300 ui $ do
+      (_, scroller) <- result
+      let sid = respId scroller
+      _ <- (`wheel` V2 0 3) =<< wordAt 0 "code"
+      -- Let the glide settle.
+      replicateM_ 30 (advance 0.05)
+      check . (/= 0) =<< scrollOffsetOf sid
+
+  it "draws a resolved image, which returns its source when clicked, and the rest as alt text" $ \cache -> do
+    let ui = columnWith (fixedW 500) (markdownConfigured cache catImages (parseMarkdown "![a cat](cat.png)\n\n![a dog](dog.png)"))
+    ctx <- drawn 600 400 ui
+    images <- map snd <$> nodesOfType NodeImage ctx
+    case images of
+      [r@(Rect _ _ w h)] -> do
+        (w, h) `shouldBe` (40, 30)
+        runClick ctx (withInput 600 400) ui (spanCenter r) `shouldReturn` Just "cat.png"
+      _ -> expectationFailure ("expected one image, got " <> show images)
+    ws <- wordTexts ctx
+    ws `shouldContain` ["dog"]
+    ws `shouldNotContain` ["cat"]
+    -- An image it does not draw is a link to its source.
+    let alt = view cache (parseMarkdown "See ![the diagram](diagram.png) here.")
+    actx <- drawn 600 400 alt
+    theme <- readIORef (ctxTheme actx)
+    fmap wColor . wordNamed "diagram" <$> drawnWords actx `shouldReturn` Just (themeLink theme)
+    clickWord alt "diagram" `shouldReturn` Just "diagram.png"
+
+  it "sends a click on an image in a link to the link, and shows the link's title over it" $ \cache -> do
+    let ui = columnWith (fixedW 500) (markdownConfigured cache catImages (parseMarkdown "[![a cat](cat.png)](https://cats.example \"All about cats\")"))
+    ctx <- newContext
+    sim ctx 600 400 ui $ do
+      [r] <- map snd <$> onContext (nodesOfType NodeImage)
+      _ <- moveTo (Within r)
+      expectNot "All about cats"
+      -- Hover until the wake the tooltip asked for, as a backend's loop
+      -- sleeps until it. The delay runs on the monotonic clock, not on
+      -- frame time, so no input delta can stand in for it.
+      wakeAt <- wakeTime
+      check (wakeAt > 0)
+      now <- liftIO getMonotonicTime
+      liftIO (threadDelay (ceiling ((wakeAt - now) * 1e6) + 1000))
+      _ <- frame
+      expect "All about cats"
+      checkEq (Just "https://cats.example") =<< click (Within r)
+
+  it "gives a paragraph that turns into a drawn image fresh ids" $ \cache -> do
+    let ui = columnWith (fixedW 500) . markdownConfigured cache catImages
+        unfinished = parseMarkdown "![a cat](cat.png"
+    ctx <- drawn 600 400 (ui unfinished)
+    textIds <- nub . map wWidget <$> drawnWords ctx
+    _ <- warmup2 ctx (withInput 600 400) (ui (appendMarkdown ")" unfinished))
+    imageIds <- map fst <$> nodesOfType NodeImage ctx
+    (length textIds, length imageIds) `shouldBe` (1, 1)
+    imageIds `shouldNotBe` textIds
+
+  it "sizes an ordered list's markers by its widest number" $ \cache -> do
+    -- "1" is narrow, so "10." is wider than the last marker, "11.".
+    base <- newContext
+    let fm = (monospaceMetrics 16) {fmAdvance = \c -> case c of '1' -> 2; 'x' -> 7; _ -> 8}
+        ctx = withFontMetrics base fm
+    _ <- warmup2 ctx (withInput 600 400) (view cache (parseMarkdown "10. ten\n11. eleven\n"))
+    fmap (\(Rect _ _ w _) -> w) . spanRectOf "10." <$> collectTextSpans ctx `shouldReturn` Just 18
+
+  it "keeps wrapped table text inside its rows on the first frame and after resizing" $ \cache -> do
+    let doc = parseMarkdown
+          "| Category | Keys |\n|---|---|\n\
+          \| Motions | `h j k l`, `w b e`, with counts and words that wrap across several lines |\n\
+          \| Operators | `d c y` with a motion, a text object, or doubled |\n\nAfter"
+        ui = columnWith fillW (markdown cache doc)
+        bottom (Rect _ y _ h) = y + h
+        rectTop (Rect _ y _ _) = y
+    ctx <- newContext
+    forM_ [400, 800, 280, 400, 400] $ \width -> do
+      _ <- runFrame ctx (withInput width 1200) ui
+      panels <- map snd <$> nodesOfType NodePanel ctx
+      ws <- drawnWords ctx
+      case panels of
+        [table, h1, h2, m1, m2, o1, o2] -> do
+          let cells = [h1, h2, m1, m2, o1, o2]
+          forM_ ws $ \word -> do
+            let V2 x y = wPos word
+            if wText word == "After"
+              then y `shouldSatisfy` (>= bottom table)
+              else cells `shouldSatisfy` any (\(Rect cx cy cw ch) -> x >= cx && x < cx + cw && y >= cy && y + wSize word <= cy + ch)
+          bottom h1 `shouldSatisfy` (<= rectTop m1)
+          bottom m2 `shouldSatisfy` (<= rectTop o2)
+          bottom table `shouldSatisfy` (\b -> abs (b - bottom o1 - 1) < 0.1)
+          (rectTop m1, bottom m1, bottom o1) `shouldBe` (rectTop m2, bottom m2, bottom o2)
+        _ -> expectationFailure ("expected a table and six cells, got " <> show panels)
+
+  it "lines a table cell's wrapped lines up as its column is aligned" $ \cache -> do
+    let cellText = "words that wrap over a few lines of a narrow column"
+        row = "| " <> T.intercalate " | " (replicate 3 cellText) <> " |"
+    ctx <- drawn 400 600 (columnWith (fixedW 380 . padAll 10) (markdown cache (parseMarkdown ("| l | r | c |\n|---|--:|:-:|\n" <> row))))
+    ws <- drawnWords ctx
+    -- The monospace test font is 12 wide per character.
+    let extent w = let V2 x _ = wPos w in (x, x + 12 * fromIntegral (T.length (wText w)))
+        cells = sortOn (map (fst . extent) . take 1) (filter (any ((== "narrow") . wText)) (groupBy ((==) `on` wWidget) ws))
+        lineExtents cell = [(minimum (map (fst . extent) l), maximum (map (snd . extent) l)) | l <- groupBy ((==) `on` (\w -> let V2 _ y = wPos w in y)) cell]
+    case map lineExtents cells of
+      [left, right, centre] -> do
+        map length [left, right, centre] `shouldSatisfy` all (> 1)
+        length (nub (map fst left)) `shouldBe` 1
+        length (nub (map snd right)) `shouldBe` 1
+        length (nub [round (x0 + x1) :: Int | (x0, x1) <- centre]) `shouldBe` 1
+      other -> expectationFailure ("expected three body cells, got " <> show (length other))
+
+  it "draws a quote's list markers in its muted text colour" $ \cache -> do
+    ctx <- drawn 600 400 (view cache (parseMarkdown "> - bullet\n>\n> text\n>\n> - [x] done\n"))
+    theme <- readIORef (ctxTheme ctx)
+    ms <- markers ctx
+    case map (\(_, _, ops) -> ops) ms of
+      [[FillCircle _ _ _ bullet], FillRoundedRect _ _ boxFill : _] -> (bullet, boxFill) `shouldBe` (themeMuted theme, themeMuted theme)
+      _ -> expectationFailure ("expected a bullet and a checked box, got " <> show (length ms) <> " markers")
+
+  it "draws a task item's box as nano-ui draws a checkbox, at the bullet's id and under another version" $ \cache -> do
+    ctx <- drawn 600 400 (view cache (parseMarkdown "- a\n"))
+    [(bulletId, bulletVersion, _)] <- markers ctx
+    _ <- warmup2 ctx (withInput 600 400) (view cache (parseMarkdown "- [ ] a\n"))
+    [(boxId, boxVersion, ops)] <- markers ctx
+    (boxId, boxVersion /= bulletVersion) `shouldBe` (bulletId, True)
+    theme <- readIORef (ctxTheme ctx)
+    let side = checkboxBoxSize (ctxFontMetrics ctx)
+    case ops of
+      [_, StrokeRoundedRect r@(Rect _ _ w h) _ _ _] -> do
+        (w, h) `shouldBe` (side, side)
+        cdc <- mkCustomDrawContext ctx (ctxFontMetrics ctx) boxId
+        ops == toList (runCanvasFor cdc (drawCheckbox theme r False)) `shouldBe` True
+      _ -> expectationFailure ("expected an unchecked box's two ops, got " <> show (length ops))
+
+  it "draws the blocks mdBlock draws, at every depth, and the rest as it would" $ \cache -> do
+    ctx <-
+      drawn 600 600 . columnWith (fixedW 500) . markdownConfigured cache customCode . parseMarkdown $
+        "```hs\ntop\n```\n\n> ```hs\n> quoted\n> ```\n\n- item\n\n  ```hs\n  listed\n  ```\n\n```py\nother\n```\n\nafter"
+    spans <- collectTextSpans ctx
+    map (`hasText` spans) ["custom top", "custom quoted", "custom listed"] `shouldBe` replicate 3 True
+    -- The language label exactly: the block's "Copy" button contains "py".
+    isJust (spanRectOf "py" spans) `shouldBe` True
+    wordTexts ctx `shouldReturn` ["item", "other", "after"]
+    -- Only the Python block uses the default widget, with its copy button.
+    length [() | (_, "Copy", _, _, _) <- spans] `shouldBe` 1
+
+  it "wraps the widget's own drawing in chrome of its own, where the block is, and returns its link" $ \cache -> do
+    let cfg :: MarkdownConfig
+        cfg =
+          defaultMarkdownConfig
+            { mdBlock = \own b -> case b of
+                Paragraph _ -> panel (own b)
+                _ -> own b
+            }
+        ui = columnWith (fixedW 500) . markdownConfigured cache cfg . parseMarkdown $
+          "See [the docs](/docs) or <https://auto.link>.\n\n> Quoted [link](/quoted)."
+    clickWord ui "docs" `shouldReturn` Just "/docs"
+    clickWord ui "https://auto.link" `shouldReturn` Just "https://auto.link"
+    clickWord ui "link" `shouldReturn` Just "/quoted"
+    clickWord ui "See" `shouldReturn` Nothing
+    -- The quoted paragraph keeps the quote's muted colour.
+    ctx <- drawn 600 400 ui
+    theme <- readIORef (ctxTheme ctx)
+    fmap wColor . wordNamed "Quoted" <$> drawnWords ctx `shouldReturn` Just (themeMuted theme)
+
+  it "styles inline code, quotes, table cells and code blocks over their own look" $ \cache -> do
+    let tint = colorRGBA 1 2 3 255
+        codeInk = colorRGBA 40 50 60 255
+        quoteInk = colorRGBA 70 80 90 255
+        cellInk = colorRGBA 100 110 120 255
+        cfg =
+          (defaultMarkdownConfig :: MarkdownConfig)
+            { mdInlineCode = fontColor codeInk
+            , mdInlineCodeBackground = Just tint
+            , mdQuote = fontColor quoteInk
+            , mdTableCell = \header -> if header then id else foreground cellInk
+            }
+        ui c = columnWith (fixedW 500) (markdownConfigured cache c (parseMarkdown "Run `build` now.\n\n> quoted\n\n| head |\n|---|\n| cell |"))
+    ctx <- drawn 600 400 (ui cfg)
+    ws <- drawnWords ctx
+    theme <- readIORef (ctxTheme ctx)
+    map (fmap wColor . (`wordNamed` ws)) ["build", "quoted", "cell", "head", "Run"]
+      `shouldBe` map Just [codeInk, quoteInk, cellInk, styleFgOf theme, styleFgOf theme]
+    -- The background covers only the code.
+    Just code <- pure (wordNamed "build" ws)
+    [Rect x _ _ _] <- drawnFills tint ctx
+    x `shouldBe` let V2 cx _ = wPos code in cx
+    (drawnFills tint =<< drawn 600 400 (ui defaultMarkdownConfig)) `shouldReturn` []
+    let block c = columnWith (fixedW 500) (markdownConfigured cache (defaultMarkdownConfig :: MarkdownConfig) {mdCodeBlock = background c} (parseMarkdown "```\ncode\n```"))
+    paints tint (block tint) `shouldReturn` True
+    paints tint (block (colorRGBA 9 9 9 255)) `shouldReturn` False
+
+  it "applies layout modifiers via markdownWith" $ \cache -> do
+    let doc = parseMarkdown "hello markdown"
+    ctx <- drawn 600 400 (columnWith tight (markdownWith (fixedW 220 . padAll 12) cache doc))
+    ws <- drawnWords ctx
+    fmap wPos (wordNamed "hello" ws) `shouldBe` Just (V2 12 12)
+  where
+    styleFgOf theme = styleFg (themePanel theme)
