html

package
v0.0.0-...-13f9312 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: BSD-2-Clause Imports: 12 Imported by: 514

Documentation

Overview

Package html implements an HTML renderer of a parsed markdown document.

Configuring and customizing a renderer

A renderer can be configured with multiple options:

import "github.com/gomarkdown/markdown/html"

flags := html.CommonFlags | html.CompletePage | html.HrefTargetBlank
opts := html.RendererOptions{
	Title: "A custom title",
	Flags: flags,
}
renderer := html.NewRenderer(opts)

You can also re-use most of the logic and customize rendering of selected nodes by providing a node render hook. This is most useful for rendering nodes that allow for design choices, like links or code blocks.

import (
	"github.com/gomarkdown/markdown/html"
	"github.com/gomarkdown/markdown/ast"
)

// a simple render hook that will output "code_replacement" instead of
// <code>${content}</code> emitted by html.Renderer
func renderHookCodeBlock(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
	_, ok := node.(*ast.CodeBlock)
	if !ok {
		return ast.GoToNext, false
	}
	io.WriteString(w, "code_replacement")
	return ast.GoToNext, true
}

opts := html.RendererOptions{
	RenderNodeHook: renderHookCodeBlock,
}
renderer := html.NewRenderer(opts)

Untrusted input

For documents you don't trust, set SkipHTML and Safelink:

flags := html.CommonFlags | html.SkipHTML | html.Safelink

SkipHTML removes raw HTML and Safelink only allows http, https, ftp and mailto URLs and relative paths in links and images. With either of them, attributes that a document sets with the parser.Attributes or parser.InlineAttributes extension are limited to id, class, title, lang, dir, role, width, height, align, data-* and aria-*, which can't run script or load anything. A document never replaces an attribute the renderer writes, like the href of a link.

These flags don't make the output safe to show as it is. Use an HTML sanitizer such as github.com/microcosm-cc/bluemonday as well. Render hooks that write attributes with BlockAttrs get all of them, unfiltered.

Index

Constants

This section is empty.

Variables

View Source
var Escaper = [256][]byte{
	'&': []byte("&amp;"),
	'<': []byte("&lt;"),
	'>': []byte("&gt;"),
	'"': []byte("&quot;"),
}

Escaper maps HTML special characters to their escaped forms.

View Source
var IDTag = "id"

IDTag is the name of the HTML attribute that holds a block attribute's ID. It defaults to "id".

Functions

func AddAbsPrefix

func AddAbsPrefix(link []byte, prefix string) []byte

func AddAbsPrefixToImage

func AddAbsPrefixToImage(link []byte, prefix string) []byte

func BlockAttrs

func BlockAttrs(node ast.Node) []string

BlockAttrs returns the serialized block attributes attached to node.

The renderer itself doesn't write all of them: see Renderer.blockAttrs.

func EscLink(w io.Writer, text []byte)

EscLink writes text with its character references decoded, then HTML-escaped.

func Escape

func Escape(w io.Writer, text []byte)

Escape writes text while removing Markdown escape backslashes. It doesn't escape HTML: use EscapeHTML for that.

func EscapeHTML

func EscapeHTML(w io.Writer, d []byte)

EscapeHTML writes d with HTML special characters escaped.

func FootnoteItem

func FootnoteItem(prefix string, slug []byte) string

func FootnoteRef

func FootnoteRef(prefix string, node *ast.Link) string
func FootnoteReturnLink(prefix, returnLink string, slug []byte) string

func HeadingCloseTagFromLevel

func HeadingCloseTagFromLevel(level int) string

func HeadingOpenTagFromLevel

func HeadingOpenTagFromLevel(level int) string

func IsList

func IsList(node ast.Node) bool

func IsListItem

func IsListItem(node ast.Node) bool

func IsListItemTerm

func IsListItemTerm(node ast.Node) bool

func IsListTight

func IsListTight(node ast.Node) bool

func ListItemOpenCR

func ListItemOpenCR(listItem *ast.ListItem) bool

func SkipParagraphTags

func SkipParagraphTags(para *ast.Paragraph) bool

func Slugify

func Slugify(in []byte) []byte

Slugify creates a URL-safe fragment slug.

func TagWithAttributes

func TagWithAttributes(name string, attrs []string) string

TagWithAttributes creates an HTML tag with the given name and attributes.

Types

type Flags

type Flags int

Flags control optional behavior of the HTML renderer.

const (
	FlagsNone               Flags = 0
	SkipHTML                Flags = 1 << iota // Skip raw HTML, and keep only document attributes that can't run script or load anything.
	SkipImages                                // Skip embedded images.
	SkipLinks                                 // Render link text without links.
	Safelink                                  // Allow only trusted URL schemes in links and images, and keep only safe document attributes. Doesn't check hosts or sanitize HTML.
	NofollowLinks                             // Add rel="nofollow" to external links.
	NoreferrerLinks                           // Add rel="noreferrer" to external links.
	NoopenerLinks                             // Add rel="noopener" to external links.
	HrefTargetBlank                           // Open external links in a new tab.
	CompletePage                              // Emit a complete HTML document.
	UseXHTML                                  // Emit XHTML-compatible singleton tags.
	FootnoteReturnLinks                       // Link footnotes back to their references.
	FootnoteNoHRTag                           // Omit the rule before footnotes.
	Smartypants                               // Enable smart punctuation.
	SmartypantsFractions                      // Enable smart fractions.
	SmartypantsDashes                         // Enable smart dashes.
	SmartypantsLatexDashes                    // Enable LaTeX-style dashes.
	SmartypantsAngledQuotes                   // Use angled double quotes.
	SmartypantsQuotesNBSP                     // Use French guillemets with nonbreaking spaces.
	TOC                                       // Generate a table of contents.
	LazyLoadImages                            // Add loading="lazy" to images.

	CommonFlags Flags = Smartypants | SmartypantsFractions | SmartypantsDashes | SmartypantsLatexDashes
)

type RenderNodeFunc

type RenderNodeFunc func(io.Writer, ast.Node, bool) (ast.WalkStatus, bool)

RenderNodeFunc can replace the default rendering of selected nodes.

type Renderer

type Renderer struct {
	Opts RendererOptions

	DisableTags       int               // Strip tags from Out and Outs when positive.
	IsSafeURLOverride func([]byte) bool // Optional safe-URL predicate. Gets the URL as written to the output.
	// contains filtered or unexported fields
}

Renderer renders an AST as HTML. Construct one with NewRenderer.

func NewRenderer

func NewRenderer(opts RendererOptions) *Renderer

NewRenderer creates an HTML renderer.

func (*Renderer) CR

func (r *Renderer) CR(w io.Writer)

CR writes a new line

func (*Renderer) Callout

func (r *Renderer) Callout(w io.Writer, node *ast.Callout)

Callout writes ast.Callout node

func (*Renderer) Caption

func (r *Renderer) Caption(w io.Writer, caption *ast.Caption, entering bool)

Caption writes ast.Caption node

func (*Renderer) CaptionFigure

func (r *Renderer) CaptionFigure(w io.Writer, figure *ast.CaptionFigure, entering bool)

CaptionFigure writes ast.CaptionFigure node

func (*Renderer) Citation

func (r *Renderer) Citation(w io.Writer, node *ast.Citation)

Citation writes ast.Citation node

func (*Renderer) Code

func (r *Renderer) Code(w io.Writer, node *ast.Code)

Code writes ast.Code node

func (*Renderer) CodeBlock

func (r *Renderer) CodeBlock(w io.Writer, codeBlock *ast.CodeBlock)

CodeBlock writes ast.CodeBlock node

func (*Renderer) DocumentMatter

func (r *Renderer) DocumentMatter(w io.Writer, node *ast.DocumentMatter, entering bool)

DocumentMatter writes ast.DocumentMatter

func (*Renderer) EnsureUniqueHeadingID

func (r *Renderer) EnsureUniqueHeadingID(id string) string

func (*Renderer) EscapeHTMLCallouts

func (r *Renderer) EscapeHTMLCallouts(w io.Writer, d []byte)

EscapeHTMLCallouts writes html-escaped d to w. It escapes &, <, > and " characters, *but* expands callouts <<N>> with the callout HTML, i.e. by calling r.callout() with a newly created ast.Callout node.

func (*Renderer) HTMLBlock

func (r *Renderer) HTMLBlock(w io.Writer, node *ast.HTMLBlock)

HTMLBlock writes ast.HTMLBlock node

func (*Renderer) HTMLSpan

func (r *Renderer) HTMLSpan(w io.Writer, span *ast.HTMLSpan)

HTMLSpan writes ast.HTMLSpan node

func (*Renderer) HardBreak

func (r *Renderer) HardBreak(w io.Writer, node *ast.Hardbreak)

HardBreak writes ast.Hardbreak node

func (*Renderer) Heading

func (r *Renderer) Heading(w io.Writer, hdr *ast.Heading, entering bool)

Heading writes ast.Heading node

func (*Renderer) HeadingEnter

func (r *Renderer) HeadingEnter(w io.Writer, hdr *ast.Heading)

func (*Renderer) HeadingExit

func (r *Renderer) HeadingExit(w io.Writer, hdr *ast.Heading)

func (*Renderer) HorizontalRule

func (r *Renderer) HorizontalRule(w io.Writer, node *ast.HorizontalRule)

HorizontalRule writes ast.HorizontalRule node

func (*Renderer) Image

func (r *Renderer) Image(w io.Writer, node *ast.Image, entering bool)

Image writes ast.Image node

func (*Renderer) Index

func (r *Renderer) Index(w io.Writer, node *ast.Index)

Index writes ast.Index node

func (r *Renderer) Link(w io.Writer, link *ast.Link, entering bool)

Link writes ast.Link node

func (*Renderer) List

func (r *Renderer) List(w io.Writer, list *ast.List, entering bool)

List writes ast.List node

func (*Renderer) ListItem

func (r *Renderer) ListItem(w io.Writer, listItem *ast.ListItem, entering bool)

ListItem writes ast.ListItem node

func (*Renderer) MakeUniqueHeadingID

func (r *Renderer) MakeUniqueHeadingID(hdr *ast.Heading) string

func (*Renderer) NonBlockingSpace

func (r *Renderer) NonBlockingSpace(w io.Writer, node *ast.NonBlockingSpace)

NonBlockingSpace writes ast.NonBlockingSpace node

func (*Renderer) Out

func (r *Renderer) Out(w io.Writer, d []byte)

Out is a helper to write data to writer

func (*Renderer) OutHRTag

func (r *Renderer) OutHRTag(w io.Writer, attrs []string)

func (*Renderer) OutOneOf

func (r *Renderer) OutOneOf(w io.Writer, outFirst bool, first string, second string)

OutOneOf writes first or second depending on outFirst

func (*Renderer) OutOneOfCr

func (r *Renderer) OutOneOfCr(w io.Writer, outFirst bool, first string, second string)

OutOneOfCr writes CR + first or second + CR depending on outFirst

func (*Renderer) OutTag

func (r *Renderer) OutTag(w io.Writer, name string, attrs []string)

func (*Renderer) Outs

func (r *Renderer) Outs(w io.Writer, s string)

Outs is a helper to write data to writer

func (*Renderer) Paragraph

func (r *Renderer) Paragraph(w io.Writer, para *ast.Paragraph, entering bool)

Paragraph writes ast.Paragraph node

func (*Renderer) RenderFooter

func (r *Renderer) RenderFooter(w io.Writer, _ ast.Node)

RenderFooter writes HTML document footer.

func (*Renderer) RenderHeader

func (r *Renderer) RenderHeader(w io.Writer, doc ast.Node)

RenderHeader writes HTML document preamble and TOC if requested.

func (*Renderer) RenderNode

func (r *Renderer) RenderNode(w io.Writer, node ast.Node, entering bool) ast.WalkStatus

RenderNode renders a markdown node to HTML

func (*Renderer) TableBody

func (r *Renderer) TableBody(w io.Writer, node *ast.TableBody, entering bool)

TableBody writes ast.TableBody node

func (*Renderer) TableCell

func (r *Renderer) TableCell(w io.Writer, tableCell *ast.TableCell, entering bool)

TableCell writes ast.TableCell node

func (*Renderer) Text

func (r *Renderer) Text(w io.Writer, text *ast.Text)

Text writes ast.Text node

type RendererOptions

type RendererOptions struct {
	AbsolutePrefix             string         // Prefix for relative URLs.
	FootnoteAnchorPrefix       string         // Prefix for footnote anchors.
	FootnoteReturnLinkContents string         // HTML inside footnote return links.
	CitationFormatString       string         // fmt string for citation targets.
	HeadingIDPrefix            string         // Prefix for generated heading IDs.
	HeadingIDSuffix            string         // Suffix for generated heading IDs.
	ParagraphTag               string         // Paragraph tag override.
	Title                      string         // Complete-page document title.
	CSS                        string         // Complete-page stylesheet URL.
	Icon                       string         // Complete-page icon URL.
	Head                       []byte         // Extra complete-page head markup.
	Flags                      Flags          // Optional renderer behavior.
	RenderNodeHook             RenderNodeFunc // Optional node rendering override.
	Comments                   [][]byte       // Code comment markers for callouts.
	Generator                  string         // Complete-page generator meta tag.
}

RendererOptions configures HTML rendering.

type SPRenderer

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

SPRenderer is a struct containing state of a Smartypants renderer.

func NewSmartypantsRenderer

func NewSmartypantsRenderer(flags Flags) *SPRenderer

NewSmartypantsRenderer constructs a Smartypants renderer object.

func (*SPRenderer) Process

func (r *SPRenderer) Process(w io.Writer, text []byte)

Process is the entry point of the Smartypants renderer.

Jump to

Keyboard shortcuts

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