commonmark

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2026 License: BSD-3-Clause Imports: 6 Imported by: 0

README

go-commonmark/commonmark

commonmark — go-commonmark

Docs License Go Coverage CommonMark spec v0.31.2

A pure-Go (no cgo) CommonMark renderer. It parses CommonMark v0.31.2 source into a node tree and renders it to an HTML fragment, and can additionally enable a subset of the GitHub Flavored Markdown extensions behind Optionswith no cgo binding to libcmark and no third-party dependencies.

Because it is pure Go and dependency-free, it compiles everywhere Go does — including GOOS=js/wasm, so it powers client-side, offline Markdown preview in a browser Web Worker (≈0.1 ms for a README-scale document; ~840 KB gzip worker) with no server round-trip.

This is the standalone engine; the Ruby binding (go-embedded-ruby's commonmark gem) is a thin consumer on top. It is a sibling of the pure-Go go-scss and go-regexp cores.

Spec-complete. The parser is validated against the upstream spec.txt conformance suite and passes all 652 / 652 CommonMark spec v0.31.2 examples, byte-exact (100%, 0 known gaps). Every spec example is embedded and run on every CI lane, and the pass rate is asserted by a ratchet test that fails if any example regresses — so full conformance can only be held, never quietly lost.

Features

  • Full block grammar — ATX and Setext headings, block quotes, bullet and ordered lists (tight/loose), indented and fenced code blocks, thematic breaks, HTML blocks, and link reference definitions.
  • Full inline grammar — emphasis / strong with the CommonMark flanking and delimiter-stack algorithm, code spans, links and images (inline, reference, collapsed, and shortcut), autolinks, raw inline HTML, backslash escapes, hard and soft line breaks, and the complete HTML5 named + numeric entity table.
  • Safe by default — raw HTML and dangerous URL schemes (javascript:, vbscript:, file:, and non-image data:) are filtered unless Unsafe is set. URL destinations are normalised and percent-encoded like the reference renderer.
  • GFM extensions behind Options — pipe tables (with per-column alignment), strikethrough (~~…~~), extended autolinks (bare http(s):// and www. links with GFM trailing-punctuation trimming), and task list checkboxes (- [ ] / - [x]). All are off by default, so the zero value is strict CommonMark.

CGO-free, dependency-free, 100% test coverage, gofmt + go vet clean, and green across the six 64-bit Go targets (amd64, arm64, riscv64, loong64, ppc64le, s390x) plus js/wasm and wasip1/wasm.

Install

go get github.com/go-commonmark/commonmark

Usage

package main

import (
	"fmt"

	"github.com/go-commonmark/commonmark"
)

func main() {
	// Strict CommonMark (the safe default).
	fmt.Print(commonmark.ToHTML("# Hello\n\nsome *emphasis*.\n", nil))
	// <h1>Hello</h1>
	// <p>some <em>emphasis</em>.</p>

	// Enable GFM tables, strikethrough, autolinks and task lists.
	opts := &commonmark.Options{
		Tables:        true,
		Strikethrough: true,
		Autolink:      true,
		TaskList:      true,
	}
	fmt.Print(commonmark.ToHTML("- [x] ~~done~~ see https://example.com\n", opts))
	// <ul>
	// <li><input type="checkbox" checked="" disabled="" /> <del>done</del> see <a href="https://example.com">https://example.com</a></li>
	// </ul>
}

API

// ToHTML converts CommonMark source to an HTML fragment. A nil opts selects the
// strict CommonMark default.
func ToHTML(src string, opts *Options) string

// Parse parses CommonMark source into a Document node tree for callers that need
// structured access. A nil opts selects the strict CommonMark default.
func Parse(src string, opts *Options) *Node

type Options struct {
	Tables        bool // GFM pipe tables
	Strikethrough bool // GFM ~~text~~
	Autolink      bool // GFM extended bare-URL / www. autolinks
	TaskList      bool // GFM - [ ] / - [x] checkboxes
	GitHubPreLang bool // emit fenced-code language on <pre> (GitHub style)
	Unsafe        bool // pass raw HTML and unsafe URL schemes through
	HardBreaks    bool // render every soft line break as <br />
}

Tests & coverage

The suite embeds the upstream CommonMark spec.txt and runs all 652 examples on every lane — all 652/652 pass, byte-exact (a ratchet test fails on any regression) — alongside targeted block/inline/GFM and error-path tests that hold statement coverage at 100%, so the qemu cross-arch and Windows lanes pass the coverage gate. The host lane keeps cgo enabled so -race runs; the six architecture lanes build and test with CGO_ENABLED=0 to prove the pure-Go build.

COVERPKG=$(go list ./... | paste -sd, -)
go test -race -coverpkg="$COVERPKG" -coverprofile=cover.out ./...
go tool cover -func=cover.out | tail -1   # 100.0%

WebAssembly

Being pure Go (CGO=0), this library also compiles to WebAssembly — both GOOS=js GOARCH=wasm (browser / Node.js) and GOOS=wasip1 GOARCH=wasm (WASI). CI builds both targets on every push, alongside the six 64-bit native/qemu arches.

GOOS=js     GOARCH=wasm go build ./...   # browser / Node
GOOS=wasip1 GOARCH=wasm go build ./...   # WASI (wasmtime, wasmer, wasmedge, …)

License

BSD-3-Clause — see LICENSE. Copyright the go-commonmark/commonmark authors.

Documentation

Overview

Package commonmark is a pure-Go (CGO=0) strict CommonMark renderer. It implements the CommonMark specification v0.31.2 — the same core that backs the Ruby `commonmarker` gem — and can additionally enable a subset of the GFM extensions (tables, strikethrough, autolinks, task lists) behind Options.

The primary entry point is ToHTML, which converts a Markdown source string to an HTML fragment. Parse exposes the intermediate Document node tree for callers that need structured access.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToHTML

func ToHTML(src string, opts *Options) string

ToHTML converts CommonMark source to an HTML fragment. A nil opts selects the strict CommonMark default.

Types

type Node

type Node struct {
	Type NodeType

	// Tree links.
	Parent                *Node
	FirstChild, LastChild *Node
	Prev, Next            *Node

	// Literal payload for leaf nodes: Text/Code/HTMLBlock/HTMLInline/CodeBlock.
	Literal []byte

	// Heading level (1..6) or, during Setext resolution, the marker level.
	Level int

	Info []byte // fenced code info string (raw)

	// Link / Image destination + title.
	Destination []byte
	Title       []byte
	// contains filtered or unexported fields
}

Node is a single node in the CommonMark parse tree. It is exported so callers that need structured access (via Parse) can walk it; ToHTML uses it internally.

func Parse

func Parse(src string, opts *Options) *Node

Parse parses CommonMark source into a Document node tree. A nil opts selects the strict CommonMark default. The returned node has Type == Document.

type NodeType

type NodeType int

NodeType enumerates the kinds of nodes in the parse tree. Block-level and inline-level nodes share one tree, following the CommonMark reference model.

const (
	// Document is the root of every parse tree.
	Document NodeType = iota
	// BlockQuote is a `>`-prefixed block quote.
	BlockQuote
	// List is a bullet or ordered list container.
	List
	// Item is a single list item.
	Item
	// CodeBlock is an indented or fenced code block.
	CodeBlock
	// HTMLBlock is a raw block-level HTML region.
	HTMLBlock
	// Paragraph is a paragraph of inline content.
	Paragraph
	// Heading is an ATX or Setext heading.
	Heading
	// ThematicBreak is a horizontal rule (`---`, `***`, `___`).
	ThematicBreak
	// Text is a run of literal text.
	Text
	// Softbreak is an end-of-line that renders as a newline (or space).
	Softbreak
	// Linebreak is a hard line break (`  \n` or `\\\n`).
	Linebreak
	// Code is an inline code span.
	Code
	// HTMLInline is raw inline HTML.
	HTMLInline
	// Emphasis is `*`/`_` emphasis (rendered <em>).
	Emphasis
	// Strong is `**`/`__` strong emphasis (rendered <strong>).
	Strong
	// Link is a hyperlink.
	Link
	// Image is an image reference.
	Image
	// Strikethrough is GFM `~~` strikethrough (extension).
	Strikethrough
	// Table is a GFM table (extension).
	Table
	// TableRow is a row within a GFM table.
	TableRow
	// TableCell is a cell within a GFM table row.
	TableCell
)

type Options

type Options struct {
	// Tables enables GFM pipe tables.
	Tables bool
	// Strikethrough enables GFM `~~text~~` strikethrough.
	Strikethrough bool
	// Autolink enables GFM extended autolinks (bare URLs and www links).
	Autolink bool
	// TaskList enables GFM `- [ ]` / `- [x]` task list items.
	TaskList bool

	// GitHubPreLang, when true, emits fenced code language as a class on the
	// <pre> element the way commonmarker's GitHub renderer does. When false
	// (the CommonMark default) the class is emitted on the <code> element.
	GitHubPreLang bool

	// Unsafe, when true, passes raw HTML and unsafe URL schemes through instead
	// of filtering them. The CommonMark reference renderer used by the spec test
	// suite is unsafe, so the conformance tests set this.
	Unsafe bool

	// HardBreaks, when true, renders every soft line break as a <br />.
	HardBreaks bool
}

Options configures the renderer. The zero value (or a nil *Options) selects strict CommonMark with all extensions disabled, which is the safe default.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL