kramdown

package module
v0.0.0-...-6152f7f 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: 5 Imported by: 0

README

go-ruby-kramdown/kramdown

go-ruby-kramdown/kramdown

Pure-Go (CGO=0), MRI-faithful reimplementation of the Ruby kramdown Markdown-to-HTML converter.

CI Coverage Go Reference

About

go-ruby-kramdown renders the kramdown dialect of Markdown to HTML, matching the output of the Ruby kramdown gem on the common feature set. It is a member of the go-ruby-* family of pure-Go Ruby modules that go-embedded-ruby (rbgo) binds as native modules — there is no cgo and no external process: the converter is a self-contained Go package that cross-compiles to every Go target.

Install

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

Usage

package main

import (
	"fmt"

	"github.com/go-ruby-kramdown/kramdown"
)

func main() {
	html := kramdown.ToHTML("# Hello *kramdown*\n\nA paragraph with a footnote.[^1]\n\n[^1]: the note.\n", nil)
	fmt.Print(html)
}

For finer control, parse into a *Document and inspect warnings:

doc := kramdown.New(src, &kramdown.Options{AutoIds: true, SmartQuotes: true})
html := doc.ToHTML()
for _, w := range doc.Warnings {
	// e.g. an undefined footnote reference
	fmt.Println("warning:", w)
}

ToHTML(src, nil) uses DefaultOptions(), which mirrors kramdown's own defaults (AutoIds, SmartQuotes, Typographic, HardWrap all on; footnotes numbered from 1).

Options

Field Default Meaning
AutoIds true Assign a generated id="" to headers lacking an explicit {#id}.
AutoIdPrefix "" Prefix prepended to every auto-generated header id.
SmartQuotes true Curly quotes / apostrophes via the SmartQuotes substitution.
Typographic true --→en-dash, ---→em-dash, ...→ellipsis, << >>→guillemets.
HardWrap true Trailing two-spaces → <br />; when off, only \\ forces a break.
FootnoteNr 1 Starting number for footnotes.

Supported syntax

Area Coverage
Headers ATX (#) + Setext (===/---), explicit {#id} and auto-ids
Blocks Paragraphs, blockquotes, horizontal rules, indented + fenced code (language class)
Lists Unordered, ordered, definition lists; lazy and nested
Tables Pipe tables with per-column alignment
Inline *em*/**strong**, `code`, links & images (inline / reference / with attrs), autolinks
Footnotes [^id] references + definitions, with back-links and ordering
Attributes Inline Attribute Lists {:.class #id key="v"}, ALDs, {::comment} / span IALs
Abbreviations *[HTML]: ... definitions applied to matching text
Typography Smart quotes, --/---/.../<< >> substitutions
HTML Raw inline + block HTML passthrough; entity and backslash escapes

Edge cases deliberately outside the common feature set are documented in the tests.

Conformance & testing

A differential oracle compares output to the real kramdown gem where it is installed; the deterministic, ruby-free tests alone hold 100% statement coverage, so the no-ruby, Windows, and qemu CI lanes stay green. The package is verified on Linux/macOS/Windows and cross-tested on amd64, arm64, riscv64, loong64, ppc64le, and s390x.

License

BSD-3-Clause — see LICENSE. Copyright (c) the go-ruby-kramdown/kramdown 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 kramdown is a pure-Go (CGO-free) reimplementation of Ruby's kramdown Markdown-to-HTML converter — the parser and HTML renderer that back Kramdown::Document.new(src, options).to_html. It parses the kramdown dialect (a superset of Markdown: ATX/Setext headers with inline-attribute lists, blockquotes, fenced and indented code, ordered/unordered/definition lists, tables with alignment, footnotes, abbreviations, smart-quote typography, block and span IALs/ALDs, the {::comment} extension, …) into an element tree and renders the gem's HTML byte-for-byte on the common feature set — with no Ruby runtime.

The value model is deliberately small: a source string in, an HTML string out, plus an options hash. The intermediate element tree (Element) mirrors kramdown's own AST (a type, a value, attributes and children) so a host (such as go-embedded-ruby) can bind Kramdown::Document / Kramdown::Element directly onto it.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToHTML

func ToHTML(src string, opts *Options) string

ToHTML is the one-shot convenience entry point: it parses src under opts and returns the HTML, equivalent to Kramdown::Document.new(src, options).to_html.

Types

type Attr

type Attr struct {
	Name string
	Val  string
}

Attr is one HTML attribute (name/value), kept ordered as kramdown emits them.

type Document

type Document struct {
	Root     *Element
	Opts     Options
	Warnings []string
	// contains filtered or unexported fields
}

Document is a parsed kramdown source, the analogue of Kramdown::Document. It holds the element [Root], the resolved [Opts], and the [Warnings] accumulated while parsing (e.g. an undefined footnote reference), and renders HTML via ToHTML.

func New

func New(src string, opts *Options) *Document

New parses src under opts (nil selects DefaultOptions) and returns the parsed Document, mirroring Kramdown::Document.new(src, options). Parsing never fails; malformed constructs degrade to literal text exactly as kramdown does.

func (*Document) ToHTML

func (d *Document) ToHTML() string

ToHTML renders the document to HTML, matching Kramdown::Document#to_html. Span parsing happens here, so any warnings it raises (e.g. an undefined footnote reference) are folded into Document.Warnings before returning.

type Element

type Element struct {
	Type     ElementType
	Value    string
	Children []*Element
	Attrs    []Attr
	Options  map[string]any
}

Element is a node in the kramdown element tree. Type selects the node kind, Value carries literal text for leaf nodes, Children holds nested elements, Attrs holds rendered HTML attributes in emission order, and Options carries parser-internal metadata (header level, list tightness, table alignments, …).

type ElementType

type ElementType int

ElementType enumerates the kinds of node in the kramdown element tree. The set mirrors the subset of Kramdown::Element types this converter produces.

const (
	// ElRoot is the document root; its Children are the top-level blocks.
	ElRoot ElementType = iota
	// ElBlank is a run of one or more blank lines between blocks.
	ElBlank
	// ElP is a paragraph; its Children are span elements.
	ElP
	// ElHeader is an ATX or Setext header; Value is unused, Options["level"] is the
	// level (1..6) and Options["raw_text"] the source used for auto-ids.
	ElHeader
	// ElBlockquote is a blockquote; Children are nested blocks.
	ElBlockquote
	// ElCodeblock is a fenced or indented code block; Value holds the literal text.
	ElCodeblock
	// ElHR is a horizontal rule.
	ElHR
	// ElUL / ElOL are unordered / ordered lists; Children are ElLI.
	ElUL
	// ElOL is an ordered list.
	ElOL
	// ElLI is a list item; Children are nested blocks (or a single bare paragraph
	// whose <p> wrapper is elided when the item is "tight").
	ElLI
	// ElDL is a definition list; Children are ElDT / ElDD.
	ElDL
	// ElDT is a definition term.
	ElDT
	// ElDD is a definition description.
	ElDD
	// ElTable is a table; Children are ElThead / ElTbody.
	ElTable
	// ElThead / ElTbody / ElTr / ElTd structure a table.
	ElThead
	// ElTbody is a table body.
	ElTbody
	// ElTr is a table row.
	ElTr
	// ElTd is a table cell (a <td> or, in a thead, a <th>).
	ElTd
	// ElHTMLBlock is a passthrough block of raw HTML; Value holds it verbatim.
	ElHTMLBlock
	// ElComment is a {::comment} extension block; Value holds the comment text.
	ElComment
	// ElFootnoteDef collects a footnote definition's blocks (never rendered inline).
	ElFootnoteDef

	// ElText is literal text; Value holds it.
	ElText
	// ElEm / ElStrong are emphasis / strong emphasis.
	ElEm
	// ElStrong is strong emphasis.
	ElStrong
	// ElCodespan is an inline code span; Value holds the literal text.
	ElCodespan
	// ElA is a hyperlink; Options["href"]/["title"] carry the destination.
	ElA
	// ElImg is an image; Options["src"]/["alt"]/["title"] carry the attributes.
	ElImg
	// ElBr is a hard line break.
	ElBr
	// ElTypographicSym carries a smart-typography substitution; Value is the entity
	// name (e.g. "ldquo", "mdash").
	ElTypographicSym
	// ElFootnoteRef is a footnote reference; Options["name"] is the id.
	ElFootnoteRef
	// ElAbbr is an expanded abbreviation; Value is the matched text and
	// Options["title"]/["class"] carry the definition.
	ElAbbr
	// ElRawHTMLSpan is raw inline HTML passed through verbatim in Value.
	ElRawHTMLSpan
)

type Options

type Options struct {
	// AutoIds, when true (kramdown's default), assigns a generated id="" to every
	// header that lacks an explicit {#id}.
	AutoIds bool
	// AutoIdPrefix is prepended to every auto-generated header id (default "").
	AutoIdPrefix string
	// SmartQuotes enables typographic substitution of quotes/dashes/ellipses
	// (kramdown's default).
	SmartQuotes bool
	// Typographic enables the --, ---, ... and <<>> substitutions (default true).
	Typographic bool
	// HardWrap, when true (kramdown's default), turns a trailing-two-spaces line
	// into a hard <br />. When false, only explicit "\\" forces a break.
	HardWrap bool
	// FootnoteNr is the starting number for footnotes (default 1).
	FootnoteNr int
}

Options configures a conversion, mirroring the keyword options accepted by Kramdown::Document.new. Only the options that influence the HTML output of the supported feature set are honoured; the rest are tolerated for API parity.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns the option set matching kramdown's own defaults, used when New is called with a nil option pointer.

Jump to

Keyboard shortcuts

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