flashman
← All guides

Portable Markdown code fences and nested examples

Write nested Markdown examples that survive CommonMark, GFM, documentation generators, syntax highlighting, sanitization, and PDF export.

2026-08-28 · 8 min read

  • markdown
  • documentation
  • portability

Fenced code blocks let documentation preserve indentation and punctuation, but examples become tricky when the code being shown is itself Markdown. A delimiter inside the sample can close the outer block and turn the remainder into live document syntax.

Portable documentation also crosses renderers. CommonMark, GitHub Flavored Markdown, static-site plugins, and PDF pipelines can differ around tables, raw HTML, highlighting metadata, and blocks nested inside lists.

Choose unambiguous fences

A backtick fence can use three or more backticks. To display an inner backtick fence, make the outer run longer than every backtick run inside it. Tilde fences provide another option when the target renderer supports them.

  • Place opening and closing fences on their own lines.
  • Use the same delimiter character and sufficient closing length.
  • Keep the info string simple and compatible with the highlighter.
  • Prefer a larger outer fence over escaping every inner character.

Handle lists and block structure

A code fence nested beneath a list item needs indentation that keeps it attached to that item without turning it into an indented code block under the target dialect. Blank lines can also decide whether following text remains inside a list.

Reduce a broken document to the nearest heading, list marker, quote, and fence. Parsing depends on surrounding block context, so an isolated fence may render correctly while the complete page fails.

Separate source safety from rendered safety

Code fences should render their content literally, but renderer extensions and malformed closures can expose HTML-looking text to the document parser. Configure raw HTML handling intentionally and sanitize untrusted Markdown output before placing it in a page.

  • Test angle brackets and entity-looking strings inside examples.
  • Do not assume syntax highlighting sanitizes HTML.
  • Review generated links and images from untrusted Markdown.
  • Keep renderer and sanitizer upgrades covered by fixtures.

Verify each publication target

Preview the repository host, documentation site, and exported PDF separately. PDF layout can overflow long lines or split blocks even when Markdown parsing is correct. Use wrapping, horizontal scrolling on the web, or shorter examples without changing the code's meaning.

Use Flashman's Markdown editor to draft, Markdown viewer to inspect rendering, Markdown PDF tool to test export, diff tool to review delimiter changes, and HTML entities tool to inspect literal markup examples. Keep a compact compatibility document with nested fences, lists, tables, links, and raw-HTML-looking text.

Try these tools