Documentation
¶
Overview ¶
Package polyglot converts HTML to polyglot XHTML/HTML4/HTML5 markup, parseable by XML parsers in almost all cases (warning if not).
It does its best if the input is malformed, and has an optional strict mode. It emulates most of the HTML5 "adoption agency" algorithm and error recovery, so the final output ends up more or less equivalent to how a browser would parse it. There are hooks to allow a subset of transformations to be made in a single pass. There is also a CLI version (github.com/pgaskin/htmlstream/cmd/polyglottify).
Polyglot markup is markup which HTML parsers and XML parsers parse to the same document. The rules for the output are those of the W3C note Polyglot Markup: A robust profile of the HTML5 vocabulary, with the differences listed in Convert. HTML parsers parse the output to the same document as the input, apart from the changes listed in Convert (e.g., the doctype). XML parsers parse it to the same document as HTML parsers, except where Options.Warn reports input which can't be represented exactly. Converting the output again usually gives the same output, but this isn't guaranteed, especially for input with warnings.
Usage ¶
Convert converts a document read from an io.Reader. Writer converts the tokens of the caller's htmlstream.Reader, which can use other Reader options and leave out elements. The hooks (Options.OnTag and Options.OnText) edit the output as it is written, and AppendEscapeText and AppendEscapeAttr escape text and attribute values in the markup they insert.
Input which can't be represented exactly is converted anyway, and reported to Options.Warn. Errors stop the conversion and leave the output incomplete: structurally unsound input with Options.Strict, contents exceeding Options.MaxRawText, and held output exceeding Options.MaxHold.
Well-formedness ¶
The output is well-formed XML, which meets the namespace constraints of Namespaces in XML 1.0, except where the contents of a script element whose type is neither JavaScript nor JSON (see htmlutil.IsJavaScriptType and htmlutil.IsJSONType) contain <, & or "]]>". They are written as they are, with a warning (see Options.Warn), since there is no comment syntax of the script's language to put a CDATA section in, and escaping them would change them for HTML parsers. With Options.Strict, this is an error (an *Error) instead.
Well-formed means syntactically and structurally valid XML, which XML parsers read without errors. It doesn't mean valid against a DTD or schema (e.g., the XHTML DTDs): the output isn't validated. This is generally how browsers and non-validating parsing libraries (i.e., most of them) work.
Markup provided by the caller is written as it is, without checks, and can make the output not well-formed: Options.Doctype, the markup inserted by the hooks (Options.OnTag and Options.OnText), and the contents of scripts of other types set with Text.SetText.
Serving ¶
The media type decides which parser reads the output: browsers read a document served as text/html with their HTML parser, and one served as application/xhtml+xml with their XML parser. Opened from a file, they go by the file extension instead (e.g., .html for HTML and .xhtml for XHTML). Only without a media type does the content decide (see XMLDeclMode). The output is always UTF-8, so the charset parameter can be left out for XML media types. For text/html, the charset meta element the output starts the head with is enough, unless the conversion warned that it is past the first 1024 bytes, where HTML parsers look for it before parsing: serve such output as text/html; charset=utf-8.
Encodings ¶
The input must be UTF-8, which the output declares with <meta charset="UTF-8" />, and converting documents in other encodings to UTF-8 is up to the caller: the input is read as UTF-8 whatever it declares. Invalid UTF-8 is replaced with U+FFFD, with a warning. Meta elements declaring another encoding are replaced or removed like the others, and so is the first XML declaration before the root element (other XML declarations are written as comments). To convert a document, detect its encoding, e.g., with htmlutil.PrescanCharset (after the byte order mark and the charset parameter of the Content-Type header, as its documentation explains), and decode it with golang.org/x/text/encoding/htmlindex, golang.org/x/text/encoding/unicode and golang.org/x/text/transform, or with golang.org/x/net/html/charset, which does both:
br := bufio.NewReader(r)
head, _ := br.Peek(1024) // the whole input if it is shorter
name, ok := htmlutil.PrescanCharset(head)
if !ok {
name = "windows-1252" // or another default
}
enc, err := htmlindex.Get(name)
if err != nil {
return err
}
// BOMOverride decodes UTF-8 or UTF-16 instead if there is a byte order
// mark, and removes it.
err = polyglot.Convert(w, transform.NewReader(br, unicode.BOMOverride(enc.NewDecoder())), polyglot.Options{})
Index ¶
- Constants
- Variables
- func AppendEscapeAttr[S ~string | ~[]byte](dst []byte, s S) []byte
- func AppendEscapeText[S ~string | ~[]byte](dst []byte, s S) []byte
- func Convert(w io.Writer, r io.Reader, opt Options) error
- type DoctypeMode
- type Error
- type Hold
- type Options
- type Tag
- func (e *Tag) Declare(prefix, uri string)
- func (e *Tag) InsertAfter(raw []byte)
- func (e *Tag) InsertBefore(raw []byte)
- func (e *Tag) LookupPrefix(prefix string) (uri string, ok bool)
- func (e *Tag) Remove()
- func (e *Tag) RemoveAttr(name string)
- func (e *Tag) Rename(name string)
- func (e *Tag) RenameAttr(name, newName string)
- func (e *Tag) SetAttr(name, value string)
- func (e *Tag) Unwrap()
- func (e *Tag) Writer() *Writer
- type Text
- type Warning
- type Writer
- func (pw *Writer) Close() error
- func (pw *Writer) Err() error
- func (pw *Writer) Fail(err error)
- func (pw *Writer) Held(h Hold) []byte
- func (pw *Writer) Hold() Hold
- func (pw *Writer) HoldDiscard(h Hold, raw []byte) error
- func (pw *Writer) HoldRelease(h Hold) error
- func (pw *Writer) Holding() int
- func (pw *Writer) WriteToken(tok *htmlstream.Token) error
- func (pw *Writer) Written() int64
- type XMLDeclMode
Examples ¶
Constants ¶
const DefaultMaxRawText = 64 << 20
DefaultMaxRawText is the default of Options.MaxRawText, 64 MiB.
Variables ¶
var ErrInvalidOp = errors.New("polyglot: invalid operation")
ErrInvalidOp is the error of a Writer method or a hook event method (see Tag and Text) called in a state which doesn't allow it or with arguments it doesn't accept, and of tokens breaking the rules of the Writer. The error wraps it with details. Like other errors of the Writer except htmlstream.ErrHoldReleased, it is sticky, unlike htmlstream.ErrInvalidOp, after which a Transformer continues.
Functions ¶
func AppendEscapeAttr ¶
AppendEscapeAttr appends s to dst, escaped for use as a quoted attribute value like Convert escapes it: like htmlstream.AppendEscapeAttr, with U+00A0 written as  .
func AppendEscapeText ¶
AppendEscapeText appends s to dst, escaped for use as text like Convert escapes it: like htmlstream.AppendEscapeText, with U+00A0 written as   so it stays visible in the markup.
func Convert ¶
Convert converts an HTML document to polyglot markup (see the package documentation). On error, the output is incomplete: w has the output written before the error, which can end anywhere (e.g., in a tag).
The input must be UTF-8, which the output declares. Invalid UTF-8 is replaced with U+FFFD, with a warning, and so are the other characters XML doesn't allow, except NUL in text in HTML content, which HTML parsers ignore and Convert drops (see the conversion list below). Convert documents in other encodings to UTF-8 first (see Encodings in the package documentation).
Convert reads the input with the htmlstream.Reader of Options.NewReader: in HTML mode with the Reader's defaults, the maximum depth of Options.MaxDepth, the limits of Options.MaxTokenSize, Options.MaxStackBytes and Options.MaxInputSize, strict mode with Options.Strict, and XML syntax and scripting with Options.XMLSyntax and Options.Scripting. Without Options.Scripting, noscript contents are converted as markup, as XML parsers read them. To use other Reader options, set them on a Reader from Options.NewReader and pass its tokens to a Writer.
Besides its size, converting a token takes time proportional to at most the number of elements open in the output, for the formatting elements reopened before it and for the checks of the open elements HTML parsers also make (e.g., at an end tag of a formatting element which isn't open). Options.MaxDepth limits that number: lower it for untrusted input. The output can be much larger than the input, since formatting elements reopened after misnested end tags are copies, as in the DOM of HTML parsers (e.g., formatting elements left open in a div are copied around the text in each div after it).
Documents written as XHTML, with self-closing tags meant as empty elements (usually with an XML declaration or the XHTML xmlns attribute, e.g., EPUB content documents), need XML syntax (Options.XMLSyntax, see htmlstream.Reader.SetXMLSyntax). Without it, they are read as HTML parsers read them: a self-closing tag of a non-void element is a start tag, so <a id="p1"/> contains the content after it and <script src="a.js"/> takes the rest of the input as its contents (with a warning for raw text and RCDATA elements like script, style, title and textarea), </br> after <br> is another br element, CDATA sections are bogus comments, processing instructions are bogus comments (as HTML parsers read them before the current HTML Standard, which reads most of them as processing instructions; see the conversion list below), and a doctype with an internal subset ends at the first ">" in it. XML syntax is for documents written as XHTML: for HTML, it only changes the meaning of loosely written markup, such as <div class="clear"/>, a start tag for browsers reading text/html and an empty div with XML syntax.
Convert reads the input in HTML mode, and Writer only accepts tokens read in HTML mode. For documents of unknown type, HTML or XHTML, which would otherwise be read in htmlstream.Universal mode, HTML mode with XML syntax is usually good enough. Well-formed XHTML is then read with the HTML parsing rules rather than as XML parsers read it: elements are closed and restructured as in HTML parsers (e.g., a div start tag closes an open p, and misnested formatting elements are reopened), script and style contents are raw text, with a warning for character references and comments in them, title and textarea contents are text, a newline at the start of pre, textarea and listing is removed, with a warning, names are case-insensitive and prefixes don't bind namespaces, with a warning for prefixed names, and character references are decoded as in HTML (e.g., © without a semicolon is ©, and – is U+2013).
The conversion is a single streaming pass:
- The doctype is replaced with Options.Doctype (see Options.DoctypeMode for the alternatives), the XML declaration before the root element is removed (see Options.XMLDecl for writing one), and <meta charset="UTF-8" /> is added at the start of the head (before the markup hooks insert after the head start tag), replacing the charset declarations of the input, so the output has one encoding declaration: the charset attribute, and http-equiv="Content-Type" with its content attribute, are removed from meta elements, including the declarations HTML parsers don't recognize (see htmlutil.MetaCharset), and a meta element without other attributes is dropped. If such a meta element is the first element of the head, the added one takes its place, after the whitespace before it (up to 256 bytes); otherwise, and if the Tag hook of the head start tag inserts markup after it or starts a hold, the added one comes right after the head start tag.
- The XML declaration, the doctype and each comment before the root element are followed by a line break, which HTML and XML parsers ignore there. Other whitespace before the root element, which they ignore too, is dropped.
- Whitespace between the html start tag and the head, which HTML parsers drop (and XML parsers would keep), is dropped. Whitespace and comments between the head end tag and the body, which HTML parsers put in the html element, while they put head content after them in the head, are written between the head end tag and the body start tag. Past 64 KiB of them, they are written in the head instead.
- Comments after a body end tag, which HTML parsers put in the html element after the body, are written after the body end tag, and comments after an html end tag, which they put after the html element, after the html end tag. The whitespace around them, which they put in the body, is written in the body. Comments after content following these end tags, and after a body end tag HTML parsers ignore (e.g., in a table cell or a template), are written in place, and so are those in an SVG or MathML element (left open by the end tag, see below), where HTML parsers put them. Past 64 KiB of comments, they and the rest are written in the body where the limit is reached.
- Implied elements (html, head, body, tbody, tr, colgroup) and implied end tags are written explicitly.
- In quirks mode documents (no doctype, or a legacy one), HTML parsers put a table after an open p in the p, which the Reader closes before the table. When the output is in quirks mode too (with NoDoctype, with a doctype selecting quirks mode in Options.Doctype, or with KeepDoctype), the p is kept open around the table, and after it until the end tag of an element around it, a p end tag, or a start tag which closes a p, as in HTML parsers. Only the start tags of void elements, tables and elements whose contents are text (e.g., script and title) keep it open: before other start tags, and before formatting elements reopened after the table, it is closed with a warning, since HTML parsers would put the element in the p.
- HTML element and attribute names are lowercased, and SVG and MathML names get the case HTML parsers give them. The tags of elements whose names aren't XML names (see htmlstream.ValidXMLName) are left out, keeping their contents, and attributes whose names aren't XML names are dropped, with a warning. This includes names with NUL, which HTML parsers replace with U+FFFD. Attributes are quoted, duplicates are removed. On HTML elements, lang is mirrored to xml:lang and xml:lang to lang, so HTML and XML parsers use the same language.
- Void elements are written as <br />, and all other elements have end tags.
- The required xmlns attributes are added to html, svg and math.
- Text and attribute values are escaped for both HTML and XML, and character references are replaced with the characters (except for U+00A0, written as  ).
- NUL in text in HTML content, including integration points like foreignObject, is dropped, since HTML parsers ignore it. Elsewhere, and in CDATA sections, it is replaced with U+FFFD, with the warning for characters XML doesn't allow: HTML parsers replace it in SVG and MathML content, and the tokenizer does in comments, attribute values and the contents of elements like script, title and textarea (see htmlstream.Token.AppendText). A newline after NUL directly after the start tag of a pre or listing, which the HTML Standard keeps (browsers drop it), can't be represented (with a warning).
- Script and style contents containing < or & are wrapped in a CDATA section inside a comment of the script or style language, after removing such a wrapper if the contents already have one, including the forms with HTML comment markers written by CMSs such as Drupal (see htmlutil.CutCDATAWrapper; not in modules), and keeping the whitespace around it. The start of the wrapper is followed by a line break and its end preceded by one, unless the contents start or end with a single line break, which takes its place. For JSON scripts, the characters are escaped as JSON instead. Scripts of other types are written as they are, with a warning (see Well-formedness in the package documentation).
- Formatting elements closed by misnested end tags are reopened like HTML parsers do (a simplified version of the adoption agency algorithm), so <b><i>x</b>y</i> becomes <b><i>x</i></b><i>y</i>.
- Leading newlines in pre, textarea and listing, which HTML parsers drop, are removed.
- xmp and plaintext are converted to pre. A leading newline in them, which HTML parsers keep, is removed with a warning, since pre can't represent it.
- The contents of iframe, noembed and noframes, which HTML parsers read as text and XML parsers as markup, are dropped, with a warning, unless they are whitespace only, which both read the same.
- Tags cut off by the end of the input, which HTML parsers drop, are dropped.
- xmlns attributes are only written on html, svg and math and on HTML elements in foreign content (e.g., in foreignObject), with the namespace HTML parsers give the element, replacing another value (which HTML parsers ignore). They are dropped from other elements.
- "--" in comments, which XML doesn't allow, is written as "- -", and a space is added at the start of a comment starting with > or -> and at the end of one ending with -, which changes the comment for HTML parsers.
- Processing instructions are written as comments, and so are XML declarations other than the first one before the root element, as HTML parsers read them. The current HTML Standard reads most processing instructions (<?target data>) as processing instructions, while polyglot writes them as comments, which all HTML parsers (older ones too) and XML parsers read the same.
Known differences from HTML parsing which aren't handled are reported through Options.Warn:
- content in tables outside cells, which HTML parsers move before the table, and elements inside head content which they move to the body;
- misnested formatting elements where the adoption agency algorithm restructures the elements, and end tags HTML parsers ignore;
- content after a body or html end tag which closed other elements (other than the head, which they close too), which HTML parsers keep open and put the content in, and likewise after a noscript end tag which closed a special element (ignored by HTML parsers, which keep the noscript open too), or an end tag of an element already closed. Whitespace after these end tags is written in the elements, as HTML parsers put it there, and so are comments after the noscript and other end tags, up to the first other token (e.g., content, or a stray end tag) and 64 KiB of whitespace in one text; whitespace and comments after that aren't reported. An end tag of an SVG or MathML element among them, which HTML parsers apply to it, closes it and the elements inside it, and the others stay open;
- template contents which HTML parsers parse differently: they parse them like the contents of a table, a table row, etc., or body content, depending on the first child element; and template end tags closing a cell or another marker element open inside the template, after which HTML parsers reopen formatting elements differently;
- start tags HTML parsers ignore: table parts outside a table, frame, frameset, nested forms and nested selects in the body, and noscript in a noscript in the head;
- element and attribute names with a namespace prefix, which XML parsers resolve, and HTML parsers don't (except for some xlink and xml attributes of SVG and MathML elements): x:a in <p xmlns:x="u" x:a="1"> is in namespace u for XML parsers and in no namespace for HTML parsers. This is reported once for each prefix and namespace, so the epub:type attributes of EPUB content give one warning. HTML parsers keep the prefix in element names, so they also differ when the namespaces are the same;
- namespace declarations which are invalid in XML (of the xmlns prefix, of the xml prefix to another namespace, and of other prefixes to an empty namespace name or to the XML or XMLNS namespace), which are dropped, leaving the prefix unbound; element and attribute names with an unbound prefix, element names with the xmlns prefix, and attributes with the same namespace and local name as another one for XML parsers, which are dropped;
- xml:lang on HTML elements with a value other than lang's: HTML parsers use lang for the language, and XML parsers xml:lang, which is written with the value of lang;
- elements nested past the Reader's stack limits or the output depth limit (Options.MaxDepth), which are dropped, and formatting elements which would be reopened past the output depth limit, which aren't;
- incomplete script and style end tags at the end of their contents (cut off by the end of the input, or followed by the end tag), which HTML parsers keep as text, and are dropped, and scripts cut off inside an escaped script (<!--<script), which can't be closed for HTML parsers;
- noscript in an implied head or after a misplaced head start tag, where the Reader's rules for noscript in the head differ from HTML parsers (with scripting disabled), including at NUL in text, which closes a noscript in the head for them before they ignore it;
- tables after an open p in quirks mode documents, where HTML parsers put the table in the p (or in the elements open in it), unless the output is in quirks mode too and only the p is open (see above): the output closes the p before the table explicitly; and with the p kept open, start tags of other elements and formatting elements reopened after the table, and end tags of elements around the p which HTML parsers ignore or apply differently with the p open;
- script and style contents containing "]]>", which is written as "]]]]><![CDATA[>" to keep the CDATA section open, which changes the contents for HTML parsers ("]]]]><![CDATA[>" in a CDATA wrapper of the input is read as "]]>", and written as it was);
- the charset meta element written past the first 1024 bytes of the output (after long comments before the root element, or long attributes on html or head), where HTML parsers which aren't told the encoding don't look for it (see Serving in the package documentation), unless the output starts with an XML declaration (AddXMLDecl, or KeepXMLDecl with one in the input), from which they take UTF-8 instead. Its position is taken when it is written: markup put before it later by Writer.HoldDiscard isn't counted.
A warning message describes the input or what the conversion did with it, often followed in parentheses by what HTML parsers would have done with the input instead ("HTML parsers would have ..."), how they will read the output ("HTML parsers will ... when parsing the output") or what the conversion matches ("to match ..."), and by "(will not warn again)" for a warning given only once.
The rules of the output are those of the W3C polyglot markup note: UTF-8 declared with a meta element (with the charset attribute: the current HTML Standard doesn't allow the http-equiv form in XML documents, see encoding declaration), the HTML5 doctype, the html, svg and math namespace declarations (and that of the xlink prefix), no omitted tags, tbody and colgroup elements, lowercase names except for the SVG and MathML ones with mixed case, void elements as empty-element tags, safe text content or safe CDATA content in script and style, no leading newline in pre and textarea, quoted attribute values with tabs and newlines as character references, lang and xml:lang with the same value, no named character references other than those of XML, and comments which don't start with > or ->. The output differs from the note where it doesn't match the current HTML Standard, or asks for what a conversion can't decide:
- SVG and MathML names get the case HTML parsers give them (see htmlstream.AdjustSVGTagName and htmlstream.AdjustSVGAttrName): the list of element names doesn't have feDropShadow, and the list of attribute names has contentScriptType, contentStyleType, externalResourcesRequired and filterRes, which HTML parsers lowercase.
- noscript elements, which the note excludes, are kept.
- Options.XMLDecl can write an XML declaration, which the note forbids, and Options.Doctype another doctype.
- A title element, which the note requires in a minimal document, isn't added.
- xml:space and xml:base attributes on HTML elements, which the note disallows, are kept, with the warning for prefixed attributes.
- The case of attribute values which HTML compares case-insensitively isn't changed (see attribute values), and id attributes aren't checked to be unique XML names (see the id attribute).
Example ¶
Convert writes the implied elements and end tags, quotes attributes, closes void elements, replaces character references, declares the namespaces and the encoding, and reopens misnested formatting elements.
package main
import (
"os"
"strings"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<!doctype html>
<html lang=en><title>Fish & chips</title>
<P CLASS=intro>Fish & chips<br>
<IMG SRC=fish.png alt=Fish>
<table><tr><td>Cod<td>£8</table>
<p><b>bold <i>both</b> italic</i>`
if err := polyglot.Convert(os.Stdout, strings.NewReader(page), polyglot.Options{}); err != nil {
panic(err)
}
}
Output: <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta charset="UTF-8" /><title>Fish & chips</title> </head><body><p class="intro">Fish & chips<br /> <img src="fish.png" alt="Fish" /> </p><table><tbody><tr><td>Cod</td><td>£8</td></tr></tbody></table> <p><b>bold <i>both</i></b><i> italic</i></p></body></html>
Example (Doctype) ¶
The doctype of the input can be kept or replaced, and an XML declaration added.
package main
import (
"bytes"
"fmt"
"strings"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><p>Text`
for _, opt := range []polyglot.Options{
{},
{DoctypeMode: polyglot.KeepDoctype, XMLDecl: polyglot.AddXMLDecl},
{Doctype: "<!DOCTYPE html SYSTEM \"about:legacy-compat\">"},
{DoctypeMode: polyglot.NoDoctype},
} {
var b bytes.Buffer
if err := polyglot.Convert(&b, strings.NewReader(page), opt); err != nil {
panic(err)
}
head, _, _ := strings.Cut(b.String(), "<html")
fmt.Printf("%q\n", head)
}
}
Output: "<!DOCTYPE html>\n" "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" "<!DOCTYPE html SYSTEM \"about:legacy-compat\">\n" ""
Example (Script) ¶
Script and style contents with < or & are wrapped in a CDATA section inside a comment, and JSON is escaped instead.
package main
import (
"os"
"strings"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<script>if (a < b && c) go()</script>
<script>ok()</script>
<style>a > b { color: red }</style>
<script type=application/ld+json>{"name": "<Fish & chips>"}</script>`
if err := polyglot.Convert(os.Stdout, strings.NewReader(page), polyglot.Options{DoctypeMode: polyglot.NoDoctype}); err != nil {
panic(err)
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /><script>//<![CDATA[ if (a < b && c) go() //]]></script> <script>ok()</script> <style>a > b { color: red }</style> <script type="application/ld+json">{"name": "\u003cFish \u0026 chips\u003e"}</script></head><body></body></html>
Example (Strict) ¶
With Options.Strict, structurally unsound input is an error instead of being converted on a best-effort basis.
package main
import (
"errors"
"fmt"
"io"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
for _, page := range []string{
`<p>Optional end tags<li>are fine`,
`<div><span>Unclosed span</div>`,
} {
err := polyglot.Convert(io.Discard, strings.NewReader(page), polyglot.Options{Strict: true})
var serr *htmlstream.SyntaxError
switch {
case errors.As(err, &serr):
fmt.Printf("%s: offset %d: %s\n", page, serr.Pos, serr.Msg)
case err != nil:
panic(err)
default:
fmt.Printf("%s: ok\n", page)
}
}
}
Output: <p>Optional end tags<li>are fine: ok <div><span>Unclosed span</div>: offset 24: element "span" at offset 5 closed without its end tag
Example (Warnings) ¶
Input which polyglot markup can't represent exactly is reported through Options.Warn.
package main
import (
"bytes"
"fmt"
"strings"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<p xmlns:epub="http://www.idpf.org/2007/ops" epub:type="note">Note</p>
<table>stray text<tr><td>cell</td></tr></table>`
var b bytes.Buffer
err := polyglot.Convert(&b, strings.NewReader(page), polyglot.Options{
DoctypeMode: polyglot.NoDoctype,
Warn: func(w polyglot.Warning) {
fmt.Printf("offset %d: %s\n", w.Pos, w.Msg)
},
})
if err != nil {
panic(err)
}
fmt.Println(b.String())
}
Output: offset 0: attribute "epub:type" is in namespace "http://www.idpf.org/2007/ops" for XML parsers and in no namespace for HTML parsers (will not warn again for this prefix and namespace) offset 78: kept text in a table outside a cell (HTML parsers would have moved it before the table) <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /></head><body><p xmlns:epub="http://www.idpf.org/2007/ops" epub:type="note">Note</p> <table>stray text<tbody><tr><td>cell</td></tr></tbody></table></body></html>
Types ¶
type DoctypeMode ¶
type DoctypeMode uint8
DoctypeMode selects the document type declaration written by Convert and Writer.
The default, <!DOCTYPE html>, selects no-quirks mode in HTML parsers, like XML parsers, which always use it. Without a doctype (NoDoctype), or with a kept doctype selecting quirks or limited-quirks mode, HTML parsers use that mode while XML parsers don't, so browsers can lay out the document differently. In quirks mode, HTML parsers also put a table after an open p in the p, and the output keeps the p open around it then (see Convert). A doctype with an XHTML public identifier doesn't change how XML parsers read the output, which has no named character references other than those XML predefines. EPUB 3.3 allows no external identifier in the doctype of XHTML content documents (see EPUB XML conformance), so the default is the one to use there.
const ( // ReplaceDoctype writes [Options.Doctype] at the start of the document, // and removes the doctype of the input. ReplaceDoctype DoctypeMode = iota // KeepDoctype writes the doctype of the input where it is (after the // comments before it), as HTML parsers read it: the name lowercased, and // the public and system identifiers, in double quotes (or single quotes // for a system identifier containing double quotes). A public // identifier without a system identifier gets an empty one, which XML // requires. Doctypes HTML parsers ignore (after other content) are // removed. A doctype which can't be represented in XML (the name isn't // an XML name, the public identifier has characters XML doesn't allow in // it, or the system identifier has both kinds of quotes) or has a > in // its system identifier, where HTML parsers end it, is removed with a // warning, and so is one selecting another document mode // (quirks, limited-quirks or no-quirks) in HTML parsers as written than // in the input (e.g., a malformed one). KeepDoctype // NoDoctype writes no doctype, and removes the doctype of the input. NoDoctype )
type Error ¶
type Error struct {
Pos htmlstream.Pos // the position of the token
Msg string // the problem
}
Error is an error at a position in the input which stops the conversion: buffered contents exceeding Options.MaxRawText (of script and style elements, of noscript elements read as raw text, and of title and textarea elements read with XML syntax, see there), and with Options.Strict, a script which can't be represented in XML (see Well-formedness in the package documentation).
type Hold ¶
type Hold struct {
// contains filtered or unexported fields
}
A Hold identifies a hold started by Writer.Hold, for Writer.HoldRelease, Writer.HoldDiscard and Writer.Held. It is only valid with the Writer which returned it. The zero Hold is no hold.
type Options ¶
type Options struct {
// Doctype is the document type declaration written at the start of the
// document with [ReplaceDoctype], the default DoctypeMode. If empty,
// "<!DOCTYPE html>" is used.
Doctype string
// DoctypeMode selects the document type declaration written.
DoctypeMode DoctypeMode
// XMLDecl selects the XML declaration written at the start of the
// document (see [XMLDeclMode] for why to write one or not). The XML
// declaration of the input isn't copied: [AddXMLDecl] and [KeepXMLDecl]
// write a fixed one.
XMLDecl XMLDeclMode
// Strict makes structurally unsound input an error instead of converting
// it on a best-effort basis. It also causes conversion to fail if the
// output is not representable as well-formed XML (see Well-formedness in
// the package documentation). Convert also reads the input in strict mode
// (see [htmlstream.Reader.SetStrict]). Other input which can't be
// represented exactly (e.g., invalid UTF-8, dropped attributes, and the
// differences from HTML parsing listed in [Convert]) is still converted,
// with a warning (see Warn). To fail on warnings, call [Writer.Fail] from
// Warn.
Strict bool
// XMLSyntax and Scripting enable XML syntax and scripting in the Reader
// of [Options.NewReader], which [Convert] uses (see
// [htmlstream.Reader.SetXMLSyntax] and [htmlstream.Reader.SetScripting]).
// A [Writer] ignores them: its caller's Reader decides them.
XMLSyntax, Scripting bool
// Warn, if not nil, is called for input which can't be represented
// exactly as polyglot markup. The output converted so far is flushed to
// the destination writer before each call, so warnings written to an
// unbuffered stream (e.g., a terminal showing both) appear after the
// output before them. Output still held back comes after the warning:
// the contents of script and style elements, of noscript elements read
// as raw text and of title and textarea elements read with XML syntax
// starting with a CDATA section (see [Writer]), which are buffered until
// their end tag, the whitespace at the start of other title and textarea
// contents read with XML syntax, buffered until the text after it, the
// whitespace at the start of text before which formatting elements are
// reopened if other text follows (see [Convert]), buffered until that
// text or the end of the text (up to 64 KiB), the whitespace at the
// start of the head, buffered until the next token (up to 256 bytes),
// the whitespace and comments between the head end tag and the body,
// buffered until the body starts (up to 64 KiB), the comments after the
// body and html end tags, buffered until Close (up to 64 KiB), with
// [Options.Indent], the whitespace and comments at block boundaries,
// buffered until the next token (up to 64 KiB), the output before the
// root element with [KeepXMLDecl], and the output held by [Writer.Hold].
Warn func(w Warning)
// MaxRawText limits the size of script and style contents, noscript
// contents read as raw text, and title and textarea contents read with
// XML syntax starting with a CDATA section (after whitespace) and the
// whitespace at the start of other ones, which are buffered to decide
// how to write them, and of the output before the root element with
// [KeepXMLDecl] (the comments and the doctype of the input, without the
// doctype written with [ReplaceDoctype]). If zero, [DefaultMaxRawText] is
// used, and if negative, any contents exceed it. Exceeding it is an error (an
// [*Error]), except for the output before the root element: then the XML
// declaration is dropped with a warning instead (also with a negative
// limit, for any output before the root element).
MaxRawText int
// MaxDepth limits the depth of the output (an element with the elements
// around it), as [htmlstream.Reader.SetMaxDepth] does that of the input.
// Formatting elements are reopened after misnested end tags (see
// [Convert]) only up to it, and other elements nested past it are
// dropped, keeping their contents, with a warning for each. Reopened
// formatting elements can nest much deeper than the elements of the
// input (e.g., <div><b></div>x repeated nests a b in the b before it),
// and XML parsers often limit the depth (e.g., to 256). If zero,
// [htmlstream.DefaultMaxDepth] is used, and values below 3 (the charset
// meta element in the head) are treated as 3. The Reader of
// [Options.NewReader], which [Convert] uses, also limits the depth of the
// input to it.
MaxDepth int
// MaxHold limits the size of the output held back by [Writer.Hold]:
// exceeding it is an error ([htmlstream.ErrHoldLimit]). If zero,
// [htmlstream.DefaultMaxHold] is used, and if negative, holding back any
// output is an error.
MaxHold int
// MaxTokenSize, MaxStackBytes and MaxInputSize, if not zero, set the
// limits of the Reader of [Options.NewReader], which [Convert] uses (see
// [htmlstream.Reader.SetMaxTokenSize],
// [htmlstream.Reader.SetMaxStackBytes] and
// [htmlstream.Reader.SetMaxInputSize]). If zero, the Reader's defaults
// are used, with no limit on the size of the input. For untrusted input,
// set lower ones.
MaxTokenSize int
MaxStackBytes int
MaxInputSize int64
// FinalNewline ends the output with a line break after the html end tag,
// which HTML parsers append to the body and XML parsers ignore. A line
// break ending whitespace at the end of the body (e.g., the line break
// at the end of the input, which HTML parsers put in the body) is written
// there instead of in the body, and so is the line break [Options.Indent]
// writes before the body end tag, so HTML parsers read the same body;
// otherwise, the body HTML parsers read ends with a line break more than
// the one XML parsers read. No Text event is reported for it.
FinalNewline bool
// Indent, if not empty, indents the output: the whitespace between block
// boundaries (the start and end tags of block-level elements, see
// [htmlutil.IsBlock], and of table cells, and the elements in the head)
// is replaced with a line break followed by Indent once for each level
// of block-level elements around it (up to 64 levels), and the comments
// there are put on lines of their own. A line break is added where
// there is no whitespace, and one empty line is kept where the input
// has one or more between two elements. The spaces and tabs starting
// the lines of text are replaced with the indentation of the contents
// of the block-level element around it. The children of the html
// element aren't indented, and there is no line break between the html
// start tag and the head, and after the body (see [Convert]). With
// [Options.FinalNewline], the line break before the body end tag is
// written after the html end tag instead.
//
// Other whitespace is written as it is: in inline content (where adding
// or removing whitespace would change the rendered text), in
// preformatted elements (pre, listing, textarea), in elements whose
// contents are text (title, script, style, and noscript, which HTML
// parsers with scripting enabled read as text), in SVG and MathML
// content, and whitespace before which HTML parsers reopen formatting
// elements (see [Convert]), which changes the structure. The
// classification of elements is that of the default styles of HTML:
// style sheets which make block-level elements inline, or set
// white-space to keep the whitespace in other elements, make the
// changed whitespace visible.
//
// Indentation changes the whitespace text of the document for HTML and
// XML parsers alike. The whitespace held back until the next token to
// decide (see [Options.Warn], up to 64 KiB) is reported to the Text hook
// when it is written as it is, and the whitespace replaced and the line
// breaks and indentation written aren't. The Text hook gets the text
// before the spaces and tabs starting its lines are replaced. Markup
// inserted by the hooks (and written by [Writer.HoldDiscard]) is
// written as it is, and doesn't change the indentation.
Indent string
// IndentPrefix, if not empty, is written at the start of each line of
// the output after the first one, except in comments and in the
// contents written as they are with Indent (preformatted elements,
// elements whose contents are text, and SVG and MathML content). It
// doesn't start empty lines. It can be used without Indent, to indent a
// document as a whole, and then replaces the spaces and tabs starting
// the lines of text, as Indent does. Like Indent, it changes the
// whitespace text of the document.
//
// Indent and IndentPrefix must contain only spaces and tabs: other
// characters fail the conversion with an error wrapping [ErrInvalidOp].
IndentPrefix string
// OnTag, if not nil, is called before each element tag is written, with a
// description of the tag (see [Tag]). It is called for the tags of the
// output: those written for the input, and those of the elements the
// conversion adds. A hook which does nothing leaves the output unchanged;
// the methods of the event change what is written.
OnTag func(e *Tag)
// OnText, if not nil, is called for each part of the text written (see
// [Text]). A hook which does nothing leaves the output unchanged (the
// text escaped, or written as contents when Raw); the methods of the
// event change what is written.
OnText func(t *Text)
}
Options configures Convert and Writer.
func (Options) NewReader ¶ added in v0.0.2
func (opt Options) NewReader(r io.Reader) *htmlstream.Reader
NewReader returns an htmlstream.Reader reading r as Convert does: in HTML mode with the Reader's defaults, the maximum depth of MaxDepth (with the same default and minimum as the output depth), the limits of MaxTokenSize, MaxStackBytes and MaxInputSize, strict mode with Strict, and XML syntax and scripting with XMLSyntax and Scripting. Other options can be set on it before reading, e.g., to pass its tokens to a Writer created with opt, which needs a maximum depth of at least 3.
type Tag ¶
type Tag struct {
// Start is true for a start tag and false for an end tag.
Start bool
// Void is true for both events of an HTML void element (e.g., br). Its
// end tag event comes right after the start tag event, with no tag
// written: markup inserted for it is written after the start tag.
// Other self-closed elements aren't void: they are written with an end
// tag (e.g., <circle /> as <circle></circle>).
Void bool
// Reopened is set for the start tag of a formatting element reopened
// after a misnested end tag closed it (<b><i>x</b>y</i> is written as
// <b><i>x</i></b><i>y</i>), and for its end tag. The start tag written
// is the element's start tag as written the first time, with its
// attribute edits and name (see Rename).
Reopened bool
// Name is the element name as written (lowercase for HTML elements; see
// Rename). Local and NS are the local name and namespace XML parsers give
// the element (the XHTML namespace for HTML elements).
Name, Local, NS string
// ID numbers the elements of the output from 1, in the order of their
// start tags. An element's start and end tag events have the same ID,
// and so do the reopened copies of a formatting element and their end
// tags, so a hook can keep what it found out about an element by ID.
ID int
// Depth is the number of elements open in the output around the element
// (0 for the html element), the same for its start and end tags.
Depth int
// Token is the input start tag of the element, for start tags written
// for the input. It is nil for end tags, for the tags of the elements
// the conversion adds and for reopened elements (see ID).
Token *htmlstream.Token
// contains filtered or unexported fields
}
Tag describes an element tag about to be written, for Options.OnTag. The tags are those of the output: the element structure HTML parsers give the input, with the elements the conversion adds (implied html, head and body elements, the charset meta element, tbody, tr and colgroup implied in tables, formatting elements reopened after a misnested end tag, and the elements written for stray </p> and </br> end tags), and without those it drops. Start and end tag events are paired (with the same ID, Name, Local, NS and Reopened) and nested, and no tag event comes in the middle of a text node (see Text).
The event is owned by the writer and valid during the call: the hook must not keep it or call its methods after returning. Its fields are for reading, and assigning them changes nothing: its methods change what is written for the tag; without them, the tag is written unchanged. Called in a way they don't allow (also after the hook returns), they make the conversion fail with an error wrapping ErrInvalidOp, which Writer.WriteToken and Writer.Close (and Convert) return; a hook can check Writer.Err to stop early. Markup passed to a method is written when the hook returns, and not kept.
Inserted markup (InsertBefore, InsertAfter, Text.SetMarkup and Writer.HoldDiscard) is written as is, and isn't checked: it must keep the output polyglot markup, well-formed XML which HTML parsers parse to the same document as XML parsers (see Convert). This means:
- It is balanced: well-formed on its own, or balanced across the start and end tag events of one element (wrapping the element), or within one text node (opened in a part and closed by the Last call).
- XML parsers read inserted elements in the namespace in scope (the default namespace of the enclosing element) and HTML parsers read them as HTML elements in HTML content and as foreign elements in svg and math content: insert HTML markup only where NS is the XHTML namespace and not inside svg or math (except in an integration point like foreignObject, where the enclosing element is an HTML element), and declare any prefix it uses, unless the prefix is bound where the markup is inserted (by a declaration of the input, or with Declare; see LookupPrefix).
- It avoids the places where HTML parsers restructure or ignore content: table content outside cells (moved before the table), select, the head (elements other than head content start the body), before the html start tag and after the body end tag, title and textarea (markup is text for HTML parsers), script and style (the contents are wrapped in a CDATA section when needed, but </script or </style inside them ends the element, and so does an incomplete one at their end, completed by the markup after it; HTML parsers ignore the script end tag after <!--<script without a later -->), and block elements inside p (which closes the p).
- Text and attribute values are escaped (AppendEscapeText, AppendEscapeAttr) and have only characters allowed in XML (see htmlstream.AppendXMLChars), script and style contents have no ]]>, and comments have no --.
- The contents of pre, listing and textarea don't start with a newline (inserted after the start tag, or at the start of the first text): HTML parsers drop it, and XML parsers keep it.
Example ¶
The Tag hook edits the tags as they are written: here, attributes of links and images, a wrapper around tables and the removal of iframes.
package main
import (
"os"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<p><a href=https://example.com/>External</a> <a href=/about>About</a></p>
<table><tr><td>1</td></tr></table><iframe src=ad.html></iframe><img src=a.png>`
err := polyglot.Convert(os.Stdout, strings.NewReader(page), polyglot.Options{
DoctypeMode: polyglot.NoDoctype,
OnTag: func(e *polyglot.Tag) {
if e.NS != htmlstream.NamespaceXHTML {
return
}
switch {
case e.Start && e.Name == "a" && e.Token != nil:
if href, ok := e.Token.Attr("href"); ok && strings.HasPrefix(href.Value(), "https://") {
e.SetAttr("rel", "noopener")
}
case e.Start && e.Name == "img":
e.SetAttr("loading", "lazy")
case e.Name == "table":
if e.Start {
e.InsertBefore([]byte(`<div class="scroll">`))
} else {
e.InsertAfter([]byte(`</div>`))
}
case e.Start && e.Name == "iframe":
e.Remove()
}
},
})
if err != nil {
panic(err)
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /></head><body><p><a href="https://example.com/" rel="noopener">External</a> <a href="/about">About</a></p> <div class="scroll"><table><tbody><tr><td>1</td></tr></tbody></table></div><img src="a.png" loading="lazy" /></body></html>
func (*Tag) Declare ¶ added in v0.0.4
Declare declares the namespace prefix on the start tag, like a namespace declaration of the input: the attribute xmlns:prefix with the namespace name uri as its value (escaped like a value of the input) is added after the attributes of the tag, and repeated by the reopened copies of a formatting element (see Reopened). XML parsers bind the prefix to the namespace in the element and its contents: the prefixed names of the input in them are bound by it, with the warning for prefixed names (see Convert) when the namespace isn't the one HTML parsers give them, and attributes with the prefix can be set with SetAttr on this tag (after Declare) and on the tags in the element (e.g., xmlns:epub declared on the html element for epub:type attributes set on the elements in it). HTML parsers read the declaration as an attribute named xmlns:prefix in no namespace, as they read the declarations of the input (except xmlns:xlink on SVG and MathML elements, which they put in the XMLNS namespace like XML parsers).
If the tag already declares the prefix with the same namespace name (in the input, or by an earlier call), Declare does nothing. A prefix bound to another namespace by an enclosing element is bound to uri in the element and its contents. The namespace name isn't checked to be a URI.
It fails the conversion for an end tag, a reopened element, the charset meta element and an unwrapped or removed element (Unwrap after Declare fails too, see there), for a tag declaring the prefix with another namespace name, for a prefix bound by an enclosing element to another namespace name when the tag's name or attributes (of the input, or set before) use the prefix (they were written for that namespace), and for declarations invalid in XML: an empty prefix (the default namespace is written by the conversion, see Convert), a prefix which isn't an XML name, the xmlns prefix, the xml prefix bound to a namespace other than the XML namespace, another prefix bound to the XML or XMLNS namespace, an empty namespace name, and a namespace name with characters not allowed in XML.
Example ¶
Declare declares a namespace prefix on the html element (here, the EPUB one, kept if the input declares it already), for the attributes set with it on the elements in it.
package main
import (
"os"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<h1>Chapter 1</h1><p>Text<a href="#n1">1</a></p><aside id="n1">Note</aside>`
err := polyglot.Convert(os.Stdout, strings.NewReader(page), polyglot.Options{
DoctypeMode: polyglot.NoDoctype,
OnTag: func(e *polyglot.Tag) {
if !e.Start || e.NS != htmlstream.NamespaceXHTML {
return
}
switch e.Name {
case "html":
e.Declare("epub", "http://www.idpf.org/2007/ops")
case "a":
e.SetAttr("epub:type", "noteref")
case "aside":
e.SetAttr("epub:type", "footnote")
}
},
})
if err != nil {
panic(err)
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><meta charset="UTF-8" /></head><body><h1>Chapter 1</h1><p>Text<a href="#n1" epub:type="noteref">1</a></p><aside id="n1" epub:type="footnote">Note</aside></body></html>
func (*Tag) InsertAfter ¶
InsertAfter writes raw after the tag (for the end tag event of a void element, after its start tag). Markup inserted by several calls is written in order. Markup inserted after the head start tag is written after the charset meta element (see Convert). See Tag for the rules inserted markup follows.
func (*Tag) InsertBefore ¶
InsertBefore writes raw before the tag. Markup inserted by several calls is written in order. See Tag for the rules inserted markup follows.
func (*Tag) LookupPrefix ¶ added in v0.0.4
LookupPrefix returns the namespace XML parsers bind the prefix to at the tag, and whether it is bound, by the declarations written on the start tag so far (those of the input kept in the output, the xlink declaration the conversion adds to svg elements and to elements with xlink attributes, those made with Declare, and those the reopened copies of a formatting element repeat, or add for a prefix of their attributes which isn't bound to the same namespace where they are reopened, with a warning; see Reopened) and on the enclosing elements. At an end tag, the element's own declarations are in scope (markup inserted after the end tag is outside the element, where they aren't). A declaration of the input which is invalid in XML isn't written and leaves the prefix unbound in the element (see Convert), and LookupPrefix reports it unbound.
The xml prefix is always bound to the XML namespace, and the xmlns prefix is reported as unbound, like by htmlstream.Reader.LookupPrefix. The empty prefix is the default namespace, declared by the conversion (see Convert): the namespace of the innermost element with an unprefixed name (the element itself when its Name has no prefix, so NS for HTML, SVG and MathML elements).
It doesn't fail the conversion, except when called after the hook returned (see Tag), where it reports the prefix unbound.
func (*Tag) Remove ¶
func (e *Tag) Remove()
Remove leaves out the element: the tag, the contents and the end tag (like leaving out all of its tokens, see Writer). No events are reported for the contents, and the end tag event is still reported, with no tag written. Markup inserted before or after either tag (in this event or in the end tag event) is still written, in that order, where the element was. Text nodes separated only by a removed element are still reported as two nodes. Like an unwrapped one, a removed formatting element isn't reopened and doesn't count toward the identical ones HTML parsers keep to reopen. It fails the conversion for an end tag, a reopened element, html, head and body (also those of the input), an element the conversion adds and the first child element of a template (see Unwrap). Removing other elements doesn't change how HTML parsers read the rest of the document.
func (*Tag) RemoveAttr ¶
RemoveAttr removes the attribute name from the start tag, if it has it. On HTML elements, lang and xml:lang are removed together. It fails the conversion like SetAttr (for a tag which can't be edited, and for a name which isn't an XML name or is a namespace declaration, which can't be removed: the names in the element may use it).
func (*Tag) Rename ¶
Rename renames the element to name: its start and end tags are written with the name, and so are its copies reopened after a misnested end tag (see Reopened). The event's Name and Local are changed, and the events of the end tag and of the reopened copies have the name too. The conversion still applies the rules of the element's name in the input (e.g., which elements are reopened), which are the same for both names.
Only renames which keep the element structure HTML parsers build are allowed: both names must be in one of these groups of HTML elements, whose members the tree construction rules of the HTML Standard handle with the same steps everywhere, and which are in the same categories (special, formatting, closing an open p, ending foreign content, scope boundaries):
- h1, h2, h3, h4, h5, h6
- pre, listing
- article, aside, details, dir, fieldset, figcaption, figure, footer, header, hgroup, main, nav, section, summary
- blockquote, center, dl, menu
- ol, ul
- applet, marquee, object
- b, big, code, em, i, s, small, strike, strong, tt, u
- span, sub, sup, var
- abbr, acronym, bdi, bdo, cite, data, del, dfn, ins, kbd, mark, q, samp, time
- area, wbr
- embed, img
- param, source, track
Elements with steps of their own are left out, and so are those named in the steps for other elements: e.g., address, div and p (an li, dd or dt start tag closes an open li, dd or dt through them, but not through other special elements), a, font and nobr, ruby and its parts, button, form, select and its contents, list items, table parts and head content. So are elements whose handling differs between the versions of the standard HTML parsers implement: search and dialog (which close an open p in recent versions) and keygen (in a select).
It fails the conversion for an end tag, a reopened element (rename its first start tag, which the reopened copies repeat), a foreign element, and names which aren't in the same group. Renaming an element to its own name does nothing, even for elements outside the groups.
Renaming formatting elements (e.g., b to i) changes which of them HTML parsers consider identical (the same name and attributes). With more than three identical formatting elements, HTML parsers keep only the last three to reopen after misnested markup (see the Noah's Ark clause of push onto the list of active formatting elements), so the renamed output can nest differently than the renamed input would.
func (*Tag) RenameAttr ¶ added in v0.0.4
RenameAttr renames the attribute name of the start tag to newName, if the tag has it (of the input, or added by SetAttr), in place: the attribute keeps its position among the attributes of the tag, and its value as written (escaped like a value of the input, and on HTML elements, the value of lang for xml:lang, see Convert). If the tag already has an attribute named newName, that attribute is removed. On HTML elements, lang and xml:lang are kept together, as by SetAttr and RemoveAttr: renaming either of them removes the other, and renaming an attribute to either of them adds the other (after the attributes of the tag, if the tag doesn't have it) with the value. Renaming an attribute to its own name does nothing. The reopened copies of a formatting element repeat the rename (see Reopened).
An attribute can be renamed to a prefixed name (e.g., type to epub:type) and back. The prefix must be bound where the tag is, as for SetAttr (by a declaration of the input, or by Declare on this tag before RenameAttr or on the tag of an enclosing element). XML parsers put the attribute in the namespace bound to the prefix, and HTML parsers in no namespace, with the prefixed name (except for some xlink and xml attributes of SVG and MathML elements, see Convert), like for attributes of the input and SetAttr.
It fails the conversion like SetAttr: for a tag which can't be edited, and for either name which isn't an XML name, has an unbound prefix, is a namespace declaration (xmlns or xmlns:*, which can't be renamed) or isn't the name HTML parsers give the attribute. Like SetAttr, it doesn't check the attributes which change how the document is parsed or converted (renaming to or from type on input, encoding on annotation-xml, charset, http-equiv and content on meta, and type and language on script changes the document for HTML parsers, or how the conversion converts it; see SetAttr), prefixed names, attributes which are the same for XML parsers, or the attributes of formatting elements (see SetAttr).
Example ¶
RenameAttr renames an attribute in place, keeping its value: here, the data-src attribute of lazily loaded images replaces their placeholder src.
package main
import (
"os"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<p><img src="blank.gif" data-src="a.png" alt="A"> <img src="b.png" alt="B"></p>`
err := polyglot.Convert(os.Stdout, strings.NewReader(page), polyglot.Options{
DoctypeMode: polyglot.NoDoctype,
OnTag: func(e *polyglot.Tag) {
if e.Start && e.NS == htmlstream.NamespaceXHTML && e.Name == "img" {
e.RenameAttr("data-src", "src")
}
},
})
if err != nil {
panic(err)
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /></head><body><p><img src="a.png" alt="A" /> <img src="b.png" alt="B" /></p></body></html>
func (*Tag) SetAttr ¶
SetAttr adds the attribute name to the start tag with the value, or replaces the value of an attribute already written. On HTML elements, lang and xml:lang are set together, to the same value, like for attributes of the input. The value is escaped like a value of the input.
It fails the conversion for an end tag, a reopened element (edit the first start tag, which the reopened copies repeat) and the charset meta element, for a name which isn't an XML name, has an unbound prefix (see Declare) or is xmlns or xmlns:* (the default namespace is written by the conversion, see Convert, and prefixes are declared with Declare), and for a value with characters not allowed in XML.
The name must be the one HTML parsers give the attribute: lowercase on HTML elements, and with the case adjustments of SVG and MathML attributes (htmlstream.AdjustSVGAttrName, htmlstream.AdjustMathMLAttrName) on those; otherwise HTML and XML parsers would give the attribute different names, and SetAttr fails the conversion. Attributes which change how the document is parsed or converted aren't checked, and must not be changed: type on input (hidden inputs stay in table content, other inputs are moved before the table), encoding on annotation-xml (an integration point for text/html and application/xhtml+xml), charset on meta, and http-equiv and content on a meta whose http-equiv is Content-Type (these encoding declarations are removed, and the encoding is declared by the meta element the conversion adds), and type and language on script (the CDATA wrapper and JSON escaping of the contents are chosen from the type in the input). Other attributes don't affect the document structure, except on formatting elements (see below).
Prefixed names other than xml:lang on HTML elements (e.g., xml:space or epub:type) aren't checked either: HTML parsers put these attributes in no namespace, and XML parsers in the namespace of the prefix, which gives a warning for such attributes of the input (see Convert). The prefix must be bound where the tag is (see LookupPrefix): by a declaration of the input on the element or an enclosing one, or by Declare on this tag (before SetAttr) or on the tag of an enclosing element. SetAttr doesn't check for another attribute of the tag with the same namespace and local name for XML parsers: with two prefixes bound to the same namespace, x:a and y:a are the same attribute, and XML parsers reject the output.
HTML parsers consider formatting elements (e.g., b) with the same name and attributes identical, and reopen only the last three of them after misnested markup (see Rename), so after attribute edits of formatting elements, the output can nest differently than the edited input would.
func (*Tag) Unwrap ¶
func (e *Tag) Unwrap()
Unwrap leaves out the tag and its end tag, keeping the contents of the element (like leaving out both tags of the input, see Writer). Both tag events are still reported. A formatting element unwrapped isn't reopened after a misnested end tag, and doesn't count toward the identical ones HTML parsers keep to reopen (see Rename), and a leading newline isn't removed from an unwrapped pre, textarea or listing.
It fails the conversion for an end tag, a reopened element, html, head and body (also those of the input), an element the conversion adds (tbody, tr, colgroup, the charset meta element and the elements written for stray end tags), the first child element of a template (HTML parsers parse the template contents like a table, a row, a cell, etc. or like body content depending on it), an svg, math or other foreign element (whose contents are foreign content for HTML parsers because of it), an element in foreign content (an integration point's child, whose start tag declares the XHTML namespace) and an element declaring namespace prefixes, in the input or with Declare (its contents may use them). As for the input, it isn't checked that the contents are parsed the same without the element: e.g., unwrapping the b in <option><b><option> gives <option><option>, where HTML parsers close the first option; unwrapping a table, select, template or p changes how HTML parsers read the contents.
type Text ¶
type Text struct {
// Data is the text as written, before escaping: decoded, without the
// NUL characters Convert drops, and with the other characters not
// allowed in XML replaced. It is valid during the call.
Data []byte
// First is set for the first part of a text node, and Last for the call
// ending it, which has no Data and no Raw.
First, Last bool
// Raw is set for the contents of a script or style element and for
// noscript contents read as raw text written unchanged (see [Writer]):
// the text is written as contents, not as markup (for script and style,
// wrapped in a CDATA section if needed, like the contents would be).
// These contents, noscript contents read as raw text written as escaped
// text, and title and textarea contents read with XML syntax starting
// with a CDATA section (after whitespace, see [Writer]), which aren't
// Raw, are reported in one call. It isn't set on the Last call.
Raw bool
// Token is the input token the text comes from (for the contents
// reported in one call, the last one), or nil when Last.
Token *htmlstream.Token
// ID is the ID of the element the text is in (see [Tag.ID]): the
// innermost element open in the output, also when it was unwrapped
// ([Tag.Unwrap]). Depth is the number of elements open in the output
// around the text, one more than the Depth of that element. Both are the
// same for all parts of a text node.
ID, Depth int
// contains filtered or unexported fields
}
Text describes text about to be written, for Options.OnText. A text node in the output (text between two tags or comments, which may come from several input tokens, including text around dropped elements) is reported in parts, in order: the first part has First set, and after the last part, a call with Last set and no Data is made before the markup following the text, or at Close. Elements the conversion adds between parts of the input text (reopened formatting elements) end the text node like other tags, and so do removed elements (see Tag.Remove). Whitespace held back (see Options.Warn) is reported when it is written, so the whitespace between the head end tag and the body is reported after the tag events of the head content after it, and the whitespace at the start of the head after the head start tag event, before or after the event of the charset meta element (see Convert). The comments after the body and html end tags aren't written in the body, so the whitespace around them is one text node. With Options.Indent, whitespace replaced by the indentation isn't reported (see there).
The event is owned by the writer and valid during the call, like Tag. Its fields are for reading, like those of Tag, and the bytes of Data must not be modified: its methods change what is written for the part; without them, the text is written unchanged (escaped, or as contents when Raw). Called in a way they don't allow, they make the conversion fail, like the methods of Tag.
Example ¶
The Text hook replaces text as it is written. SetText escapes the new text, like the text of the input.
package main
import (
"os"
"strings"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<p>It's "fish" & chips.</p><script>if (a < b) alert("x")</script>`
err := polyglot.Convert(os.Stdout, strings.NewReader(page), polyglot.Options{
DoctypeMode: polyglot.NoDoctype,
OnText: func(t *polyglot.Text) {
if t.Raw || t.Last {
return // leave script contents alone
}
s := strings.NewReplacer("'", "\u2019", ` "`, " \u201c", `"`, "\u201d").Replace(string(t.Data))
t.SetText([]byte(s))
},
})
if err != nil {
panic(err)
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /></head><body><p>It’s “fish” & chips.</p><script>//<![CDATA[ if (a < b) alert("x") //]]></script></body></html>
func (*Text) SetMarkup ¶
SetMarkup writes raw, markup, instead of the text (nothing, if raw is empty). For the Last call, it is written at the end of the text node. See Tag for the rules inserted markup follows. It fails the conversion for Raw text, which is written as contents.
Example ¶
SetMarkup replaces text with markup, here with the text around it escaped with AppendEscapeText. Text nodes are reported in parts, so a word split across two parts isn't matched.
package main
import (
"bytes"
"os"
"strings"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<p>Fish & chips are <b>tasty</b>.</p><script>chips()</script>`
err := polyglot.Convert(os.Stdout, strings.NewReader(page), polyglot.Options{
DoctypeMode: polyglot.NoDoctype,
OnText: func(t *polyglot.Text) {
if t.Raw || t.Last {
return
}
var b []byte
for i, word := range bytes.Split(t.Data, []byte("chips")) {
if i != 0 {
b = append(b, "<mark>chips</mark>"...)
}
b = polyglot.AppendEscapeText(b, word)
}
t.SetMarkup(b)
},
})
if err != nil {
panic(err)
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /></head><body><p>Fish & <mark>chips</mark> are <b>tasty</b>.</p><script>chips()</script></body></html>
func (*Text) SetText ¶
SetText writes data instead of the text, escaped like the text would be (for Raw, as the new contents of the element, wrapped in a CDATA section if needed; the contents of script and style must not have the end tag of the element in them, nor end with an incomplete one (e.g., </script), and those of script must not contain <!--<script without a later -->, after which HTML parsers ignore the end tag). For the Last call, data is written at the end of the text node like a part (escaped, also after Raw contents). The data must have only characters allowed in XML (see htmlstream.AppendXMLChars), and must not start with a newline at the start of the contents of pre, listing or textarea (see Tag).
Noscript contents read as raw text containing <, & or ]]> are written escaped, without the warning given for such contents of the input: XML parsers and HTML parsers with scripting disabled read them as text, and HTML parsers with scripting enabled read the escapes (e.g., <) as they are.
Script and style contents are written like the contents of the input (see Well-formedness in the package documentation), without the warnings for such contents of the input, and without the error of Options.Strict: "]]>" in JavaScript and CSS is written as "]]]]><![CDATA[>" in the CDATA section, which HTML parsers read as it is, and the contents of scripts of types other than JavaScript and JSON are written as they are: if they contain <, & or ]]>, keeping the output well-formed is up to the caller. A CDATA wrapper in data (e.g., //<![CDATA[ ... //]]>) isn't removed like that of the contents of the input, whose Data is without it: it is written as part of the contents. The whitespace around the wrapper of the input is written around the new contents.
type Warning ¶
type Warning struct {
// Pos is the position of the input token the warning is about (for
// text, comments and CDATA sections split into multiple tokens, see
// [htmlstream.Token.Partial], the position of the first one), so it
// doesn't depend on the Reader's chunk size.
Pos htmlstream.Pos
// Msg describes the input and how it is converted.
Msg string
}
Warning describes input which can't be represented exactly as polyglot markup, for Options.Warn.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer converts a document to polyglot markup like Convert, one token at a time: the caller reads the document with its own htmlstream.Reader, with the options it needs (e.g., htmlstream.Reader.SetXMLSyntax, which the Reader of Convert takes from Options.XMLSyntax; Options.NewReader returns a Reader set up like Convert's), and passes the tokens to WriteToken, leaving out those it wants removed. Warnings have the positions of the tokens in the caller's input.
The tokens must be from one Reader in htmlstream.HTML mode, in order. Tokens read in htmlstream.Universal mode aren't accepted, also in the documents it reads like in HTML mode with XML syntax, since it reads the processing instructions and doctypes after an XML declaration like XML mode. The tokens left out must keep the stream nested like the Reader's: an element's start tag and end tag (explicit or implied) are both written or both left out, and the parts of text, comments and other tokens split into multiple tokens (see htmlstream.Token.Partial) are all written or all left out. Leaving out an element's start and end tags keeps its contents (like htmlstream.Transformer.Unwrap), and leaving out all of its tokens removes it. The tags of an element which sets the rules for its contents (svg and math, and the integration points in them, like foreignObject) can only be left out with the contents. WriteToken and Close return an error wrapping ErrInvalidOp for tokens breaking these rules: a token out of order or written twice, an end tag whose start tag was left out, a start tag whose end tag was left out (found at the end tag of the enclosing element, or at Close), a token continuing one left out or not continued, an element in SVG or MathML content whose root element was left out, an HTML element in foreign content whose integration point was left out, and a token not read in HTML mode. Other edits of the input (renames, attribute edits, inserted markup) aren't supported, since they would need the Reader's rules applied again (e.g., renaming a span containing a div to p would write <p><div>, which HTML parsers restructure); attribute edits, renames (restricted to elements HTML parsers handle the same way), removals and inserted markup are done on the output, through the hooks (see below).
Implied end tags are converted with the token after them, and the elements closed by implied end tags before a body or html end tag, or an end tag HTML parsers ignore, are closed after the whitespace and comments after the end tag (see Convert): the hooks are called, the output written and the errors for the tokens returned when they are converted. The comments after body and html end tags are written by Close.
When the conversion fails (see Writer.Err), the output is incomplete: the destination has the output written before the error, which can end anywhere (e.g., in a tag), and Close doesn't flush the rest.
The conversion relies on the Reader's element model for the tokens it is given: the structure written is the Reader's, without the start and end tags left out, and the warnings about HTML parsing differences are for that structure. Removing an element with its contents keeps the structure of the rest consistent, and the warnings take the elements left out into account (e.g., a tr whose table was left out is reported as outside a table). Leaving out only the tags of an element is consistent when its contents are parsed the same without it, which isn't checked beyond the namespace rules above: e.g., leaving out the b in <option><b><option> gives <option><option>, where HTML parsers close the first option and the Reader's structure has the second one inside it.
With scripting enabled in the Reader (htmlstream.Reader.SetScripting), noscript contents are raw text, which is written unchanged if it has no <, & or ]]>, so that HTML parsers with scripting disabled and XML parsers read it the same, and otherwise as escaped text, with a warning. Like script and style contents, it is buffered until the end tag to decide this (see Options.MaxRawText).
With XML syntax (htmlstream.Reader.SetXMLSyntax), self-closing tags of non-void HTML elements are written as empty elements, a void element followed by its end tag (e.g., <br></br>, also with whitespace in between) as one element, and other end tags of void elements (e.g., after a comment) as HTML parsers read them, with a warning, CDATA sections in HTML content as text (with a warning for one reaching the end of the input, whose text is the rest of the input, while HTML parsers end it at the first >), and processing instructions (which the Reader ends at the first >, like HTML parsers end a bogus comment) as comments: the current HTML Standard reads most processing instructions (<?target data>) as processing instructions, while polyglot writes them as comments, which all HTML parsers (older ones too) and XML parsers read the same. A first doctype with an internal subset is read to the end of the subset, past a > in it, where HTML parsers end the doctype, and the declarations in it aren't applied, with a warning for each. One whose internal subset reaches the end of the input ends at the first > in it, as in HTML parsers, and is unsound (see htmlstream.Token.Unsound): an error with Options.Strict.
The Reader reads the contents of script, style, title and textarea as text with XML syntax too, with the markers of CDATA sections in them: a CDATA section around all of the contents (with only whitespace around it), as XHTML writes it, is removed, leaving its contents, which XML parsers read (see htmlutil.CDATABare; not in scripts of types other than JavaScript and JSON), and other CDATA sections there are kept as text, with a warning. Like script and style contents, title and textarea contents starting with a CDATA section (after whitespace) are buffered until the end tag for this, and the whitespace at the start of other title and textarea contents until the text after it. Outside CDATA sections, character references and comments in JavaScript, JSON and CSS contents, which XML parsers read as markup (e.g., they decode &), are kept as text, as HTML parsers read them, with a warning. A newline directly after a pre, textarea or listing start tag, which XML parsers keep, is removed like HTML parsers remove it, with a warning, also at the start of a CDATA section directly after a pre, textarea or listing start tag. See Convert for which documents need XML syntax.
The output can be edited without parsing it again: Options.OnTag and Options.OnText report the element tags and text nodes as written (the structure HTML parsers give the input, with the elements the conversion adds), and the methods of the events insert markup around the tags, edit attributes, declare namespace prefixes, rename and leave out elements and replace the text (see Tag and Text). Hold, HoldRelease and HoldDiscard hold back the output, so a hook can decide what to write before the held output once it has seen what follows, and Fail makes the conversion fail. The hooks must not call WriteToken or Close.
Options.MaxDepth limits the depth of the output, and the Reader's maximum depth (htmlstream.Reader.SetMaxDepth) that of the input; see Convert for the time a token takes and the size of the output. The Reader's maximum depth must be at least 3, which Options.NewReader ensures: below that, the Reader leaves out the head and body or the elements in them, and HTML and XML parsers read the output differently.
A Writer isn't safe for concurrent use, and converts a single document.
Example ¶
A Writer converts the tokens of the caller's Reader, here set up like the Reader of Convert by Options.NewReader. Leaving out all the tokens of an element removes it, and leaving out its start and end tags keeps the contents.
package main
import (
"os"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<p>Text<script>track()</script> with <font color=red>red</font> and <span>spans<span>.`
opt := polyglot.Options{DoctypeMode: polyglot.NoDoctype}
r := opt.NewReader(strings.NewReader(page))
pw := polyglot.NewWriter(os.Stdout, opt)
var unwrapped htmlutil.Stack[struct{}]
for r.Next() {
tok := r.Token()
switch tok.Kind() {
case htmlstream.StartTag:
if tok.Is("script") {
r.Skip()
continue
}
if tok.Is("font") || tok.Is("span") {
unwrapped.Push(tok, struct{}{})
continue
}
case htmlstream.EndTag:
if _, ok := unwrapped.Pop(tok); ok {
continue
}
}
if err := pw.WriteToken(tok); err != nil {
panic(err)
}
}
if err := r.Err(); err != nil {
panic(err)
}
if err := pw.Close(); err != nil {
panic(err)
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /></head><body><p>Text with red and spans.</p></body></html>
func (*Writer) Close ¶
Close ends the document: it writes the end tags of the elements still open (and the elements HTML parsers create at the end, like the body) and flushes the output. It returns an error if an element's start tag was written without its end tag, or the last token continues in a token which wasn't written. On error (also before Close), it returns the error without flushing the output, which is incomplete (see Writer). Calling Close again returns the same result, and methods called after Close (event methods, Fail, and WriteToken, which returns its own error) don't change the output or the result.
func (*Writer) Err ¶
Err returns the error which failed the conversion so far, the one WriteToken and Close return, or nil; after Close, the result of Close. Hooks can use it to stop early after an event method failed the conversion.
func (*Writer) Fail ¶
Fail makes the conversion fail with err, for errors of the hooks or of the caller. If the conversion has already failed (see Writer.Err), Fail does nothing and that error is kept, and a nil err does nothing. Otherwise, err is sticky: it is returned by WriteToken and Close (and by the current one, if called from a hook), and Close then writes nothing more. To end the document after an error of the caller, don't give that error to Fail.
Example ¶
A function converting the tokens of its own Reader can give the Reader's error and its own to Fail in a deferred function before Close, so that it returns the first error, and the Writer writes nothing more after an error.
package main
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"testing/iotest"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/polyglot"
)
// convertArticle converts an HTML article to polyglot markup, rejecting
// articles with forms.
func convertArticle(w io.Writer, r io.Reader) (err error) {
opt := polyglot.Options{DoctypeMode: polyglot.NoDoctype}
rd := opt.NewReader(r)
pw := polyglot.NewWriter(w, opt)
defer func() {
pw.Fail(rd.Err()) // a read error comes first
pw.Fail(err) // leave this out to write the rest of the document after our own error
if cerr := pw.Close(); cerr != nil {
err = cerr
}
}()
for rd.Next() {
tok := rd.Token()
if tok.Kind() == htmlstream.StartTag && tok.Is("form") {
return fmt.Errorf("form at offset %d", tok.Pos())
}
if err := pw.WriteToken(tok); err != nil {
return err
}
}
return nil // the deferred Close ends the document and reports the errors
}
// A function converting the tokens of its own Reader can give the Reader's
// error and its own to Fail in a deferred function before Close, so that it
// returns the first error, and the Writer writes nothing more after an error.
func main() {
const page = `<p>Some <b>bold</b> text<p>More text`
for _, r := range []io.Reader{
strings.NewReader(page),
strings.NewReader(page + `<form action=/x>`),
io.MultiReader(strings.NewReader(page[:20]), iotest.ErrReader(errors.New("connection reset"))),
} {
var b bytes.Buffer
if err := convertArticle(&b, r); err != nil {
fmt.Printf("error: %v (wrote %d bytes)\n", err, b.Len())
continue
}
fmt.Println(b.String())
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /></head><body><p>Some <b>bold</b> text</p><p>More text</p></body></html> error: form at offset 36 (wrote 0 bytes) error: connection reset (wrote 0 bytes)
func (*Writer) Held ¶
Held returns the output held back by the hold h so far, including that of the holds inside it, or nil if h isn't open. It is valid until the next write or until a hold ends.
func (*Writer) Hold ¶
Hold starts holding back the output, like htmlstream.Transformer.Hold: the output from here on is written to a buffer until the hold ends with Writer.HoldRelease or Writer.HoldDiscard. The output held back is limited to Options.MaxHold; to give up on a hold at a smaller size, end it when Writer.Held gets too long. Called from Options.OnTag, the hold starts after the tag and the markup inserted after it; called from Options.OnText, it starts with the text (or its replacement). Holds started for the charset meta element start after the markup inserted after the head start tag, like those started for the head start tag. A hold started in a Tag hook can end in the same hook: HoldRelease holds back nothing, and HoldDiscard writes raw after the tag and the markup inserted after it. Holds still open at Close are released. The comments after body and html end tags are written by Close (see Convert), so holds ending before it don't contain them.
A hold started while another is open is inside it, and must end first: its output then stays in the enclosing hold. HoldRelease and HoldDiscard of a hold with an open hold inside it fail with an error wrapping ErrInvalidOp, and so do those of the zero Hold and of a hold of another Writer. Those of a hold which has ended return htmlstream.ErrHoldReleased, after which the conversion continues.
After an error, and once Close has returned, Hold returns the zero Hold. The errors of HoldRelease and HoldDiscard other than ErrHoldReleased are sticky, and also returned by WriteToken and Close, so a hook calling them doesn't need to report them.
Example ¶
Hold holds back the output, here to insert a table of contents built from the headings at the start of the body.
package main
import (
"os"
"strconv"
"strings"
"github.com/pgaskin/htmlstream/polyglot"
)
func main() {
const page = `<h1>Fish</h1><p>Intro.<h2>Cod</h2><p>White.<h2>Salmon & trout</h2><p>Pink.`
var toc, heading []byte
var body polyglot.Hold
inHeading := false
n := 0
err := polyglot.Convert(os.Stdout, strings.NewReader(page), polyglot.Options{
DoctypeMode: polyglot.NoDoctype,
OnTag: func(e *polyglot.Tag) {
pw := e.Writer()
switch {
case e.Name == "body" && e.Start:
body = pw.Hold()
toc = append(toc, "<ul>"...)
case e.Name == "body":
toc = append(toc, "</ul>"...)
pw.Fail(pw.HoldDiscard(body, append(toc, pw.Held(body)...)))
case e.Name == "h2" && e.Start:
n++
e.SetAttr("id", "s"+strconv.Itoa(n))
inHeading = true
heading = heading[:0]
case e.Name == "h2":
inHeading = false
toc = append(toc, `<li><a href="#s`+strconv.Itoa(n)+`">`...)
toc = polyglot.AppendEscapeText(toc, heading)
toc = append(toc, "</a></li>"...)
}
},
OnText: func(t *polyglot.Text) {
if inHeading {
heading = append(heading, t.Data...)
}
},
})
if err != nil {
panic(err)
}
}
Output: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="UTF-8" /></head><body><ul><li><a href="#s1">Cod</a></li><li><a href="#s2">Salmon & trout</a></li></ul><h1>Fish</h1><p>Intro.</p><h2 id="s1">Cod</h2><p>White.</p><h2 id="s2">Salmon & trout</h2><p>Pink.</p></body></html>
func (*Writer) HoldDiscard ¶
HoldDiscard ends the hold h, writing raw (which may be nil) instead of the output held back. Markup is inserted before the held output with HoldDiscard(h, append(markup, pw.Held(h)...)). If a hold encloses h, raw is held back in it, and counts toward Options.MaxHold. See Writer.Hold for the errors.
func (*Writer) HoldRelease ¶
HoldRelease ends the hold h, writing the output held back (or keeping it in the enclosing hold). See Writer.Hold for the errors.
func (*Writer) WriteToken ¶
func (pw *Writer) WriteToken(tok *htmlstream.Token) error
WriteToken converts the next token (see Writer for the tokens which can be left out). Errors are sticky, including an error of the io.Writer: the output is buffered, so WriteToken returns a write error once the buffered output is written, after up to 4 KiB more output, or Close returns it.
type XMLDeclMode ¶
type XMLDeclMode uint8
XMLDeclMode selects the XML declaration written by Convert and Writer.
The output doesn't need an XML declaration: XML parsers read a document without one as XML 1.0 in UTF-8 (see character encoding in entities), which the output is. HTML parsers read a declaration as a comment (a parse error), so the documents HTML and XML parsers build differ by that comment, and the W3C polyglot markup note forbids it (see Convert). A declaration only matters when the output is read without a media type (e.g., served without a Content-Type header): MIME sniffing then identifies a resource starting with "<?xml" as XML, and one starting with a doctype or an html tag as HTML. With a media type, the document is read as that, whatever the declaration says (see Serving in the package documentation). KeepXMLDecl writes one only if the input has one.
const ( // NoXMLDecl writes no XML declaration. NoXMLDecl XMLDeclMode = iota // AddXMLDecl writes <?xml version="1.0" encoding="UTF-8"?> at the start // of the document. AddXMLDecl // KeepXMLDecl writes the XML declaration of [AddXMLDecl] if the input has // one before the root element (HTML parsers read it as a bogus comment, // which may follow other comments and the doctype). The output before the // root element (comments and the doctype) is held back until the root // element starts, up to [Options.MaxRawText]; an XML declaration after // more output than that is removed with a warning. KeepXMLDecl )