md2html

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

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

Go to latest
Published: Apr 8, 2026 License: MIT Imports: 38 Imported by: 0

README

md2html

Command md2html renders Markdown as HTML.

It can:

  • render a single Markdown file to stdout
  • serve a Markdown tree over HTTP with live reload
  • generate a static HTML tree

Basic usage:

md2html README.md

Serve the current tree:

md2html -http :8080

Generate static output:

md2html -html _site .

The command is a thin wrapper around package github.com/tmc/md2html.

Documentation

Overview

Package md2html renders Markdown as HTML and serves or writes the result.

The package provides three main entry points:

RenderFragment renders a single Markdown string.
NewLoader parses Markdown into headings, links, lists, and frontmatter.
Run drives the server and static-site modes used by the md2html command.

Rendering uses Goldmark with GFM extensions, syntax highlighting, admonitions, optional table-of-contents generation, and relative-link rewriting for Markdown source trees.

For small in-process rendering, use RenderFragment:

frag := md2html.RenderFragment("# Hello\n", "", md2html.FragmentOptions{})
_ = frag.HTML

For command-style integration, build a Config and call Run:

fs := md2html.NewFlagSet("md2html")
_ = fs.Parse([]string{"-http", ":8080", "README.md"})
cfg := md2html.ConfigFromFlags(fs)
err := md2html.Run(context.Background(), cfg, slog.Default(), os.Stdout, fs.Args())

For navigation and structured parsing, use ParseSummary and Loader.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FragmentStyles

func FragmentStyles() template.CSS

FragmentStyles returns shared CSS for rendered markdown fragments.

func NewFlagSet

func NewFlagSet(name string) *flag.FlagSet

NewFlagSet returns a FlagSet configured for the md2html CLI.

func Run

func Run(ctx context.Context, cfg Config, logger *slog.Logger, out io.Writer, args []string) error

Types

type Config

type Config struct {
	Source            string // file, directory, or "-" for stdin
	HTTP              string
	HTML              string
	Open              bool
	Verbose           bool
	Title             string
	CSS               string
	Depth             int
	TOC               bool
	AllowUnsafe       bool
	TemplateDir       string
	DataJSON          string
	RenderFrontmatter bool
	Index             string
	HTMLExt           string
	Versions          bool
	VersionPattern    string
	VersionBranches   bool
	VersionDefault    string
	Search            bool
}

func ConfigFromFlags

func ConfigFromFlags(fs *flag.FlagSet) Config

ConfigFromFlags creates a Config from an initialized FlagSet.

type DocumentData

type DocumentData struct {
	Content     string
	Frontmatter map[string]interface{}
}

type Fragment

type Fragment struct {
	HTML             template.HTML
	ChromaCSS        template.CSS
	HasMath          bool
	HasMermaid       bool
	MermaidTheme     string
	MermaidDarkTheme string
	MermaidAutoTheme bool
}

Fragment contains rendered markdown plus enhancement metadata for clients.

func RenderFragment

func RenderFragment(markdown, filePath string, opts FragmentOptions) Fragment

RenderFragment renders markdown using the md2html pipeline and returns client enhancement metadata for MathJax and Mermaid.

type FragmentOptions

type FragmentOptions struct {
	AllowUnsafe bool
	TOC         bool
	HTMLExt     string
	Frontmatter map[string]interface{}
}

FragmentOptions configures fragment rendering.

type GitVersion

type GitVersion struct {
	Name   string // Tag or branch name
	Ref    string // Full git reference (e.g., refs/tags/v1.0.0)
	IsTag  bool   // true if this is a tag, false if branch
	Commit string // Short commit hash
}

GitVersion represents a git tag or branch that can be used for versioned docs

type GitVersionManager

type GitVersionManager struct {
	// contains filtered or unexported fields
}

GitVersionManager handles git operations for versioned documentation

func NewGitVersionManager

func NewGitVersionManager(repoPath string) *GitVersionManager

NewGitVersionManager creates a new git version manager for the given repository

func (*GitVersionManager) CheckoutVersion

func (gvm *GitVersionManager) CheckoutVersion(version string) error

CheckoutVersion checks out a specific version (for local development)

func (*GitVersionManager) GetCurrentVersion

func (gvm *GitVersionManager) GetCurrentVersion() (string, error)

GetCurrentVersion returns the current version (tag or branch)

func (*GitVersionManager) GetFileContent

func (gvm *GitVersionManager) GetFileContent(version, filePath string) ([]byte, error)

GetFileContent returns the content of a file at a specific version

func (*GitVersionManager) IsGitRepo

func (gvm *GitVersionManager) IsGitRepo() bool

IsGitRepo checks if the given path is inside a git repository

func (*GitVersionManager) ListFiles

func (gvm *GitVersionManager) ListFiles(version, pattern string) ([]string, error)

ListFiles returns all files at a specific version matching a pattern

func (*GitVersionManager) ListVersions

func (gvm *GitVersionManager) ListVersions(includeBranches bool, tagPattern string) ([]GitVersion, error)

ListVersions returns all available versions (tags and optionally branches)

type Heading

type Heading struct {
	Level int    // 1-6
	Text  string // Heading text
	ID    string // Anchor ID
}

Heading represents a heading in the document.

type Link struct {
	Text   string // Link text
	URL    string // Link URL
	Line   int    // Source line number
	Indent int    // Indentation level (for list items)
}

Link represents a link in the document.

type ListItem

type ListItem struct {
	Text     string     // Item text (without link)
	Link     *Link      // Link if item contains one
	Indent   int        // Nesting level (0 = top level)
	Children []ListItem // Nested list items
}

ListItem represents an item in a list, potentially with nested children.

type Loader

type Loader struct {
	// contains filtered or unexported fields
}

Loader loads and parses data files (JSON, YAML, Markdown).

func NewLoader

func NewLoader(baseDir, htmlExt string) *Loader

NewLoader creates a new data loader rooted at baseDir.

func (*Loader) Load

func (l *Loader) Load(path string) (interface{}, error)

Load auto-detects file type by extension and loads accordingly.

func (*Loader) LoadJSON

func (l *Loader) LoadJSON(path string) (interface{}, error)

LoadJSON loads and parses a JSON file.

func (*Loader) LoadMD

func (l *Loader) LoadMD(path string) (*MarkdownDoc, error)

LoadMD loads and parses a markdown file into structured data.

func (*Loader) LoadSummary

func (l *Loader) LoadSummary(path string) (*Navigation, error)

LoadSummary loads and parses SUMMARY.md from a directory.

func (*Loader) LoadYAML

func (l *Loader) LoadYAML(path string) (interface{}, error)

LoadYAML loads and parses a YAML file.

func (*Loader) ParseMD

func (l *Loader) ParseMD(content string) (*MarkdownDoc, error)

ParseMD parses markdown content into a MarkdownDoc.

func (*Loader) TemplateFuncs

func (l *Loader) TemplateFuncs() template.FuncMap

TemplateFuncs returns template functions for data loading.

type MarkdownDoc

type MarkdownDoc struct {
	Frontmatter map[string]interface{} // YAML frontmatter
	Content     string                 // Raw markdown content
	HTML        template.HTML          // Rendered HTML
	Title       string                 // First H1 or frontmatter title
	Headings    []Heading              // All headings
	Links       []Link                 // All links with context
	Lists       []ListItem             // Top-level list items (with nesting)
}

MarkdownDoc represents a parsed markdown file with extracted structure.

type NavContext struct {
	Items      []*NavItem // Full navigation tree
	Current    *NavItem   // Current page (nil if not found)
	Prev       *NavItem   // Previous page (nil if first or not found)
	Next       *NavItem   // Next page (nil if last or not found)
	Breadcrumb []*NavItem // Ancestor chain (root to parent)
	HasNav     bool       // True if navigation was loaded
}

NavContext provides navigation state for a specific page.

type NavItem struct {
	Title    string     `json:"title"`
	Path     string     `json:"path"`               // Source file path (e.g., "getting-started/installation.md")
	URL      string     `json:"url"`                // Rendered URL (with htmlExt applied)
	Level    int        `json:"level"`              // Nesting depth (0 = top level)
	Children []*NavItem `json:"children,omitempty"` // Nested items
	IsGroup  bool       `json:"isGroup"`            // True for ## section headers
	IsSep    bool       `json:"isSep"`              // True for --- separators
}

NavItem represents a single navigation entry from SUMMARY.md.

type Navigation struct {
	Items  []*NavItem          `json:"items"` // Top-level items
	ByPath map[string]*NavItem `json:"-"`     // Quick lookup by path
	Flat   []*NavItem          `json:"-"`     // Flattened for prev/next (excludes groups/seps)
}

Navigation represents the full navigation tree parsed from SUMMARY.md.

func LoadNavigationFromDir

func LoadNavigationFromDir(dir, htmlExt string) *Navigation

LoadNavigationFromDir loads SUMMARY.md from a directory if it exists.

func ParseSummary

func ParseSummary(content, htmlExt string) (*Navigation, error)

ParseSummary parses SUMMARY.md content into a Navigation structure.

func (n *Navigation) ForPage(currentPath string) *NavContext

ForPage returns navigation context for a specific page path.

type RenderOptions

type RenderOptions struct {
	Nav       *NavContext
	SiteTitle string
	Data      interface{} // from -data-json
}

RenderOptions contains optional parameters for rendering.

type SearchDocument

type SearchDocument struct {
	Title    string `json:"title"`
	Text     string `json:"text"`
	Category string `json:"category"`
	URL      string `json:"url"`
	Blurb    string `json:"blurb"`
	Type     string `json:"type"`
}

SearchDocument represents a document in the search index

Directories

Path Synopsis
cmd
md2html command
Command md2html renders Markdown as HTML.
Command md2html renders Markdown as HTML.
internal
scripttestutil
Package scripttestutil helps with script-based testing.
Package scripttestutil helps with script-based testing.

Jump to

Keyboard shortcuts

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