html

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2023 License: BSD-2-Clause Imports: 10 Imported by: 0

Documentation

Overview

Package html implements HTML renderer of parsed markdown document.

Configuring and customizing a renderer

A renderer can be configured with multiple options:

import "github.com/panhongrainbow/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 node render hook. This is most useful for rendering nodes that allow for design choices, like links or code blocks.

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

// a very dummy render hook that will output "code_replacements" 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)

Index

Constants

This section is empty.

Variables

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

Escaper defines how to escape HTML special characters

View Source
var IDTag = "id"

IDTag is the tag used for tag identification, it defaults to "id", some renderers may wish to override this and use e.g. "anchor".

Functions

func AddAbsPrefix

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

func BlockAttrs

func BlockAttrs(node ast.Node) []string

BlockAttrs takes a node and checks if it has block level attributes set. If so it will return a slice each containing a "key=value(s)" string.

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

func Escape

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

Escape writes the text to w, but skips the escape character.

func EscapeHTML

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

EscapeHTML writes html-escaped d to w. It escapes &, <, > and " characters.

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

TODO: move to internal package Create a url-safe slug for fragments

func TagWithAttributes

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

TagWithAttributes creates a HTML tag with a given name and attributes

Types

type Flags

type Flags int

Flags control optional behavior of HTML renderer.

const (
	FlagsNone               Flags = 0
	SkipHTML                Flags = 1 << iota // Skip preformatted HTML blocks
	SkipImages                                // Skip embedded images
	SkipLinks                                 // Skip all links
	Safelink                                  // Only link to trusted protocols
	NofollowLinks                             // Only link with rel="nofollow"
	NoreferrerLinks                           // Only link with rel="noreferrer"
	NoopenerLinks                             // Only link with rel="noopener"
	HrefTargetBlank                           // Add a blank target
	CompletePage                              // Generate a complete HTML page
	UseXHTML                                  // Generate XHTML output instead of HTML
	FootnoteReturnLinks                       // Generate a link at the end of a footnote to return to the source
	FootnoteNoHRTag                           // Do not output an HR after starting a footnote list.
	Smartypants                               // Enable smart punctuation substitutions
	SmartypantsFractions                      // Enable smart fractions (with Smartypants)
	SmartypantsDashes                         // Enable smart dashes (with Smartypants)
	SmartypantsLatexDashes                    // Enable LaTeX-style dashes (with Smartypants)
	SmartypantsAngledQuotes                   // Enable angled double quotes (with Smartypants) for double quotes rendering
	SmartypantsQuotesNBSP                     // Enable « French guillemets » (with Smartypants)
	TOC                                       // Generate a table of contents
	LazyLoadImages                            // Include loading="lazy" with images

	CommonFlags Flags = Smartypants | SmartypantsFractions | SmartypantsDashes | SmartypantsLatexDashes
)

HTML renderer configuration options.

type RenderNodeFunc

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

RenderNodeFunc allows reusing most of Renderer logic and replacing rendering of some nodes. If it returns false, Renderer.RenderNode will execute its logic. If it returns true, Renderer.RenderNode will skip rendering this node and will return WalkStatus

type Renderer

type Renderer struct {
	Opts RendererOptions

	// if > 0, will strip html tags in Out and Outs
	DisableTags int

	// IsSafeURLOverride allows overriding the default URL matcher. URL is
	// safe if the overriding function returns true. Can be used to extend
	// the default list of safe URLs.
	IsSafeURLOverride func(url []byte) bool
	// contains filtered or unexported fields
}

Renderer implements Renderer interface for HTML output.

Do not create this directly, instead use the NewRenderer function.

func NewRenderer

func NewRenderer(opts RendererOptions) *Renderer

NewRenderer creates and configures an Renderer object, which satisfies the Renderer interface.

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 write 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, node *ast.Heading, entering bool)

Heading writes ast.Heading node

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) 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, ast 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 {
	// Prepend this text to each relative URL.
	AbsolutePrefix string
	// Add this text to each footnote anchor, to ensure uniqueness.
	FootnoteAnchorPrefix string
	// Show this text inside the <a> tag for a footnote return link, if the
	// FootnoteReturnLinks flag is enabled. If blank, the string
	// <sup>[return]</sup> is used.
	FootnoteReturnLinkContents string
	// CitationFormatString defines how a citation is rendered. If blank, the string
	// <sup>[%s]</sup> is used. Where %s will be substituted with the citation target.
	CitationFormatString string
	// If set, add this text to the front of each Heading ID, to ensure uniqueness.
	HeadingIDPrefix string
	// If set, add this text to the back of each Heading ID, to ensure uniqueness.
	HeadingIDSuffix string
	// can over-write <p> for paragraph tag
	ParagraphTag string

	Title string // Document title (used if CompletePage is set)
	CSS   string // Optional CSS file URL (used if CompletePage is set)
	Icon  string // Optional icon file URL (used if CompletePage is set)
	Head  []byte // Optional head data injected in the <head> section (used if CompletePage is set)

	Flags Flags // Flags allow customizing this renderer's behavior

	// if set, called at the start of RenderNode(). Allows replacing
	// rendering of some nodes
	RenderNodeHook RenderNodeFunc

	// Comments is a list of comments the renderer should detect when
	// parsing code blocks and detecting callouts.
	Comments [][]byte

	// Generator is a meta tag that is inserted in the generated HTML so show what rendered it. It should not include the closing tag.
	// Defaults (note content quote is not closed) to `  <meta name="GENERATOR" content="github.com/panhongrainbow/markdown markdown processor for Go`
	Generator string
}

RendererOptions is a collection of supplementary parameters tweaking the behavior of various parts of HTML renderer.

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