commonmark

package module
v0.0.0-...-c973388 Latest Latest
Warning

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

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

README

go-ruby-commonmark/commonmark

commonmark — go-ruby-commonmark

Docs License Go Coverage

A pure-Go (no cgo) CommonMark renderer — the deterministic, interpreter-independent core that backs Ruby's commonmarker gem. It parses CommonMark v0.31.2 source into a node tree and renders it to an HTML fragment, and it can additionally enable a subset of the GitHub Flavored Markdown extensions behind Optionswithout any Ruby runtime, and without a cgo binding to libcmark.

It is the Markdown backend for go-embedded-ruby, but is a standalone, reusable module with no dependency on the Ruby runtime — a sibling of go-ruby-kramdown and go-ruby-liquid.

Conformance is honest, not aspirational. The parser is validated against the upstream spec.txt conformance suite: 593 / 652 examples pass today. The remaining failures are concentrated in a handful of hard emphasis-nesting edge cases, lazy list-item continuation, and the spec's raw-HTML-block corner cases (many of which the reference renderer only produces in "unsafe" mode). Every spec example is embedded and run on every CI lane; the exact pass rate is asserted in the test suite, so it can only go up.

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).

Install

go get github.com/go-ruby-commonmark/commonmark

Usage

package main

import (
	"fmt"

	"github.com/go-ruby-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 (reporting the honest pass rate), 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%

License

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

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, …)

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