These docs describe the main branch, including unreleased changes. Read the 0.9.9 docs.

Markdown

Markdown renders CommonMark with the GitHub tables, strikethrough, task lists and autolinks. OpenTUI’s native Markdown engine parses it as it streams in and writes paragraphs and headings itself; fenced code blocks can use Tree-sitter highlighting. Use Code when the full content is source code.

Availability#

Field Availability
Package @opentui/core
Core renderable MarkdownRenderable
React <markdown> (automatic)
Solid <markdown> (automatic)
Status Built in

Basic usage#

Renderable API#

import { MarkdownRenderable, SyntaxStyle, RGBA, createCliRenderer } from "@opentui/core"

const renderer = await createCliRenderer()

const syntaxStyle = SyntaxStyle.fromStyles(
  {
    "markup.heading.1": { fg: RGBA.fromHex("#58A6FF"), bold: true },
    "markup.list": { fg: RGBA.fromHex("#FF7B72") },
    "markup.raw": { fg: RGBA.fromHex("#A5D6FF") },
    default: { fg: RGBA.fromHex("#E6EDF3") },
  },
  renderer.nativeScene,
)

const markdown = new MarkdownRenderable(renderer, {
  id: "readme",
  width: 60,
  content: "# Hello\n\n- One\n- Two\n\n```ts\nconst x = 1\n```",
  syntaxStyle,
})

renderer.root.add(markdown)

Fenced language normalization#

Markdown normalizes each code fence info string to a file type before Tree-sitter highlighting:

  • tsx -> typescriptreact
  • .jsx -> javascriptreact
  • TSX title=Button.tsx -> typescriptreact
  • Dockerfile -> dockerfile

Markdown uses infoStringToFiletype() for this step. To add or change mappings at runtime, edit the maps that it reads:

import { extensionToFiletype, basenameToFiletype } from "@opentui/core"

extensionToFiletype.set("templ", "html")
basenameToFiletype.set("mytoolrc", "yaml")

Concealment#

Set conceal: true to hide Markdown markers, such as backticks and emphasis markers:

const markdown = new MarkdownRenderable(renderer, {
  content: "**bold** and `code`",
  syntaxStyle,
  conceal: true,
})

concealCode controls concealment inside fenced code blocks separately. Its default is false.

With conceal on, a task item shows ☐ or ☑. Set taskMarkers to show other boxes, such as ASCII ones:

const markdown = new MarkdownRenderable(renderer, {
  content: "- [ ] write tests\n- [x] fix the bug",
  syntaxStyle,
  taskMarkers: { unchecked: "[ ]", checked: "[x]" },
})

The box is part of the item’s marker, so wrapped item text lines up after it. Without conceal, items show the source’s [ ] or [x].

Streaming updates#

Use streaming mode when content arrives in chunks. Keep streaming: true while you append chunks. When the content is complete, set markdown.streaming = false; the document then shows as it would from one content without streaming.

const markdown = new MarkdownRenderable(renderer, {
  content: "",
  syntaxStyle,
  streaming: true,
})

markdown.content += "# Live log\n"
markdown.content += "- line 1\n"
markdown.streaming = false

Content that extends the previous content is appended: the engine reads only the new text, and when it only grows a paragraph or heading, it writes that block’s text natively with no text work in JavaScript (in a terminal that shows links, with conceal on, and for blocks the inline hook does not rewrite; otherwise JavaScript writes the block’s styled text). Other content is parsed again, and blocks equal to the shown ones keep their renderables.

While streaming, the last line shows as far as it is decided. A line that may still become a table row, a fence’s end, a rule or a heading’s underline waits for its end, and an emphasis or code span that has not closed yet draws as if it had. So a block’s kind never flips back and forth on screen.

Committed blocks#

markdown.committedBlockCount is the number of top-level blocks at the start of the document whose rows are final: they equal the rows a render of the finished document draws, with one exception: a link reference definition that arrives after a committed block used its label turns that label into a link on screen, while rows already written out keep the old text. It never goes down while content only grows. markdown.blocks lists every block in document order (the index is the block’s id) with its kind and the renderable that shows it. Together they let an app write finished rows out once, for example to terminal scrollback with ScrollbackSurface: write each committed block’s rows together with the blank row above it.

md.content = "# Title\n\nPara 1"
// md.committedBlockCount is 1: the heading is final; "Para 1" can still grow.

md.content = "# Title\n\nPara 1\n\nPara 2"
// md.committedBlockCount is 2: "Para 1" ended at the blank line.

Markdown tables#

Use tableOptions to set the style, sizing, wrapping, borders, and selection of Markdown tables. Each column aligns its cells, the header included, as the delimiter row says: :--- or --- left, :---: centered, ---: right.

const markdown = new MarkdownRenderable(renderer, {
  content: "| Service | Status |\n| --- | --- |\n| api | ok |",
  syntaxStyle,
  tableOptions: {
    style: "grid",
    widthMode: "full",
    columnFitter: "balanced",
    wrapMode: "word",
    cellPadding: 1,
    cellPaddingX: 2,
    cellPaddingY: 0,
    borders: true,
    outerBorder: true,
    borderStyle: "rounded",
    borderColor: "#6b7280",
    selectable: true,
  },
})

tableOptions#

Option Type Default Description
style "grid" | "columns" "grid" Visual preset (see Table styles)
widthMode "content" | "full" depends on style "full" expands columns to fill available width
columnFitter "proportional" | "balanced" "proportional" How columns shrink when space is constrained
wrapMode "none" | "char" | "word" "word" Wrapping mode inside each table cell
cellPadding number 0 Padding on all sides of each cell
cellPaddingX number cellPadding Horizontal padding on each side
cellPaddingY number cellPadding Vertical padding on each side
borders boolean depends on style Enable inner and outer borders
outerBorder boolean borders Override outer border visibility
borderStyle BorderStyle "single" Table border character set
borderColor ColorInput conceal fg or #888888 Border color for markdown tables
selectable boolean true Enable table cell text selection

Table styles#

tableOptions.style picks a preset. The preset sets the defaults for borders, outerBorder, and widthMode:

  • "grid": a boxed table with visible borders. Defaults to borders: true and widthMode: "full". This is the normal table rendering.
  • "columns": borderless columns with a 2-column gap. Defaults to borders: false and widthMode: "content". Use it for append-only output where a full-width grid is too heavy.

This Name/Status sample shows both presets:

Grid:

Columns:

If you do not pass style, it is "grid". Individual fields, such as borders: true, override the preset defaults.

Custom block rendering#

Use renderBlock to replace the renderable for a top-level block or a code block at any depth. It gets a MarkdownBlock: kind ("paragraph", "heading", "code", "html", "rule", "table", "quote", "list" and so on), index (its id), level, ordered, start, checked, lang, info, closed, and, read when you ask, raw (its source), text and children. Return undefined or null to use the default renderable, or call context.defaultRender() to get it yourself; a renderable you return may hold it. renderBlock runs again when the block changes, when a style option (such as syntaxStyle, fg, or conceal) changes, and when streaming changes. Its result replaces the old renderable, which is destroyed, so return a new renderable on each call:

const markdown = new MarkdownRenderable(renderer, {
  content: "# Title\n\nHello",
  syntaxStyle,
  renderBlock: (block, context) => {
    if (block.kind === "heading") return new TextRenderable(renderer, { content: `>> ${block.text}` })
    return context.defaultRender()
  },
})

Custom fenced-code languages#

Use createMarkdownCodeBlockRenderer to replace only specific fenced-code languages. It matches each key against the normalized info string. A tsx fence matches the key typescriptreact. A custom name such as taskflow matches itself.

import {
  BoxRenderable,
  MarkdownRenderable,
  SyntaxStyle,
  TextRenderable,
  createMarkdownCodeBlockRenderer,
  type CliRenderer,
  type MarkdownCodeBlockRenderer,
} from "@opentui/core"

const syntaxStyle = SyntaxStyle.fromStyles({ default: {} }, renderer.nativeScene)

const renderTaskFlow =
  (renderer: CliRenderer): MarkdownCodeBlockRenderer =>
  (block) => {
    const steps = block.text
      .split("\n")
      .filter((line) => line.startsWith("step "))
      .map((line) => line.slice("step ".length))

    const card = new BoxRenderable(renderer, {
      border: true,
      borderStyle: "rounded",
      borderColor: "#38BDF8",
      paddingX: 1,
      flexDirection: "column",
      width: "100%",
    })

    for (const step of steps) {
      card.add(new TextRenderable(renderer, { content: `- ${step}`, width: "100%" }))
    }

    return card
  }

const markdown = new MarkdownRenderable(renderer, {
  content: "```taskflow\nstep Parse markdown done\nstep Render widget active\n```",
  syntaxStyle,
  renderBlock: createMarkdownCodeBlockRenderer({
    taskflow: renderTaskFlow(renderer),
  }),
})

A code-block renderer gets a MarkdownCodeBlock: type: "code", lang, info, text (the code), raw and closed, which says whether the closing fence arrived (a fence the stream left open is not closed, even once the stream ends).

Inline hooks and math#

inlineHook rewrites the display text of every paragraph, heading and table cell before it shows, for example to show IDs as titled links. It gets the parser’s spans (text, styles, link, code, math) and the block’s source, and returns the spans to show; a span’s target in a paragraph or heading makes it clickable through markdown.targetAt(x, y) (targets in table cells are not). targetAt answers for what the last frame drew: after the text changes (a new content, a rename through rerunInlineHook), it answers from the next frame. inlineHookFilter: ["ses_"] runs the hook only on blocks whose source holds one of the strings, so other blocks stay on the native path; an empty filter runs it on none. The filter holds at most 16 strings of 1 to 64 bytes, 256 bytes in all, and the source at most 64 MiB. rerunInlineHook(select) runs it again for the blocks whose source select accepts, without parsing anything.

extensions: ["math"] parses $…$ and \(…\) as inline math (a span with math set) and $$ or \[ lines as display math, a code block of the language math, so createMarkdownCodeBlockRenderer({ math }) renders it.

Properties#

Property Type Default Description
content string "" Markdown source
syntaxStyle SyntaxStyle required Style definitions for the Markdown scopes
fg ColorInput - Base foreground color, also used by inner code blocks
bg ColorInput - Base background color, also used by inner code blocks
conceal boolean true Hide markdown markers in markdown text
concealCode boolean false Hide markers inside fenced code blocks
taskMarkers MarkdownTaskMarkers ☐ and ☑ Task boxes with conceal on
streaming boolean false More content is coming. Set false to finish
tableOptions MarkdownTableOptions - Options for markdown table rendering
treeSitterClient TreeSitterClient - Custom Tree-sitter client for code blocks
renderBlock (block: MarkdownBlock, context: RenderNodeContext) => Renderable | null | undefined - Custom renderer for top-level blocks and code blocks
inlineHook MarkdownInlineHook - Rewrites prose and table cell spans before they show
inlineHookFilter readonly string[] - Runs the hook only on blocks that hold a string
extensions readonly "math"[] [] Delimiter extensions to parse

Markdown applies content, streaming, conceal, taskMarkers, syntaxStyle and the hook options at once. It restyles its renderables for syntaxStyle, fg, bg, conceal and concealCode changes in its lifecycle pass (onLifecyclePass), which Core runs before layout, so the new styles appear in that frame. A theme change repaints the natively written text and parses nothing again. If you assign onLifecyclePass on a Markdown renderable, call refreshStyles() after each change.

Migrating from 0.8#

0.9.0 replaces the marked-based parser with the native engine. What changes for apps:

  • renderNode(token, context) is now renderBlock(block, context). Switch on block.kind instead of token.type (blockquote is quote, hr is rule); token.raw is block.raw, token.text is block.text, token.lang is block.lang. There is no inline token tree; use inlineHook for inline content. The React and Solid prop is renderBlock too.
  • MarkdownCodeBlockRenderer gets a MarkdownCodeBlock instead of Tokens.Code, with closed (the closing fence arrived). A renderer that checked raw for a closing fence can read closed. The default renderable’s id is still ${markdown.id}-block-${index}, now with the block’s index in document order, counting nested blocks.
  • internalBlockMode is gone: every document renders its top-level blocks as separate renderables, one blank row apart. Apps on the old default ("coalesced") see blank rows between some blocks they used to join. Top-level mode’s default table style, "columns", is gone too: set tableOptions.style: "columns" for it.
  • BlockState, ParseState, _parseState, _blockStates and _stableBlockCount are gone. Use blocks and committedBlockCount, which counts final blocks only (see Committed blocks).
  • marked is no longer a dependency, and marked extension objects are no longer used.
  • Paragraphs and headings are TextRenderables written natively, not CodeRenderables with filetype: "markdown", and prose no longer goes to the Tree-sitter client. Code that set onChunks or onHighlight on them should use inlineHook.
  • Parsing follows CommonMark 0.31.2 and GFM: [x] without a definition keeps its brackets, a backslash escape hides its backslash, a code span loses one space at each end, a link reference definition applies anywhere in the document, a header with its delimiter row is a table before any row arrives, task items show ☐ or ☑ ([ ] or [x] without conceal), and a list with a blank line between items shows a blank row between them.
  • While streaming, a line that may still change kind waits for its end (see Streaming updates).
  • The inline hook runs when its content or options change (content, inlineHook, inlineHookFilter, rerunInlineHook, a new syntaxStyle), not when a highlight arrives, so a renamed title shows at once and a failed highlight no longer keeps an old one. Its output is written in the current style: a hook that reads context.syntaxStyle is run again on a theme change.
  • targetAt answers from the next frame after a rename or other text change; until then it answers nothing.
  • A markup.strikethrough style strikes its text through unless the style sets strikethrough: false.

OpenTUI bundles a limited parser set. See the Tree-sitter reference before you highlight other fenced-code languages.

Use Code for source-only content. Add a Line number gutter to a compatible code or editor renderable. Use Diff for patches. Use TextTable for table data that does not start as Markdown.

Changes0.9.9, 0.9.6, 0.9.5
0.9.9
core: MarkdownRenderable no longer throws undefined is not an object (evaluating 'c.ordinal=o++') while a list streams in. Lists now lay out after all blocks of an update are shown. OpenTUI 0.9.4 to 0.9.8 had this error. (#2199)
0.9.6
native: With math on, Core and Rust Markdown now draw a $ before a held pipe, as in $|$[, as plain text while the line waits to become a table header. Before, that $ used the math style. See Markdown and Code, Markdown, and highlighting. (#2178)
0.9.5
core: MarkdownOptions.taskMarkers and MarkdownRenderable.taskMarkers set the text of the unchecked and checked task boxes when conceal is on. The defaults are ☐ and ☑. (#2173)
Added MarkdownTaskMarkers, MarkdownOptions.taskMarkers, MarkdownRenderable.taskMarkers.
Changed MarkdownRenderable._contentDefaultOptions.