NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI
A fast, fully typed HTML toolkit for Python, powered by a C-accelerated core.
Latest stable
1.15.11
Last release 9 days ago
16 Nov 2026
Ships fairly regularly
a new release about every 2 weeks
Nearly every release is documented
notes for 37 of 37 stable releases
Nothing withdrawn
no release was ever pulled
5 months old
37 releases · first in 2026
Drag across the ruler to compare, or tap a release to open it.
Add Markdown.Escaping(mode="none"), which leaves prose as written in to_markdown apart from the asterisks and underscores choices and a | inside a tab
<a name="release-1-11-0-added"></a>
Markdown.Escaping(mode="none"), which leaves prose as written in to_markdown apart from the asterisks and underscores choices and a | inside a table cell. (#874) by @gaborbernat.Element.tag renames the element in place, keeping its namespace, attributes, children and position. (#883) by @gaborbernat.attribute_policy for retaining bleach attribute rules with native CSS settings. Preserve callable precedence, source values before safety checks, and changes to rule mappings. Treat * as an attribute name. (#895) by @gaborbernat.Policy.attribute_predicate to inspect attributes before allowlist and safety checks. (#901) by @gaborbernat.<a name="release-1-11-0-fixed"></a>
to_markdown keeps a list's content that is not an <li>: text or a block before the first item renders on its own, one after an item continues it, and items wrapped in another element keep their markers. (#864) by @gaborbernat.to_markdown keeps a table's <caption>, rendering it as a paragraph above the pipe table and the stripped table text. (#865) by @gaborbernat.to_markdown ends each pipe-table row at its closing | with no trailing space, and a cell that holds a block no longer starts with two spaces. (#866) by @gaborbernat.to_markdown keeps two adjacent lists of the same kind apart: the second switches its bullet or ordered delimiter, since CommonMark joins items that share one into a single list. (#867) by @gaborbernat.to_markdown keeps whitespace at the edges of a link or a converted inline element outside its output, so x<a href="h"> t </a>y renders x [t](h) y where the leading space used to vanish. (#868) by @gaborbernat.id() evaluated on a node outside any document, such as an element built with Element(...) or held by a DocumentFragment, now starts at the root of that node's tree instead of crashing the interpreter. (#876) by @gaborbernat.hash() on a node no longer slows down as its tree takes in nodes from other trees: the hashes those nodes carried over now sit in a hash table instead of a list scanned on every call. (#878) by @gaborbernat.node[-len(node) - 1] raises IndexError again instead of returning a child. (#879) by @gaborbernat.< or a control character the parser keeps from markup; only ASCII whitespace, U+0000, /, = and > are rejected. (#881) by @gaborbernat..//div//a, no longer runs in quadratic time when its context nodes nest inside one another. (#885) by @gaborbernat.PATH. This prevents ARM64 builds from selecting an x64 compiler and failing to link Python. (#888) by @gaborbernat.kbd and samp as Markdown code spans with safe backtick fences. Omit empty inline code spans. (#896) by @gaborbernat.re:test() and matches() predicates by reusing compiled regular expressions. (#897) by @gaborbernat.checked state. (#905) by @gaborbernat.attrs mapping during find() or find_all(). (#910) by @gaborbernat.Your coding agent can read these notes before it upgrades. Set up the MCP server →
One column per month.
Add Markdown.Escaping(mode="none"), which leaves prose as written in ~turbohtml.Node.to_markdown apart from the asterisks and underscores choices and a | inside a table cell. (874) by gaborbernat.
Assigning Element.tag renames the element in place, keeping its namespace, attributes, children and position. (883) by gaborbernat.
Add turbohtml.migration.bleach.attribute_policy for retaining bleach attribute rules with native CSS settings. Preserve callable precedence, source values before safety checks, and changes to rule mappings. Treat * as an attribute name. (895) by gaborbernat.
Add Policy.attribute_predicate to inspect attributes before allowlist and safety checks. (901) by gaborbernat.
~turbohtml.Node.to_markdown keeps a list's content that is not an <li>: text or a block before the first item renders on its own, one after an item continues it, and items wrapped in another element keep their markers. (864) by gaborbernat.
~turbohtml.Node.to_markdown keeps a table's <caption>, rendering it as a paragraph above the pipe table and the stripped table text. (865) by gaborbernat.
~turbohtml.Node.to_markdown ends each pipe-table row at its closing | with no trailing space, and a cell that holds a block no longer starts with two spaces. (866) by gaborbernat.
~turbohtml.Node.to_markdown keeps two adjacent lists of the same kind apart: the second switches its bullet or ordered delimiter, since CommonMark joins items that share one into a single list. (867) by gaborbernat.
~turbohtml.Node.to_markdown keeps whitespace at the edges of a link or a converted inline element outside its output, so x<a href="h"> t </a>y renders x [t](h) y where the leading space used to vanish. (868) by gaborbernat.
An absolute XPath or id() evaluated on a node outside any document, such as an element built with Element(...) or held by a DocumentFragment, now starts at the root of that node's tree instead of crashing the interpreter. (876) by gaborbernat.
hash() on a node no longer slows down as its tree takes in nodes from other trees: the hashes those nodes carried over now sit in a hash table instead of a list scanned on every call. (878) by gaborbernat.
Negative child indexes on PyPy 8.0 no longer get the sequence length added twice, so node[-len(node) - 1] raises IndexError again instead of returning a child. (879) by gaborbernat.
Setting an attribute accepts every name the DOM Standard allows, including a quote, < or a control character the parser keeps from markup; only ASCII whitespace, U+0000, /, = and > are rejected. (881) by gaborbernat.
An XPath descendant step without a predicate, such as the second step of .//div//a, no longer runs in quadratic time when its context nodes nest inside one another. (885) by gaborbernat.
Moving a subtree between trees preserves references to its descendants and their attribute views. Aliases of the moved node retain their identity and hashes. (887) by gaborbernat.
Source installs on Windows activate MSVC even when MinGW is on PATH. This prevents ARM64 builds from selecting an x64 compiler and failing to link Python. (888) by gaborbernat.
Predicate-free XPath descendant steps skip nested contexts during traversal. Deep trees no longer require a separate ancestor walk for each context. (890) by gaborbernat.
Reduce Markdown conversion overhead by inlining child dispatch and skipping converter calls without configured converters. (893) by gaborbernat.
Render kbd and samp as Markdown code spans with safe backtick fences. Omit empty inline code spans. (896) by gaborbernat.
Speed up XPath re:test() and matches() predicates by reusing compiled regular expressions. (897) by gaborbernat.
Reuse parent styles and CSS sibling positions across computed-style calls and reverse traversal. (898) by gaborbernat.
Reject unmatched brackets in URL authorities during sanitization, including rewritten and forced attributes. Preserve bracketed hostnames and brackets outside the authority. (899) by gaborbernat.
Keep cloned element attributes independent during DOM edits and sanitization. (900) by gaborbernat.
Fix XSLT transforms of standalone and detached nodes, including document fragments. Keep source trees alive across callbacks. (902) by gaborbernat.
Reuse compiled stylesheet text to reduce XSLT allocations. (904) by gaborbernat.
Honor form ownership and tree boundaries when setting a radio input's checked state. (905) by gaborbernat.
Reduce query ordering costs for large sets of sibling roots. (906) by gaborbernat.
Reduce parent query costs for nodes without siblings. (907) by gaborbernat.
Avoid repeated attribute-name length calculations during XSLT execution. (908) by gaborbernat.
Retain attribute predicates when callbacks clear the attrs mapping during find() or find_all(). (910) by gaborbernat.
Count default XSLT numbers by expanded name and processing-instruction target. (911) by gaborbernat.
Add DocumentFragment: Range.extract_contents and Range.clone_contents return one, and every insertion method moves a fragment's children into place an
<a name="release-1-10-0-added"></a>
DocumentFragment: Range.extract_contents and Range.clone_contents return one, and every insertion method moves a fragment's children into place and leaves it empty, as the DOM insert algorithm does. (#857) by @gaborbernat.<a name="release-1-10-0-fixed"></a>
sanitize escape mode from rendering a start tag the source never wrote: the tbody a bare <table><tr> implies, a formatting element the parser clones, or the skeleton of an empty document. (#807) by @gaborbernat.build when sanitize_node escapes it, so <span>x</span>y no longer escapes as <span>xy. (#808) by @gaborbernat.title, p, div) with CSS selectors on a parse_xml tree, so select("title") from the document and combinators such as p > x find them. (#809) by @gaborbernat.IncrementalParser with source_locations=True reports the same absolute offsets as parse when a tag spans two feeds, and to_source() on its document no longer reads freed memory. (#810) by @gaborbernat.sanitize from leaving a kept HTML element such as <style> directly under <svg> or <math> when it escapes the desc, title, foreignObject, or MathML text element that held it. (#811) by @gaborbernat.Tokenizer with capture_source=True reports the full source of a tag split across two feed() calls, where it used to truncate it or raise ValueError. (#812) by @gaborbernat.minify_css keeps the zero units the flex shorthand needs: flex:0px and flex:1 1 0px no longer change grow or basis, and flex-basis:0% no longer becomes flex-basis:0. (#813) by @gaborbernat.minify_css keeps zero units inside round(), abs(), hypot(), mod(), rem() and the other CSS Values 4 math functions, where round(0px,1px) used to become the invalid round(0,1px). (#814) by @gaborbernat.sanitize keep HTML content under MathML annotation-xml only while the output still carries an encoding of text/html or application/xhtml+xml. (#815) by @gaborbernat.IncrementalParser honors a byte-order mark at the start of bytes input: the mark picks the encoding over the encoding argument and is stripped, as parse does. (#816) by @gaborbernat.sanitize from keeping an HTML mglyph or malignmark under a MathML mi, mo, mn, ms, or mtext, where a reparse turns it and its children into MathML. (#817) by @gaborbernat.colgroup fragment or a template holding a <col> keeps the whitespace that follows ignored text, so parse_fragment("a b\nc", "colgroup") yields " \n" instead of an empty fragment. (#818) by @gaborbernat.Range operations raise IndexError or ValueError when a tree edit left a boundary past the end of its text, in another tree, or after the end, instead of reading out of bounds or crashing. (#819) by @gaborbernat.node.wrap(node) raises ValueError instead of making the node its own parent and looping. (#820) by @gaborbernat.parse_fragment keeps the SVG mixed case on its root, so an "svg foreignObject" context returns a foreignObject element instead of foreignobject. (#821) by @gaborbernat.sanitize_node and transform_tags scrub every text run of a kept <style>, drop its element children, and escape a </style in its body so the stylesheet cannot close the element early. (#822) by @gaborbernat.ValueError instead of creating a cycle that made assigned_nodes(flatten=True) loop forever. (#823) by @gaborbernat.sanitize and the bleach clean shim drop javascript: URLs even when url_schemes or protocols lists javascript, as the safety baseline documents. (#824) by @gaborbernat.minify_js keeps (0,o.f)(), (1&&o.f)() and similar value callees, tags and delete/typeof operands as (0,o.f) instead of unwrapping them to o.f, which changed this, deleted properties and turned indirect eval direct. (#825) by @gaborbernat.strip_template_markers in sanitize catch a marker whose halves end up adjacent once a comment or disallowed element between them is removed, stripped, or escaped, and markers inside an escaped tag. (#826) by @gaborbernat.linkify leave the text of xmp, iframe, noembed, noframes, plaintext, textarea, title, and scripting-parsed noscript untouched instead of dropping or nesting link text there. (#827) by @gaborbernat.sanitize from appending another ;} on every pass to a <style> body that ends inside an unterminated string or comment; the trailing declaration is now dropped. (#828) by @gaborbernat.minify_js keeps a function declared in a block, and the binding its name reaches outside the block, when mangling: Annex B makes the function visible after the block, so dropping or inlining it broke typeof g and calls there. (#829) by @gaborbernat.minify_js keeps assignments to parameters in functions that read arguments, which mirrors each parameter in sloppy code; function(a){a=2;return arguments[0]} used to lose the a=2. (#830) by @gaborbernat.minify_js accepts a raw U+2028 LINE SEPARATOR or U+2029 PARAGRAPH SEPARATOR inside a string literal, legal since ES2019, instead of raising a lexical error. (#831) by @gaborbernat.wrap, wrap_siblings, insert_before, insert_after, replace_with, unwrap and Range.insert_node no longer corrupt the tree or crash on the free-threaded build when another thread edits it while a node moves in from another tree. (#832) by @gaborbernat.minify_js and the HTML minifier read <!-- and a line-leading --> as line comments in classic scripts, as Annex B requires; <script type=module> keeps them as operators. (#833) by @gaborbernat.Element and E keep the first of several attribute keys that differ only in ASCII case, matching the parser, instead of storing the attribute twice. (#834) by @gaborbernat.Range.surround_contents raises ValueError for a wrapper that is not an element, such as a Text node, instead of silently dropping the range contents. (#835) by @gaborbernat.minify_js output is a fixed point again when a binding named undefined exists: reads that reach the global undefined fold to void 0 on the first pass instead of the second. (#836) by @gaborbernat.NodeIterator follows the DOM pre-remove steps: removing an ancestor of its current node, even from inside the filter, moves the iterator out of the removed subtree so iteration continues with the remaining nodes. (#837) by @gaborbernat.//@n[. > 5] compares the attribute value and //@n/.. returns the owner element. (#838) by @gaborbernat.turbohtml.extract.feed() as XML, so CDATA summaries and content keep their markup, a channel <image> no longer overrides the feed title and link, and parse_xml(...).feed() reads RSS <link> text. (#839) by @gaborbernat.Element.attrs implements the full MutableMapping interface: update, pop, popitem, setdefault, clear, copy, equality with any mapping, and | / |=. (#840) by @gaborbernat.//foreignObject finds the SVG element and //foreignobject no longer does. (#841) by @gaborbernat.to_markdown() escapes text a CommonMark reader would parse as markup: list-item line starts such as 1., ~, < and & before markup, a heading's trailing #, and unbalanced parentheses in link destinations. (#842) by @gaborbernat.parse_xml and HTML trees take the destination tree's naming and raw-text rules, and set_inner_html / insert_adjacent_html on an XML element use the XML fragment parser. (#843) by @gaborbernat.Element.form_data() (newlines stripped, url/email trimmed, invalid number and date values emptied, range clamped), normalize textarea line breaks, and skip controls inside <datalist>. (#844) by @gaborbernat.rowspan at the end of its <thead>/<tbody>/<tfoot> in Element.rows(), records(), and Node.tables(), and return <tfoot> rows last, as the WHATWG table model does. (#845) by @gaborbernat.Node.xpath(), xpath_one(), xpath_iter(), and XPath.__call__ with the full result union: numbers, booleans, and strings from scalar expressions, and any node kind in a node-set. (#846) by @gaborbernat.itemprop attribute repeats a name, as in itemprop="a a". (#847) by @gaborbernat.NaN, Infinity, or -Infinity literals in Document.json_ld(), as the docs promise for invalid JSON, instead of returning nan or inf. (#848) by @gaborbernat.round() no longer rounds up the largest doubles below a half or integers past 2^52, and returns negative zero for arguments in [-0.5, 0); substring() positions round the same way. (#849) by @gaborbernat.Document, fragment, or ShadowRoot rebuilds its structure instead of reparsing serialized markup: doctype identifiers, quirks mode, adjacent text, template contents, and foreign-element case survive, and elements holding a <template> pickle again. (#850) by @gaborbernat.Html(layout=Indent()) from adding whitespace inside inline content, which changed the rendered text (<p>a<b>b</b>c</p> reparsed as "a b c"); it now breaks lines only between block-level elements. (#851) by @gaborbernat.lang() and CSS :lang() honor xml:lang: an XML tree reads it, and on an HTML tree it overrides lang on SVG and MathML elements. //@xml:lang now matches those attributes. (#852) by @gaborbernat.Range.insert_node raise ValueError instead of putting a doctype outside a Document, or a second doctype, a second root element, or a Text node directly into a Document. (#853) by @gaborbernat.parse_xml tree: [type=checkbox] no longer matches type="CheckBox", since the HTML case-insensitive value list applies to HTML documents only. (#854) by @gaborbernat.</p>, </li> or </dd> of the last child of a phrasing parent such as <span> or <label>, whose end tag does not close it on reparse. (#855) by @gaborbernat.number() convert decimals to the nearest double, so 0.49999999999999994 < 0.5 holds and number(string(x)) round-trips. (#856) by @gaborbernat.ShadowRoot no longer links the fragment node itself into the tree; its children move into place and a shadow root stays attached to its host. (#857) by @gaborbernat.</p> before a <table> in quirks mode, so the output reparses in the same document mode and to the same tree. (#858) by @gaborbernat.</plaintext> and no end tag after a <plaintext> element, which the parser would read back as text, so minifying such a page is idempotent. (#859) by @gaborbernat.Formatter.NAMED_ENTITIES writes ⟨ and ⟩ for U+27E8 and U+27E9, their HTML5 meaning, and keeps U+2329 and U+232A literal, so the output reparses to the same text. (#860) by @gaborbernat.Add DocumentFragment: Range.extract_contents and Range.clone_contents return one, and every insertion method moves a fragment's children into place and leaves it empty, as the DOM insert algorithm does. (857) by gaborbernat.
Stop ~turbohtml.clean.sanitize escape mode from rendering a start tag the source never wrote: the tbody a bare <table><tr> implies, a formatting element the parser clones, or the skeleton of an empty document. (807) by gaborbernat.
Keep the end tag of an element built with turbohtml.build when ~turbohtml.clean.sanitize_node escapes it, so <span>x</span>y no longer escapes as <span>xy. (808) by gaborbernat.
Match elements named like HTML tags (title, p, div) with CSS selectors on a ~turbohtml.parse_xml tree, so select("title") from the document and combinators such as p > x find them. (809) by gaborbernat.
turbohtml.IncrementalParser with source_locations=True reports the same absolute offsets as turbohtml.parse when a tag spans two feeds, and to_source() on its document no longer reads freed memory. (810) by gaborbernat.
Stop ~turbohtml.clean.sanitize from leaving a kept HTML element such as <style> directly under <svg> or <math> when it escapes the desc, title, foreignObject, or MathML text element that held it. (811) by gaborbernat.
turbohtml.Tokenizer with capture_source=True reports the full source of a tag split across two feed() calls, where it used to truncate it or raise ValueError. (812) by gaborbernat.
minify_css keeps the zero units the flex shorthand needs: flex:0px and flex:1 1 0px no longer change grow or basis, and flex-basis:0% no longer becomes flex-basis:0. (813) by gaborbernat.
minify_css keeps zero units inside round(), abs(), hypot(), mod(), rem() and the other CSS Values 4 math functions, where round(0px,1px) used to become the invalid round(0,1px). (814) by gaborbernat.
Make ~turbohtml.clean.sanitize keep HTML content under MathML annotation-xml only while the output still carries an encoding of text/html or application/xhtml+xml. (815) by gaborbernat.
turbohtml.IncrementalParser honors a byte-order mark at the start of bytes input: the mark picks the encoding over the encoding argument and is stripped, as turbohtml.parse does. (816) by gaborbernat.
Stop ~turbohtml.clean.sanitize from keeping an HTML mglyph or malignmark under a MathML mi, mo, mn, ms, or mtext, where a reparse turns it and its children into MathML. (817) by gaborbernat.
A colgroup fragment or a template holding a <col> keeps the whitespace that follows ignored text, so parse_fragment("a b\nc", "colgroup") yields " \n" instead of an empty fragment. (818) by gaborbernat.
Range operations raise IndexError or ValueError when a tree edit left a boundary past the end of its text, in another tree, or after the end, instead of reading out of bounds or crashing. (819) by gaborbernat.
node.wrap(node) raises ValueError instead of making the node its own parent and looping. (820) by gaborbernat.
turbohtml.parse_fragment keeps the SVG mixed case on its root, so an "svg foreignObject" context returns a foreignObject element instead of foreignobject. (821) by gaborbernat.
Make ~turbohtml.clean.sanitize_node and transform_tags scrub every text run of a kept <style>, drop its element children, and escape a </style in its body so the stylesheet cannot close the element early. (822) by gaborbernat.
Appending a shadow host into its own shadow tree raises ValueError instead of creating a cycle that made assigned_nodes(flatten=True) loop forever. (823) by gaborbernat.
Make ~turbohtml.clean.sanitize and the bleach clean shim drop javascript: URLs even when url_schemes or protocols lists javascript, as the safety baseline documents. (824) by gaborbernat.
minify_js keeps (0,o.f)(), (1&&o.f)() and similar value callees, tags and delete/typeof operands as (0,o.f) instead of unwrapping them to o.f, which changed this, deleted properties and turned indirect eval direct. (825) by gaborbernat.
Make strip_template_markers in ~turbohtml.clean.sanitize catch a marker whose halves end up adjacent once a comment or disallowed element between them is removed, stripped, or escaped, and markers inside an escaped tag. (826) by gaborbernat.
Make ~turbohtml.clean.linkify leave the text of xmp, iframe, noembed, noframes, plaintext, textarea, title, and scripting-parsed noscript untouched instead of dropping or nesting link text there. (827) by gaborbernat.
Stop ~turbohtml.clean.sanitize from appending another ;} on every pass to a <style> body that ends inside an unterminated string or comment; the trailing declaration is now dropped. (828) by gaborbernat.
minify_js keeps a function declared in a block, and the binding its name reaches outside the block, when mangling: Annex B makes the function visible after the block, so dropping or inlining it broke typeof g and calls there. (829) by gaborbernat.
minify_js keeps assignments to parameters in functions that read arguments, which mirrors each parameter in sloppy code; function(a){a=2;return arguments[0]} used to lose the a=2. (830) by gaborbernat.
minify_js accepts a raw U+2028 LINE SEPARATOR or U+2029 PARAGRAPH SEPARATOR inside a string literal, legal since ES2019, instead of raising a lexical error. (831) by gaborbernat.
wrap, wrap_siblings, insert_before, insert_after, replace_with, unwrap and Range.insert_node no longer corrupt the tree or crash on the free-threaded build when another thread edits it while a node moves in from another tree. (832) by gaborbernat.
minify_js and the HTML minifier read <!-- and a line-leading --> as line comments in classic scripts, as Annex B requires; <script type=module> keeps them as operators. (833) by gaborbernat.
Element and E keep the first of several attribute keys that differ only in ASCII case, matching the parser, instead of storing the attribute twice. (834) by gaborbernat.
Range.surround_contents raises ValueError for a wrapper that is not an element, such as a Text node, instead of silently dropping the range contents. (835) by gaborbernat.
minify_js output is a fixed point again when a binding named undefined exists: reads that reach the global undefined fold to void 0 on the first pass instead of the second. (836) by gaborbernat.
NodeIterator follows the DOM pre-remove steps: removing an ancestor of its current node, even from inside the filter, moves the iterator out of the removed subtree so iteration continues with the remaining nodes. (837) by gaborbernat.
XPath predicates and steps on an attribute now use the attribute as the context node: //@n[. > 5] compares the attribute value and //@n/.. returns the owner element. (838) by gaborbernat.
Parse well-formed feeds in turbohtml.extract.feed() as XML, so CDATA summaries and content keep their markup, a channel <image> no longer overrides the feed title and link, and parse_xml(...).feed() reads RSS <link> text. (839) by gaborbernat.
Element.attrs implements the full MutableMapping interface: update, pop, popitem, setdefault, clear, copy, equality with any mapping, and | / |=. (840) by gaborbernat.
XPath name tests match SVG and MathML elements by their exact spelling: //foreignObject finds the SVG element and //foreignobject no longer does. (841) by gaborbernat.
to_markdown() escapes text a CommonMark reader would parse as markup: list-item line starts such as 1., ~, < and & before markup, a heading's trailing #, and unbalanced parentheses in link destinations. (842) by gaborbernat.
Nodes adopted between parse_xml and HTML trees take the destination tree's naming and raw-text rules, and set_inner_html / insert_adjacent_html on an XML element use the XML fragment parser. (843) by gaborbernat.
Apply each input type's value sanitization in Element.form_data() (newlines stripped, url/email trimmed, invalid number and date values emptied, range clamped), normalize textarea line breaks, and skip controls inside <datalist>. (844) by gaborbernat.
Stop a rowspan at the end of its <thead>/<tbody>/<tfoot> in Element.rows(), records(), and Node.tables(), and return <tfoot> rows last, as the WHATWG table model does. (845) by gaborbernat.
Type Node.xpath(), xpath_one(), xpath_iter(), and XPath.__call__ with the full result union: numbers, booleans, and strings from scalar expressions, and any node kind in a node-set. (846) by gaborbernat.
List a microdata value once per property name when an itemprop attribute repeats a name, as in itemprop="a a". (847) by gaborbernat.
Skip a JSON-LD block that uses the non-JSON NaN, Infinity, or -Infinity literals in Document.json_ld(), as the docs promise for invalid JSON, instead of returning nan or inf. (848) by gaborbernat.
XPath round() no longer rounds up the largest doubles below a half or integers past 2^52, and returns negative zero for arguments in [-0.5, 0); substring() positions round the same way. (849) by gaborbernat.
Pickling a Document, fragment, or ShadowRoot rebuilds its structure instead of reparsing serialized markup: doctype identifiers, quirks mode, adjacent text, template contents, and foreign-element case survive, and elements holding a <template> pickle again. (850) by gaborbernat.
Stop Html(layout=Indent()) from adding whitespace inside inline content, which changed the rendered text (<p>a<b>b</b>c</p> reparsed as "a b c"); it now breaks lines only between block-level elements. (851) by gaborbernat.
XPath lang() and CSS :lang() honor xml:lang: an XML tree reads it, and on an HTML tree it overrides lang on SVG and MathML elements. //@xml:lang now matches those attributes. (852) by gaborbernat.
Node insertion methods and Range.insert_node raise ValueError instead of putting a doctype outside a Document, or a second doctype, a second root element, or a Text node directly into a Document. (853) by gaborbernat.
Compare attribute values exactly on a ~turbohtml.parse_xml tree: [type=checkbox] no longer matches type="CheckBox", since the HTML case-insensitive value list applies to HTML documents only. (854) by gaborbernat.
Minify keeps the </p>, </li> or </dd> of the last child of a phrasing parent such as <span> or <label>, whose end tag does not close it on reparse. (855) by gaborbernat.
XPath number literals and number() convert decimals to the nearest double, so 0.49999999999999994 < 0.5 holds and number(string(x)) round-trips. (856) by gaborbernat.
Inserting a range's contents or a ShadowRoot no longer links the fragment node itself into the tree; its children move into place and a shadow root stays attached to its host. (857) by gaborbernat.
Minify keeps the doctype's public and system identifiers and a </p> before a <table> in quirks mode, so the output reparses in the same document mode and to the same tree. (858) by gaborbernat.
Minify writes no </plaintext> and no end tag after a <plaintext> element, which the parser would read back as text, so minifying such a page is idempotent. (859) by gaborbernat.
Formatter.NAMED_ENTITIES writes ⟨ and ⟩ for U+27E8 and U+27E9, their HTML5 meaning, and keeps U+2329 and U+232A literal, so the output reparses to the same text. (860) by gaborbernat.
Add native DOM whitespace collapse, comment removal, and ordered transformation composition. Serialize subtree children with inner=True on serialize,
<a name="release-1-9-0-added"></a>
inner=True on serialize, encode, and serialize_iter. (#791) by @gaborbernat.JavaScript minification of long guard-return sequences. (#795) by @gaborbernat.JavaScript minification of declarations with single-use initializers. (#795) by @gaborbernat.:has() selectors on nested elements. (#795) by @gaborbernat.JavaScript minification of libraries containing boolean literals. (#795) by @gaborbernat.canonical serialization with explicit options. (#795) by @gaborbernat.XPath translate() with large character maps. (#795) by @gaborbernat.XSLT numbering with explicit element, wildcard or document-root patterns. (#795) by @gaborbernat.computed-style lookups on an unchanged tree. (#795) by @gaborbernat.XSD validation with inherited simple-type facets. (#795) by @gaborbernat.CSS minification with long conflicting declaration values. (#795) by @gaborbernat.HTML serialization with explicit options. (#795) by @gaborbernat.Unicode normalization tables. (#795) by @gaborbernat.form-data collection from deeply nested disabled fieldsets. (#795) by @gaborbernat.language detection on text with many distinct trigrams. (#795) by @gaborbernat.article extraction from deeply nested content. (#795) by @gaborbernat.XPath equality comparisons between node sets. (#795) by @gaborbernat.XSLT level="any" numbering. (#795) by @gaborbernat.computed-style matching of class-qualified selectors. (#795) by @gaborbernat.XPath inequality comparisons between node sets. (#795) by @gaborbernat.XPath str:replace() with sparse matches of long strings. (#795) by @gaborbernat.Markdown wrapping of long lines. (#795) by @gaborbernat.JavaScript minification of mixed retained and removable declarations. (#795) by @gaborbernat.XSD validation of elements with many instance attributes. (#795) by @gaborbernat.RELAX NG validation of optional groups and interleaves. (#795) by @gaborbernat.microdata extraction when referenced properties are already ordered. (#795) by @gaborbernat.XPath set:intersection() on large node sets. (#795) by @gaborbernat.JavaScript minification that removes declarations from long statement lists. (#795) by @gaborbernat.XPath id() when its argument contains many short nodes. (#795) by @gaborbernat.XPath str:concat() over many short text nodes. (#795) by @gaborbernat.XSLT applications with many template rules. (#795) by @gaborbernat.canonical serialization of deeply nested trees with xlink attributes. (#795) by @gaborbernat.JavaScript literal propagation within large multi-binding declarations. (#795) by @gaborbernat.plain-text serialization with explicit options. (#795) by @gaborbernat.XSLT sibling numbering. (#795) by @gaborbernat.CSS minification with many rules sharing declaration bodies. (#795) by @gaborbernat.table extraction with large row and column spans. (#795) by @gaborbernat.Unicode normalization of long combining-mark sequences. (#795) by @gaborbernat.Range ancestors. (#795) by @gaborbernat.DOM normalization of empty text nodes. (#795) by @gaborbernat.Range operations on fully contained sibling intervals. (#795) by @gaborbernat.JavaScript minification of long expression sequences. (#795) by @gaborbernat.XSLT numbering with static predicates and union patterns. (#795) by @gaborbernat.XSD validation of values with named-type facets. (#795) by @gaborbernat.XSLT stylesheets with repeated numbering patterns. (#795) by @gaborbernat.JavaScript minification that merges long declaration lists. (#795) by @gaborbernat.computed styles for complex selector alternatives. (#795) by @gaborbernat.Markdown conversion of long runs of punctuation. (#795) by @gaborbernat.Node.equals() for elements with many attributes. (#795) by @gaborbernat.article extraction from pages with many content candidates. (#795) by @gaborbernat.XSLT numbering across repeated source-node visits. (#795) by @gaborbernat.XPath set:difference() on large node sets. (#795) by @gaborbernat.JavaScript literal propagation across many interleaved declarations. (#795) by @gaborbernat.XPath ordered numeric comparisons between node sets. (#795) by @gaborbernat.JavaScript minification of integer arrays. (#795) by @gaborbernat.XSD validation of elements with many declared attributes. (#795) by @gaborbernat.Range operations whose boundary is near the start of a sibling list. (#795) by @gaborbernat.SAX element records. (#795) by @gaborbernat.encoding detection of short inputs. (#795) by @gaborbernat.XSD validation of decimals without numeric bounds. (#795) by @gaborbernat.XPath set:distinct() on large node sets. (#795) by @gaborbernat.XPath equality comparisons of long strings. (#795) by @gaborbernat.DOM normalization of adjacent text nodes. (#795) by @gaborbernat.XPath set:has-same-node() on large node sets. (#795) by @gaborbernat.microdata extraction with repeated item references. (#795) by @gaborbernat.microdata extraction when properties are local to their item. (#795) by @gaborbernat.feed extraction from entries with extension fields. (#795) by @gaborbernat.XPath unions of results already in document order. (#795) by @gaborbernat.CSS minification with many mergeable media blocks. (#795) by @gaborbernat.JavaScript minification with interleaved unused bindings. (#795) by @gaborbernat.DOM linkification of long non-ASCII text. (#795) by @gaborbernat.XSLT applications with many named declarations. (#795) by @gaborbernat.XPath translate() on text with repeated characters. (#795) by @gaborbernat.streaming encoding detection of short inputs. (#795) by @gaborbernat.structured-data extraction from documents without metadata. (#795) by @gaborbernat.IncrementalParser. (#799) by @gaborbernat.parse_into by reusing namespace strings within each parse. (#799) by @gaborbernat.Transform indexes XSLT keys. (#799) by @gaborbernat.Transform enters and leaves scopes. (#799) by @gaborbernat.Sanitizer. (#799) by @gaborbernat.EncodingDetector. (#799) by @gaborbernat.text by determining string width while collecting text. (#799) by @gaborbernat.Transform. (#799) by @gaborbernat.to_annotated_text with many annotation rules. (#799) by @gaborbernat.check on nested sections without headings. (#799) by @gaborbernat.find and find_all. (#799) by @gaborbernat.Element construction. (#799) by @gaborbernat.sanitize. (#799) by @gaborbernat.minify_css. (#799) by @gaborbernat.normalize. (#799) by @gaborbernat.Transform numeric sorting. (#799) by @gaborbernat.detect_language scores text. (#799) by @gaborbernat.xpath concatenates node strings. (#799) by @gaborbernat.minify_css. (#799) by @gaborbernat.find and find_all. (#799) by @gaborbernat.minify_css. (#799) by @gaborbernat.normalize_url. (#799) by @gaborbernat.normalize_url. (#799) by @gaborbernat.normalize_url. (#799) by @gaborbernat.:has() selectors in select. (#799) by @gaborbernat.sanitize when checking allowed attribute prefixes. (#799) by @gaborbernat.PhoneNumber. (#799) by @gaborbernat.Sanitizer prefix checks. (#799) by @gaborbernat.Transform. (#799) by @gaborbernat.css_to_xpath. (#799) by @gaborbernat.normalize. (#799) by @gaborbernat.PhoneNumber. (#799) by @gaborbernat.:default in select. (#799) by @gaborbernat.dates. (#799) by @gaborbernat.select nth selectors. (#799) by @gaborbernat.parse reads UTF-8 or UTF-16 bytes. (#799) by @gaborbernat.minify_js. (#799) by @gaborbernat.Html. (#799) by @gaborbernat.opengraph. (#799) by @gaborbernat.parse_into by avoiding temporary text copies. (#799) by @gaborbernat.Html for elements with many attributes. (#799) by @gaborbernat.is_valid and is_valid for invalid documents. (#799) by @gaborbernat.normalize. (#799) by @gaborbernat.<a name="release-1-9-0-fixed"></a>
let or const binding before initialization. (#795) by @gaborbernat.XSLT numbers with periods when the format contains no separator token. (#795) by @gaborbernat.XPath numbers. (#795) by @gaborbernat.var undefined when an earlier initializer invokes its closure. (#795) by @gaborbernat.XSD or RELAX NG schema. (#795) by @gaborbernat.RELAX NG definition state separate between concurrent validations using the same schema. (#795) by @gaborbernat.let or const binding is read before its initializer. (#795) by @gaborbernat.boilerplate extraction. (#795) by @gaborbernat.RELAX NG validation. (#795) by @gaborbernat.:has() queries from growing retained cache memory without new entries. (#795) by @gaborbernat.pre, textarea and listing elements. (#795) by @gaborbernat.form-data collection when a garbage-collection callback detaches a control's ancestor. (#795) by @gaborbernat.of selector list when calculating :nth-child() and :nth-last-child() specificity. (#795) by @gaborbernat.__html__ method during MarkupSafe-compatible escaping. (#795) by @gaborbernat.XPath regular-expression flags contain repeated letters. (#795) by @gaborbernat.xml namespace during schema validation. (#795) by @gaborbernat.strip_tags annotations. (#796) by @gaborbernat.unwrap annotations. (#796) by @gaborbernat.prune annotations. (#796) by @gaborbernat.strip_comments_node annotations. (#796) by @gaborbernat.extract annotations. (#796) by @gaborbernat.sanitize_node annotations. (#796) by @gaborbernat.surround_contents annotations. (#796) by @gaborbernat.sanitize_report_node annotations. (#796) by @gaborbernat.linkify_node annotations. (#796) by @gaborbernat.remove annotations. (#796) by @gaborbernat.transform_node results from the input and callback types. (#796) by @gaborbernat.collapse_whitespace_node annotations. (#796) by @gaborbernat.minify_css. (#799) by @gaborbernat.minify_css. (#799) by @gaborbernat.minify_css. (#799) by @gaborbernat.Add native DOM whitespace collapse, comment removal, and ordered transformation composition. Serialize subtree children with inner=True on serialize, encode, and serialize_iter. (791) by gaborbernat.
Speed up JavaScript minification of long guard-return sequences. (795) by gaborbernat.
Speed up JavaScript minification of declarations with single-use initializers. (795) by gaborbernat.
Speed up descendant :has() selectors on nested elements. (795) by gaborbernat.
Speed up JavaScript minification of libraries containing boolean literals. (795) by gaborbernat.
Speed up canonical serialization with explicit options. (795) by gaborbernat.
Speed up importing turbohtml from an installed wheel. (795) by gaborbernat.
Speed up XPath translate() with large character maps. (795) by gaborbernat.
Speed up sanitization of elements with many rejected attributes. (795) by gaborbernat.
Speed up XSLT numbering with explicit element, wildcard or document-root patterns. (795) by gaborbernat.
Speed up XML parsing of long text without character references. (795) by gaborbernat.
Speed up HTML parsing with deeply nested formatting elements. (795) by gaborbernat.
Speed up repeated computed-style lookups on an unchanged tree. (795) by gaborbernat.
Speed up HTML parsing with repeated scope checks in nested structures. (795) by gaborbernat.
Speed up XSD validation with inherited simple-type facets. (795) by gaborbernat.
Speed up repeated named-slot assignment queries on wide shadow roots. (795) by gaborbernat.
Speed up CSS minification with long conflicting declaration values. (795) by gaborbernat.
Speed up parent queries over selections with shared parents. (795) by gaborbernat.
Speed up HTML serialization with explicit options. (795) by gaborbernat.
Speed up XML parsing of attributes with many namespace prefixes. (795) by gaborbernat.
Speed up generation of the Unicode normalization tables. (795) by gaborbernat.
Speed up form-data collection from deeply nested disabled fieldsets. (795) by gaborbernat.
Speed up language detection on text with many distinct trigrams. (795) by gaborbernat.
Speed up queries combining many roots supplied out of document order. (795) by gaborbernat.
Speed up article extraction from deeply nested content. (795) by gaborbernat.
Speed up XPath equality comparisons between node sets. (795) by gaborbernat.
Speed up positional CSS queries over wide sibling lists. (795) by gaborbernat.
Speed up repeated default XSLT level="any" numbering. (795) by gaborbernat.
Speed up computed-style matching of class-qualified selectors. (795) by gaborbernat.
Speed up XPath inequality comparisons between node sets. (795) by gaborbernat.
Speed up XPath str:replace() with sparse matches of long strings. (795) by gaborbernat.
Speed up HTML parsing of long text with carriage returns. (795) by gaborbernat.
Speed up HTML parsing that merges text around tables. (795) by gaborbernat.
Speed up Markdown wrapping of long lines. (795) by gaborbernat.
Speed up JavaScript minification of mixed retained and removable declarations. (795) by gaborbernat.
Speed up XSD validation of elements with many instance attributes. (795) by gaborbernat.
Speed up RELAX NG validation of optional groups and interleaves. (795) by gaborbernat.
Speed up microdata extraction when referenced properties are already ordered. (795) by gaborbernat.
Speed up closest-ancestor queries over overlapping selections. (795) by gaborbernat.
Speed up XPath set:intersection() on large node sets. (795) by gaborbernat.
Speed up JavaScript minification that removes declarations from long statement lists. (795) by gaborbernat.
Speed up XPath id() when its argument contains many short nodes. (795) by gaborbernat.
Speed up streaming rewrites that add many attributes to a start tag. (795) by gaborbernat.
Speed up XPath str:concat() over many short text nodes. (795) by gaborbernat.
Speed up compilation of schema patterns with large character classes. (795) by gaborbernat.
Speed up external-link extraction from URLs with many subdomains. (795) by gaborbernat.
Speed up flattening nested shadow-slot assignments. (795) by gaborbernat.
Speed up XSLT applications with many template rules. (795) by gaborbernat.
Speed up canonical serialization of deeply nested trees with xlink attributes. (795) by gaborbernat.
Speed up JavaScript literal propagation within large multi-binding declarations. (795) by gaborbernat.
Speed up plain-text serialization with explicit options. (795) by gaborbernat.
Speed up repeated default XSLT sibling numbering. (795) by gaborbernat.
Speed up adding many attributes to an element. (795) by gaborbernat.
Speed up CSS minification with many rules sharing declaration bodies. (795) by gaborbernat.
Speed up mutations observed only for unrelated event kinds. (795) by gaborbernat.
Speed up repeated element path generation on an unchanged tree. (795) by gaborbernat.
Speed up table extraction with large row and column spans. (795) by gaborbernat.
Speed up Unicode normalization of long combining-mark sequences. (795) by gaborbernat.
Speed up cloning partially selected Range ancestors. (795) by gaborbernat.
Speed up serialization of elements with large attribute sets. (795) by gaborbernat.
Speed up publication-date extraction from text containing many distinct dates. (795) by gaborbernat.
Speed up pruning selections that share matching ancestors. (795) by gaborbernat.
Speed up shadow-slot assignment queries on hosts with many children. (795) by gaborbernat.
Speed up DOM normalization of empty text nodes. (795) by gaborbernat.
Speed up reading attributes from tokens with many attributes. (795) by gaborbernat.
Speed up Range operations on fully contained sibling intervals. (795) by gaborbernat.
Speed up JavaScript minification of long expression sequences. (795) by gaborbernat.
Speed up XSLT numbering with static predicates and union patterns. (795) by gaborbernat.
Speed up XSD validation of values with named-type facets. (795) by gaborbernat.
Speed up XSLT stylesheets with repeated numbering patterns. (795) by gaborbernat.
Speed up JavaScript minification that merges long declaration lists. (795) by gaborbernat.
Speed up computed styles for complex selector alternatives. (795) by gaborbernat.
Speed up repeated validation with schema patterns. (795) by gaborbernat.
Speed up queries combining many detached roots. (795) by gaborbernat.
Speed up Markdown conversion of long runs of punctuation. (795) by gaborbernat.
Speed up Node.equals() for elements with many attributes. (795) by gaborbernat.
Speed up article extraction from pages with many content candidates. (795) by gaborbernat.
Speed up XML parsing of elements with many distinct attributes. (795) by gaborbernat.
Speed up queries spanning many documents. (795) by gaborbernat.
Speed up JavaScript initialization-order checks across many variable pairs. (795) by gaborbernat.
Speed up explicit XSLT numbering across repeated source-node visits. (795) by gaborbernat.
Speed up XPath set:difference() on large node sets. (795) by gaborbernat.
Speed up JavaScript literal propagation across many interleaved declarations. (795) by gaborbernat.
Speed up XPath ordered numeric comparisons between node sets. (795) by gaborbernat.
Speed up JavaScript minification of integer arrays. (795) by gaborbernat.
Speed up XSD validation of elements with many declared attributes. (795) by gaborbernat.
Speed up Range operations whose boundary is near the start of a sibling list. (795) by gaborbernat.
Speed up iteration over SAX element records. (795) by gaborbernat.
Speed up encoding detection of short inputs. (795) by gaborbernat.
Speed up repeated document-wide radio-group updates. (795) by gaborbernat.
Speed up XML parsing of long attribute values without character references. (795) by gaborbernat.
Speed up XSD validation of decimals without numeric bounds. (795) by gaborbernat.
Speed up XPath set:distinct() on large node sets. (795) by gaborbernat.
Speed up XPath equality comparisons of long strings. (795) by gaborbernat.
Speed up DOM normalization of adjacent text nodes. (795) by gaborbernat.
Speed up XPath set:has-same-node() on large node sets. (795) by gaborbernat.
Speed up HTML parsing with many active formatting elements. (795) by gaborbernat.
Speed up sibling queries over selections with shared parents. (795) by gaborbernat.
Speed up microdata extraction with repeated item references. (795) by gaborbernat.
Speed up microdata extraction when properties are local to their item. (795) by gaborbernat.
Speed up HTML parsing of long text containing isolated NUL characters. (795) by gaborbernat.
Speed up feed extraction from entries with extension fields. (795) by gaborbernat.
Speed up XPath unions of results already in document order. (795) by gaborbernat.
Speed up CSS minification with many mergeable media blocks. (795) by gaborbernat.
Speed up JavaScript minification with interleaved unused bindings. (795) by gaborbernat.
Speed up DOM linkification of long non-ASCII text. (795) by gaborbernat.
Speed up XSLT applications with many named declarations. (795) by gaborbernat.
Speed up XPath translate() on text with repeated characters. (795) by gaborbernat.
Speed up streaming encoding detection of short inputs. (795) by gaborbernat.
Speed up structured-data extraction from documents without metadata. (795) by gaborbernat.
Skip repeated NUL scans in ~turbohtml.IncrementalParser. (799) by gaborbernat.
Speed up ~turbohtml.treebuild.parse_into by reusing namespace strings within each parse. (799) by gaborbernat.
Avoid repeated duplicate scans when ~turbohtml.transform.Transform indexes XSLT keys. (799) by gaborbernat.
Avoid shifting existing variable bindings when ~turbohtml.transform.Transform enters and leaves scopes. (799) by gaborbernat.
Speed up escaping disallowed tags with many attributes in ~turbohtml.clean.Sanitizer. (799) by gaborbernat.
Skip disqualified encoding candidates in ~turbohtml.detect.EncodingDetector. (799) by gaborbernat.
Speed up ~turbohtml.Node.text by determining string width while collecting text. (799) by gaborbernat.
Speed up text emission in ~turbohtml.transform.Transform. (799) by gaborbernat.
Reduce rule matching work in ~turbohtml.Node.to_annotated_text with many annotation rules. (799) by gaborbernat.
Speed up ~turbohtml.conformance.check on nested sections without headings. (799) by gaborbernat.
Speed up exact text filters in ~turbohtml.Node.find and ~turbohtml.Node.find_all. (799) by gaborbernat.
Speed up ~turbohtml.Element construction. (799) by gaborbernat.
Speed up template-safe ~turbohtml.clean.sanitize. (799) by gaborbernat.
Speed up Unicode range sorting in ~turbohtml.clean.minify_css. (799) by gaborbernat.
Skip impossible composition lookups in ~turbohtml.detect.normalize. (799) by gaborbernat.
Avoid redundant string copies and integer conversions in ~turbohtml.transform.Transform numeric sorting. (799) by gaborbernat.
Select only the highest-ranked trigrams when ~turbohtml.detect.detect_language scores text. (799) by gaborbernat.
Avoid temporary text copies when ~turbohtml.Node.xpath concatenates node strings. (799) by gaborbernat.
Speed up zero terms with large exponents in ~turbohtml.clean.minify_css. (799) by gaborbernat.
Speed up boolean attribute filters in ~turbohtml.Node.find and ~turbohtml.Node.find_all. (799) by gaborbernat.
Avoid temporary function-rendering buffers in ~turbohtml.clean.minify_css. (799) by gaborbernat.
Avoid rescanning ASCII hosts in ~turbohtml.extract.normalize_url. (799) by gaborbernat.
Speed up unescaped query keys in ~turbohtml.extract.normalize_url. (799) by gaborbernat.
Speed up dot-segment handling in ~turbohtml.extract.normalize_url. (799) by gaborbernat.
Speed up child and sibling :has() selectors in ~turbohtml.Node.select. (799) by gaborbernat.
Speed up ~turbohtml.clean.sanitize when checking allowed attribute prefixes. (799) by gaborbernat.
Use indexed country-code lookup when formatting and validating ~turbohtml.clean.PhoneNumber. (799) by gaborbernat.
Speed up phone table generation. (799) by gaborbernat.
Speed up Unicode normalization table generation. (799) by gaborbernat.
Skip unused attribute-name conversions in ~turbohtml.clean.Sanitizer prefix checks. (799) by gaborbernat.
Reuse namespace declarations for consecutive copies of a literal element in ~turbohtml.transform.Transform. (799) by gaborbernat.
Speed up literal conversion in ~turbohtml.convert.css_to_xpath. (799) by gaborbernat.
Skip unchanged prefixes in ~turbohtml.detect.normalize. (799) by gaborbernat.
Index Unicode digit ranges when parsing ~turbohtml.clean.PhoneNumber. (799) by gaborbernat.
Reuse each form's first submit control when matching :default in ~turbohtml.Node.select. (799) by gaborbernat.
Stop temporal text scanning after the first valid date in ~turbohtml.extract.dates. (799) by gaborbernat.
Reuse adjacent sibling positions in ~turbohtml.Node.select nth selectors. (799) by gaborbernat.
Use direct UTF decoders when ~turbohtml.parse reads UTF-8 or UTF-16 bytes. (799) by gaborbernat.
Speed up single-character renaming in ~turbohtml.clean.minify_js. (799) by gaborbernat.
Speed up named-entity serialization with ~turbohtml.Html. (799) by gaborbernat.
Avoid intermediate metadata copies in ~turbohtml.Document.opengraph. (799) by gaborbernat.
Speed up ~turbohtml.treebuild.parse_into by avoiding temporary text copies. (799) by gaborbernat.
Speed up attribute sorting with ~turbohtml.Html for elements with many attributes. (799) by gaborbernat.
Speed up ~turbohtml.validate.RelaxNG.is_valid and ~turbohtml.validate.XMLSchema.is_valid for invalid documents. (799) by gaborbernat.
Use direct combining-class lookup for common marks in ~turbohtml.detect.normalize. (799) by gaborbernat.
Avoid crashes when minifying detached subtrees containing adjacent ruby annotations or option groups. (795) by gaborbernat.
Avoid crashes and stale results when selector-cache cleanup callbacks move or modify the queried node. (795) by gaborbernat.
Preserve JavaScript initialization errors when a closure reads a let or const binding before initialization. (795) by gaborbernat.
Protect Query parent, child and sibling traversal against concurrent mutation of the same tree on free-threaded Python. (795) by gaborbernat.
Separate multi-level XSLT numbers with periods when the format contains no separator token. (795) by gaborbernat.
Avoid invalid integer conversions when formatting large XPath numbers. (795) by gaborbernat.
Fix memory leaks when schema validation reads text and CDATA nodes. (795) by gaborbernat.
Keep unrelated benchmark inputs out of each timing worker's setup and report invalid inputs as errors. (795) by gaborbernat.
Fix crashes when annotation exporters consume generators that yield temporary labels. (795) by gaborbernat.
Keep a captured JavaScript var undefined when an earlier initializer invokes its closure. (795) by gaborbernat.
Preserve JavaScript initialization errors when a switch-case jump skips a binding's initializer. (795) by gaborbernat.
Release temporary validation buffers after each call when reusing an XSD or RELAX NG schema. (795) by gaborbernat.
Keep RELAX NG definition state separate between concurrent validations using the same schema. (795) by gaborbernat.
Preserve JavaScript initialization errors when a let or const binding is read before its initializer. (795) by gaborbernat.
Release temporary text buffers after boilerplate extraction. (795) by gaborbernat.
Avoid concurrent writes to shared schema text during RELAX NG validation. (795) by gaborbernat.
Prevent repeated descendant :has() queries from growing retained cache memory without new entries. (795) by gaborbernat.
Prevent extra unwritten bytes in escaped output when escapable characters occupy adjacent byte positions. (795) by gaborbernat.
Handle empty leading text nodes when serializing pre, textarea and listing elements. (795) by gaborbernat.
Avoid crashes during form-data collection when a garbage-collection callback detaches a control's ancestor. (795) by gaborbernat.
Include the of selector list when calculating :nth-child() and :nth-last-child() specificity. (795) by gaborbernat.
Propagate exceptions raised while looking up an object's __html__ method during MarkupSafe-compatible escaping. (795) by gaborbernat.
Preserve JavaScript variable behavior when duplicate declarations include an uninitialized declaration. (795) by gaborbernat.
Prevent buffer overruns when XPath regular-expression flags contain repeated letters. (795) by gaborbernat.
Avoid concurrent writes while resolving the reserved xml namespace during schema validation. (795) by gaborbernat.
Preserve the receiver type in ~turbohtml.Node.strip_tags annotations. (796) by gaborbernat.
Preserve the receiver type in ~turbohtml.Node.unwrap annotations. (796) by gaborbernat.
Preserve the receiver type in ~turbohtml.Node.prune annotations. (796) by gaborbernat.
Preserve the input node type in ~turbohtml.clean.strip_comments_node annotations. (796) by gaborbernat.
Preserve the receiver type in ~turbohtml.Node.extract annotations. (796) by gaborbernat.
Preserve the input node type in ~turbohtml.clean.sanitize_node annotations. (796) by gaborbernat.
Preserve the wrapper type in ~turbohtml.Range.surround_contents annotations. (796) by gaborbernat.
Preserve the input node type in ~turbohtml.clean.sanitize_report_node annotations. (796) by gaborbernat.
Preserve the input node type in ~turbohtml.clean.linkify_node annotations. (796) by gaborbernat.
Preserve the receiver type in ~turbohtml.Node.remove annotations. (796) by gaborbernat.
Infer ~turbohtml.clean.transform_node results from the input and callback types. (796) by gaborbernat.
Preserve the input node type in ~turbohtml.clean.collapse_whitespace_node annotations. (796) by gaborbernat.
Preserve prefix encoding errors when sanitizing attributes without exact-name rules. (799) by gaborbernat.
Preserve numeric mantissas longer than 128 digits in ~turbohtml.clean.minify_css. (799) by gaborbernat.
Prevent numeric exponent overflow in ~turbohtml.clean.minify_css. (799) by gaborbernat.
Preserve benchmark notes for libraries that use different labels across operations in migration tables. (799) by gaborbernat.
Bound decimal expansion of exponent notation in ~turbohtml.clean.minify_css. (799) by gaborbernat.
PhoneNumbers(collapse_whitespace=True) reads a run of HTML whitespace between the parts of a number as the one space it renders as, so a number a sour
<a name="release-1-8-0-added"></a>
PhoneNumbers(collapse_whitespace=True) reads a run of HTML whitespace between the parts of a number as the one space it renders as, so a number a source formatter or a template broke across a line still links. (#758) by @gaborbernat.http://localhost:8000/path, http://intranet/ and http://[::1]:8080/ link. A bare domain still needs a dot and a known top-level domain to be told apart from an ordinary word. Recognize an internationalized top-level domain written as its Unicode label, so президент.рф links the way президент.xn--p1ai already did. (#768) by @gaborbernat.unique=True to LinkDetector.find, which keeps the first span of each distinct URL. (#770) by @gaborbernat.nofollow and target_blank into the C core. They keep their names, their signatures and their behavior, with one correction: the web-scheme test now matches the whole scheme, so ht: and httpx: no longer count as web links. (#774) by @gaborbernat.Query facade's set algebra into the C core: deduplicating by node identity, collecting siblings, the combined text, the joined attribute read, and the four class operations. Behavior is unchanged. (#775) by @gaborbernat.Detection allowlist, exclusions, language preference and confidence floor. Results are unchanged. (#776) by @gaborbernat.Extraction thresholds. Results are unchanged. (#777) by @gaborbernat.MicrodataItem as nested plain dicts. Decoding each block stays with the standard library's JSON parser. Results are unchanged. (#778) by @gaborbernat.<meta>, JSON-LD, <time> and visible-text signals dates reads now run in one walk each. Results are unchanged. (#779) by @gaborbernat.normalize_url, clean_url and extract_links now run their normalization, gates and anchor walk in one C call each. Results are unchanged. (#780) by @gaborbernat.check reads valid from the walk, and errors/warnings/infos filter there. Results are unchanged. (#781) by @gaborbernat.parent, children and closest walk there, and a Matcher applies its limit and filters a node's children inside the walk. Results are unchanged. (#782) by @gaborbernat.StyleDeclaration's accessors into the C core: which declaration wins a repeated property and the text serialization are computed there. Results are unchanged. (#783) by @gaborbernat.whatwg-* codec name resolves to, when a byte-order mark settles an EncodingDetector, the no-match answer, and the language confidence floor. Results are unchanged. (#784) by @gaborbernat.rel value, the value allowlists, the style patterns and the transform rules a Sanitizer indexes are built there. Results are unchanged. (#785) by @gaborbernat.attributes translation into the C core: the flat, per-tag and callable shapes of clean compile there, and the per-tag predicates run through a C-bound filter. Results are unchanged. (#786) by @gaborbernat.PhoneNumber are computed there. Results are unchanged. (#787) by @gaborbernat.striptags into the C core. Results are unchanged. (#789) by @gaborbernat.build's argument sorting into the C core: a leading mapping becomes the attributes and a string becomes a text node there, for E and document alike. Results are unchanged. (#790) by @gaborbernat.sanitize_node and sanitize_report_node, the tree-to-tree sanitizer for a pipeline that parses once and serializes once; sanitize and sanitize_report also accept a parsed node. (#793) by @gaborbernat.linkify_node, which links URLs, email addresses and phone numbers in an already parsed tree in place; linkify also accepts a parsed node. (#794) by @gaborbernat.<a name="release-1-8-0-fixed"></a>
| where turbohtml writes a Markdown table cell's content rather than over the finished cell, so a nested table no longer adds a backslash per level; a table, list or <br> in a cell keeps its HTML unless Markdown.Tables(cell_blocks="text"). (#764) by @gaborbernat.https:/nonsense.com no longer renders as https:/<a href="http://nonsense.com">nonsense.com</a>. Link a written mailto: URI as one anchor covering its own scheme. (#766) by @gaborbernat.http://example.com- links http://example.com. Treat a port outside 0-65535 as text, and stop reading an underscore in a host's last two labels as a bare domain, so _example.com stays plain while the _dmarc.example.com of a DNS record still links. (#767) by @gaborbernat.<script type="application/ld+json"> block that the decoder cannot process for a reason other than malformed JSON, such as nesting past the interpreter's recursion budget, now raises from json_ld and dates instead of being skipped. (#788) by @gaborbernat.<a name="release-1-8-0-documentation"></a>
migration guide from urlextract, which maps its find_urls/has_urls surface onto LinkDetector and states what turbohtml does not do: no DNS check, no bare IP addresses, no tunable stop characters, and no runtime download of the top-level-domain list. (#772) by @gaborbernat.PhoneNumbers(collapse_whitespace=True) reads a run of HTML whitespace between the parts of a number as the one space it renders as, so a number a source formatter or a template broke across a line still links. (758) by gaborbernat.
Detect a URL whose authority is a single-label host or an IP literal when its scheme is written, so http://localhost:8000/path, http://intranet/ and http://[::1]:8080/ link. A bare domain still needs a dot and a known top-level domain to be told apart from an ordinary word. Recognize an internationalized top-level domain written as its Unicode label, so президент.рф links the way президент.xn--p1ai already did. (768) by gaborbernat.
Add unique=True to LinkDetector.find, which keeps the first span of each distinct URL. (770) by gaborbernat.
Move the work behind the shipped link callbacks ~turbohtml.clean.nofollow and ~turbohtml.clean.target_blank into the C core. They keep their names, their signatures and their behavior, with one correction: the web-scheme test now matches the whole scheme, so ht: and httpx: no longer count as web links. (774) by gaborbernat.
Move the ~turbohtml.query.Query facade's set algebra into the C core: deduplicating by node identity, collecting siblings, the combined text, the joined attribute read, and the four class operations. Behavior is unchanged. (775) by gaborbernat.
Move the encoding detector's candidate ranking into the C core: deduplicating the scored candidates, normalizing each score to its share, promoting the detector's own winner, and applying the ~turbohtml.detect.Detection allowlist, exclusions, language preference and confidence floor. Results are unchanged. (776) by gaborbernat.
Move the boilerplate classifier into the C core: segmenting a page into paragraph units, collapsing each unit's text, and deciding which units are article content against the ~turbohtml.extract.Extraction thresholds. Results are unchanged. (777) by gaborbernat.
Move the structured-data shaping into the C core: which JSON-LD blocks carry data, and rendering a ~turbohtml.MicrodataItem as nested plain dicts. Decoding each block stays with the standard library's JSON parser. Results are unchanged. (778) by gaborbernat.
Move the publication-date stages into the C core: the canonical-URL, <meta>, JSON-LD, <time> and visible-text signals ~turbohtml.extract.dates reads now run in one walk each. Results are unchanged. (779) by gaborbernat.
Move the URL cleaning pipeline into the C core: ~turbohtml.extract.normalize_url, ~turbohtml.extract.clean_url and ~turbohtml.extract.extract_links now run their normalization, gates and anchor walk in one C call each. Results are unchanged. (780) by gaborbernat.
Move the conformance verdict and the severity views into the C core: ~turbohtml.conformance.check reads valid from the walk, and errors/warnings/infos filter there. Results are unchanged. (781) by gaborbernat.
Move the query facade's traversal into the C core: ~turbohtml.query.Query.parent, ~turbohtml.query.Query.children and ~turbohtml.query.Query.closest walk there, and a ~turbohtml.query.Matcher applies its limit and filters a node's children inside the walk. Results are unchanged. (782) by gaborbernat.
Move ~turbohtml.cssom.StyleDeclaration's accessors into the C core: which declaration wins a repeated property and the text serialization are computed there. Results are unchanged. (783) by gaborbernat.
Move the encoding and language detectors' last decisions into the C core: which label a whatwg-* codec name resolves to, when a byte-order mark settles an ~turbohtml.detect.EncodingDetector, the no-match answer, and the language confidence floor. Results are unchanged. (784) by gaborbernat.
Move the sanitizer's policy compilation into the C core: the rel value, the value allowlists, the style patterns and the transform rules a ~turbohtml.clean.Sanitizer indexes are built there. Results are unchanged. (785) by gaborbernat.
Move the bleach shim's attributes translation into the C core: the flat, per-tag and callable shapes of turbohtml.migration.bleach.clean compile there, and the per-tag predicates run through a C-bound filter. Results are unchanged. (786) by gaborbernat.
Move the link and phone detectors' configuration folding into the C core: tag, top-level-domain, scheme and word lists, region codes, the phone type mask and the E.164 check of ~turbohtml.clean.PhoneNumber are computed there. Results are unchanged. (787) by gaborbernat.
Move the whitespace fold of turbohtml.migration.markupsafe.Markup.striptags into the C core. Results are unchanged. (789) by gaborbernat.
Move turbohtml.build's argument sorting into the C core: a leading mapping becomes the attributes and a string becomes a text node there, for ~turbohtml.build.E and ~turbohtml.build.document alike. Results are unchanged. (790) by gaborbernat.
Add ~turbohtml.clean.sanitize_node and ~turbohtml.clean.sanitize_report_node, the tree-to-tree sanitizer for a pipeline that parses once and serializes once; ~turbohtml.clean.sanitize and ~turbohtml.clean.sanitize_report also accept a parsed node. (793) by gaborbernat.
Add ~turbohtml.clean.linkify_node, which links URLs, email addresses and phone numbers in an already parsed tree in place; ~turbohtml.clean.linkify also accepts a parsed node. (794) by gaborbernat.
Escape a | where turbohtml writes a Markdown table cell's content rather than over the finished cell, so a nested table no longer adds a backslash per level; a table, list or <br> in a cell keeps its HTML unless Markdown.Tables(cell_blocks="text"). (764) by gaborbernat.
Leave a URL whose scheme syntax is malformed entirely plain instead of linking its host on its own, so https:/nonsense.com no longer renders as https:/<a href="http://nonsense.com">nonsense.com</a>. Link a written mailto: URI as one anchor covering its own scheme. (766) by gaborbernat.
End a host before a trailing hyphen rather than dropping the whole link, so http://example.com- links http://example.com. Treat a port outside 0-65535 as text, and stop reading an underscore in a host's last two labels as a bare domain, so _example.com stays plain while the _dmarc.example.com of a DNS record still links. (767) by gaborbernat.
A <script type="application/ld+json"> block that the decoder cannot process for a reason other than malformed JSON, such as nesting past the interpreter's recursion budget, now raises from ~turbohtml.Document.json_ld and ~turbohtml.extract.dates instead of being skipped. (788) by gaborbernat.
Add a migration guide from urlextract, which maps its find_urls/has_urls surface onto ~turbohtml.clean.LinkDetector and states what turbohtml does not do: no DNS check, no bare IP addresses, no tunable stop characters, and no runtime download of the top-level-domain list. (772) by gaborbernat.
Link phone numbers as tel: anchors with a PhoneNumbers setting; each match carries a PhoneNumber, the class that parses and formats numbers. (#758) by
<a name="release-1-7-0-added"></a>
tel: anchors with a PhoneNumbers setting; each match carries a PhoneNumber, the class that parses and formats numbers. (#758) by @gaborbernat.Link phone numbers as tel: anchors with a ~turbohtml.clean.PhoneNumbers setting; each match carries a ~turbohtml.clean.PhoneNumber, the class that parses and formats numbers. (758) by gaborbernat.
Parse a document, or feed a first stream chunk, that opens with a carriage return without touching the not yet allocated input buffer; UndefinedBehavi
<a name="release-1-6-1-fixed"></a>
Parse a document, or feed a first stream chunk, that opens with a carriage return without touching the not yet allocated input buffer; UndefinedBehaviorSanitizer reported the empty append as a zero offset applied to a null pointer. (752) by gaborbernat.
Compile reusable XSLT stylesheet state during Transform construction. (#713) by @gaborbernat.
<a name="release-1-6-0-added"></a>
Transform construction. (#713) by @gaborbernat.allow_imports and import_root controls for XSLT import filesystem access. (#714) by @gaborbernat.<a name="release-1-6-0-fixed"></a>
</p> and </br> as foreign-content breakout tokens so the resulting HTML elements follow the foreign root, matching the HTML standard and WPT. (#32) by @gaborbernat.has_link after the first match without allocating a span list. (#711) by @gaborbernat.keygen rules inside select elements. (#717) by @gaborbernat.nobr elements as siblings across table formatting scope. (#718) by @gaborbernat.itemref graphs, and read combined metadata from one tree snapshot. (#722) by @gaborbernat.list cast from filter under current ty releases. (#738) by @gaborbernat.Compile reusable XSLT stylesheet state during ~turbohtml.transform.Transform construction. (713) by gaborbernat.
Add allow_imports and import_root controls for XSLT import filesystem access. (714) by gaborbernat.
Process </p> and </br> as foreign-content breakout tokens so the resulting HTML elements follow the foreign root, matching the HTML standard and WPT. (32) by gaborbernat.
Recheck sanitizer callback and forced-attribute rewrites against the mandatory baseline safety rules. (708) by gaborbernat.
Reject SVG animation elements that can assign event handlers or script URLs at runtime. (709) by gaborbernat.
Make XML tag-name queries case-sensitive, including names shared with known HTML tags. (710) by gaborbernat.
Stop ~turbohtml.clean.LinkDetector.has_link after the first match without allocating a span list. (711) by gaborbernat.
Avoid building a whole-tree tag index for first-result and small-limit queries. (712) by gaborbernat.
Move HTML-aware linkifier traversal and mutation into one native operation. (715) by gaborbernat.
Parse living-standard HTML processing instructions as typed nodes and events while keeping reserved XML targets as comments. (716) by gaborbernat.
Apply the living-standard keygen rules inside select elements. (717) by gaborbernat.
Keep repeated nobr elements as siblings across table formatting scope. (718) by gaborbernat.
Decode CSS escapes when checking sanitizer function names and URL schemes. (721) by gaborbernat.
Complete deep XML and programmatic-tree operations without silent truncation or C stack exhaustion. Bound recursive Microdata and RDFa records at 400 levels, reject cyclic Microdata itemref graphs, and read combined metadata from one tree snapshot. (722) by gaborbernat.
Remove a redundant list cast from turbohtml.query.Matcher.filter under current ty releases. (738) by gaborbernat.
Report unacknowledged self-closing start tags as HTML parse errors. (743) by gaborbernat.
Match tag and attribute names case-sensitively on a parse_xml document: an uppercase name like Y reads through attrs instead of raising KeyError, CSS
<a name="release-1-5-1-fixed"></a>
parse_xml document: an uppercase name like Y reads through attrs instead of raising KeyError, CSS selectors tell [Attr] from [attr] and Child from child, and loads/deepcopy round-trip the tree without folding its names to the HTML parser's lowercase. (#695) by @gaborbernat.parse_xml document per XML 1.0 §2.11 across attribute values, CDATA sections, comments, and processing instructions: a literal CRLF folds to a single LF (one space in an attribute value) rather than two, matching the text-content path and every other conformant XML parser. (#696) by @gaborbernat.Match tag and attribute names case-sensitively on a turbohtml.parse_xml document: an uppercase name like Y reads through ~turbohtml.Element.attrs instead of raising KeyError, CSS selectors tell [Attr] from [attr] and Child from child, and pickle.loads/copy.deepcopy round-trip the tree without folding its names to the HTML parser's lowercase. (695) by gaborbernat.
Normalize line endings in a turbohtml.parse_xml document per XML 1.0 §2.11 across attribute values, CDATA sections, comments, and processing instructions: a literal CRLF folds to a single LF (one space in an attribute value) rather than two, matching the text-content path and every other conformant XML parser. (696) by gaborbernat.
Speed the C core across the read, query, validation, and extraction paths. Measured against the 1.4.0 release on a fixed workload, an id-selective XPa
<a name="release-1-5-0-added"></a>
xsl:number computes a level's number as the count of preceding siblings that match the count criteria, which rescanned the whole run for each sibling and cost time quadratic in the run length; number_counts was 10.13% of all instructions executed by the instruction-dense transform workload, the largest single entry ahead of every CPython symbol. The engine now carries the previous answer forward, since a node's number is its previous sibling's number plus whether that sibling counted, and holds the criteria alongside it so a run numbered under different criteria does not reuse it. Callgrind measures 5.9% fewer instructions over that workload (#687). (#687) by @gaborbernat.html.parser adapter's tokens from C. HTMLParser used to loop in Python over the token stream, building a token object and reading six of its fields for every token; the tokenizer now calls the handle_* methods itself, binding them once per feed and passing the strings straight through. Under Callgrind that removes 30.8% of the instructions the whole workload executes and 46.7% of its indirect branches, which is what the interpreter spends on dispatch. The adapter now leads lxml's native target parser by 1.7 to 2.7 times where it previously trailed it, and html.parser by 7.5 to 11.2 times. (#689) by @gaborbernat.sax_parse built a tuple, a typed record, and an isinstance chain for every event; the tokenizer now binds the six handler methods once and drives them off the tree walk, for 43.7% fewer instructions with instruction-cache misses down 71% on the WHATWG specification. URL cleaning (clean_url, normalize_url, extract_links), the dates <meta> stage, escape_identifier, and linkify's scheme classification each moved their loops to C as well, for 3.5% to 56.8% fewer instructions on those operations. Differential runs against the retired Python across 1,484,640, 809,481, 360,282, 302,762, 38,590, and 4,828 inputs found one divergence: the URL resolver matches %2e in either case as the WHATWG URL path state specifies, which no public call reaches because percent-encoding uppercases escape hex first. iter_events keeps its typed records, since those are its public product. Other hot paths keep their Python entry and shed work. XSD validation resolves each schema element's qname once at compile time into a binary-searched table for 17.2% fewer instructions, built for XSD only after the eager cache slowed RELAX NG compilation by 8.15%. The link walk mints element wrappers on first use (14.8% fewer) and skips the URL join that already returns an absolute reference (67.8% fewer); the <meta> encoding prescan jumps inert bytes with memchr (8.67% fewer on ASCII); the gb18030 decoder maps astral pointers by arithmetic (13.4% fewer); and CSS property dispatch gates on the first byte (9.3% fewer on bootstrap.css). The migration and benchmark tables also stopped over-claiming: a caveat marks only the rows of the operation it describes, a shared measurement shows in both columns, XPath labels render as inline code, and the CSS-stripper note gives the measured 1-3% size difference. (#692) by @gaborbernat.<a name="release-1-5-0-documentation"></a>
Add capture_attributes=False for tag-and-text token streams, and reduce DOM allocation for large documents. (#640) by @gaborbernat.
<a name="release-1-4-0-added"></a>
capture_attributes=False for tag-and-text token streams, and reduce DOM allocation for large documents. (#640) by @gaborbernat.<a name="release-1-4-0-fixed"></a>
Node hash stable across cross-document adoption so sets and dictionaries can still find it. (#634) by @gaborbernat.ValueError with the import chain for circular xsl:import references. (#637) by @gaborbernat.find results in document order across connected roots; retain root input order across disconnected trees. (#638) by @gaborbernat.Add capture_attributes=False for tag-and-text token streams, and reduce DOM allocation for large documents. ( #640 ) by @gaborbernat .
Keep a turbohtml.Node hash stable across cross-document adoption so sets and dictionaries can still find it. ( #634 ) by @gaborbernat .
Copy source subtrees from one state during DOM adoption, Range operations, and XSLT under free-threaded Python. ( #635 ) by @gaborbernat .
Recognize XSLT instructions by namespace URI and local name, including stylesheets with a default XSLT namespace or rebound prefix. ( #636 ) by @gaborbernat .
Raise ValueError with the import chain for circular xsl:import references. ( #637 ) by @gaborbernat .
Return turbohtml.query.Query.find() results in document order across connected roots; retain root input order across disconnected trees. ( #638 ) by @gaborbernat .
Add capture_attributes=False for tag-and-text token streams, and reduce DOM allocation for large documents. (640) by gaborbernat.
Keep a turbohtml.Node hash stable across cross-document adoption so sets and dictionaries can still find it. (634) by gaborbernat.
Copy source subtrees from one state during DOM adoption, Range operations, and XSLT under free-threaded Python. (635) by gaborbernat.
Recognize XSLT instructions by namespace URI and local name, including stylesheets with a default XSLT namespace or rebound prefix. (636) by gaborbernat.
Raise ValueError with the import chain for circular xsl:import references. (637) by gaborbernat.
Return turbohtml.query.Query.find results in document order across connected roots; retain root input order across disconnected trees. (638) by gaborbernat.
🐍 PyPI release 📜 Full Changelog
Run the C core on PyPy 3.10 and 3.11 through cpyext, with the same conformance and byte-identical output as CPython; see /explanation/interpreters for
<a name="release-1-3-0-added"></a>
cpyext, with the same conformance and byte-identical output as CPython; see /explanation/interpreters for what cpyext costs and for the three behaviors that do not carry over. (#623) by @gaborbernat.IncrementalParser's decode scratch on every feed. (#624) by @gaborbernat.<a name="release-1-3-0-fixed"></a>
IndexError for a negative subscript further back than a node's child count; node[-len - 1] answered the first child, where list raises. (#623) by @gaborbernat.IncrementalParser chunk boundary. A chunk ending on an incomplete escape sequence dropped back to the output state, so the next chunk read the escape's first byte as content and lost one U+FFFD. (#624) by @gaborbernat.parse no longer mojibakes two common inputs. Bytes that are valid UTF-8 but declare no encoding now decode as UTF-8 rather than reaching the windows-1252 fallback. Validity is a structural proof rather than a frequency guess, so it costs none of the candidate scoring detect_encoding=True adds, and pure ASCII still resolves to windows-1252, which decodes it to the same text. A <meta> charset sitting past the prescan's 1024-byte window now redoes the parse against what it declares, following the WHATWG "changing the encoding while parsing" step, so where the declaration sits in the document no longer changes the answer. Only a real <meta> element counts, so a charset written inside a <script> string cannot pose as one, and a byte-order mark or the encoding argument still settles the encoding. encoding_confidence reports which step answered: "certain" when the document named its own encoding through a byte-order mark, the encoding argument, or a <meta> charset, "tentative" when the sniff guessed, and None for str input. detect reads bytes and has no tree to consult, so on a document whose only <meta> sits past the prescan window it stops at the prescan and can disagree with parse. errors reports every parse error the WHATWG tokenizer defines. It carried 8 of the 48 codes the algorithm names, so a\x00b and a malformed <!DOCTYPE> both parsed without a word. turbohtml now reports the other 45, along with the preprocessing errors a control, noncharacter, or surrogate code point raises by being in the input at all, interleaved with the tokenizer's in source order. Reading errors is what finds the preprocessing ones, so a parse that never asks for them does not pay to look. strict=True therefore raises on documents it used to accept, and IncrementalParser keeps no source to walk, so it reports none of them. Nothing gated the errors arrays the vendored html5lib-tests tokenizer suite carries; they now gate the codes and their order on all 7032 cases, and the line and column on every BMP-only input. (#625) by @gaborbernat._c/encoding/detect.h ports, takes the host's rightmost DNS label and reads it three ways: the encoding that label expects gains a point, the encodings native to it keep their score, and the rest pay a penalty. The port dropped all three, so turbohtml scored a Czech page served from a .ru domain the same as one served from .cz. Detection now carries a tld field that reaches the scoring, and leaving it unset detects as before. A differential test runs both implementations over all 133 labels chardetng's classifier carries. EncodingDetector no longer buffers the stream. It appended every chunk to a bytearray and detected once over the concatenation at close, so a caller streaming a large file paid its length in memory, in a class documented as mirroring chardet's UniversalDetector. Each candidate now carries its own state between feeds, and the only bytes the detector keeps are the leading 1024 the byte-order-mark check and the <meta> prescan read, which the spec bounds. Where the chunks fall does not change the answer: the stateful detector is the only implementation, so detect drives it with a single feed and the differential test against chardetng covers the scoring both paths share. A four-byte gb18030 sequence that resolved to no code point returned an error without naming the byte that caused it, leaving error_at at whatever the previous error had set. Reading a whole buffer at once never noticed, because the value that means "the input ended mid-sequence" is only ever set at the end. A resumed decoder did notice, and so would IncrementalParser, which tells "wait for more input" from "this input is wrong" by that same value. (#627) by @gaborbernat.IncrementalParser, which collected none: the streaming tokenizer never attached an error sink, and the preprocessing errors were found by a pass over a source no stream keeps. Each chunk is now swept as it arrives. (#629) by @gaborbernat.<a name="release-1-3-0-documentation"></a>
/explanation/interpreters, from a table the benchmark harness generates (tox -e bench -- interpreters) rather than from figures typed into prose. How the core adapts to cpyext moved to /development/cpyext, alongside the invariant that keeps CPython's machine code unchanged. (#623) by @gaborbernat.<a name="release-1-3-0-packaging"></a>
pp310, pp311) for Linux, macOS, and Windows. They carry LTO but skip the profile-guided optimization the CPython Linux wheels use, since a profile trained under PyPy measures cpyext rather than the C hot paths. (#623) by @gaborbernat.Add EncodingMatch.codec; data.decode(match.codec) reproduces what parse saw, where match.encoding corrupted or raised. (#622) by @gaborbernat.
<a name="release-1-2-0-added"></a>
EncodingMatch.codec; data.decode(match.codec) reproduces what parse saw, where match.encoding corrupted or raised. (#622) by @gaborbernat.<a name="release-1-2-0-fixed"></a>
file:// stylesheet URLs for xsl:import; Path.as_uri() bases now load sibling imports. (#618) by @gaborbernat.Linkify.skip_tags names before matching parsed HTML tags; CODE now skips <code> text. (#619) by @gaborbernat.<legend> child of a disabled <fieldset> in form_data() output. (#621) by @gaborbernat.koi8-u is KOI8-RU, and GBK 0x80 is the euro sign. The <meta> prescan, the content detector, and IncrementalParser now follow the spec too. (#622) by @gaborbernat.<a name="release-1-2-0-breaking-changes"></a>
detect reports windows-1252, not ascii, for pure-ASCII input; EncodingMatch gained a trailing codec field; and IncrementalParser takes WHATWG labels, so latin-1 raises where iso-8859-1 works. (#622) by @gaborbernat.Add EncodingMatch.codec; data.decode(match.codec) reproduces what turbohtml.parse saw, where match.encoding corrupted or raised. (622) by gaborbernat.
Lock free-threaded DOM tree reads and attribute views; concurrent mutation no longer crashes those readers. (617) by gaborbernat.
Resolve local file:// stylesheet URLs for xsl:import; Path.as_uri() bases now load sibling imports. (618) by gaborbernat.
Normalize configured Linkify.skip_tags names before matching parsed HTML tags; CODE now skips <code> text. (619) by gaborbernat.
Keep controls inside the first <legend> child of a disabled <fieldset> in form_data() output. (621) by gaborbernat.
Decode legacy bytes with the WHATWG decoders rather than CPython's same-named codecs, whose tables and error handling both differ: koi8-u is KOI8-RU, and GBK 0x80 is the euro sign. The <meta> prescan, the content detector, and ~turbohtml.IncrementalParser now follow the spec too. (622) by gaborbernat.
turbohtml.detect.detect reports windows-1252, not ascii, for pure-ASCII input; ~turbohtml.detect.EncodingMatch gained a trailing codec field; and ~turbohtml.IncrementalParser takes WHATWG labels, so latin-1 raises where iso-8859-1 works. (622) by gaborbernat.
🐍 PyPI release 📜 Full Changelog
Policy gained strip_template_markers: with it on, sanitizing collapses template-engine expressions ({{ }}, ${ }, <% %>) in kept text and attribute val
<a name="release-1-1-0-added"></a>
Policy gained strip_template_markers: with it on, sanitizing collapses template-engine expressions ({{ }}, ${ }, <% %>) in kept text and attribute values to a single space, so the output cannot re-inject when a template engine renders it. This matches DOMPurify's SAFE_FOR_TEMPLATES. (#527) by @gaborbernat.sanitize_report (and sanitize_report) sanitize a fragment and return what the policy dropped alongside the cleaned HTML: one Removed record per removed element or stripped attribute, in walk order. This matches DOMPurify's DOMPurify.removed. (#528) by @gaborbernat.css_specificity returns the (a, b, c) specificity of each selector in a comma-separated list, per CSS Selectors Level 4 §17, the value cssselect exposes as Selector.specificity(). It weighs the parsed selector in one C pass, with :is()/:not()/:has() taking their most specific argument and :where() contributing zero. (#529) by @gaborbernat.feed normalizes an RSS 2.0, Atom 1.0, or RDF/RSS-1.0 document into one frozen, typed Feed of Entry records, the feedparser.parse entry point over feed. It detects the format from the root element and maps each dialect's spelling of a field -- the entry title, link, id, updated/published, summary/content, and author -- onto one shape in a single C walk of the parsed tree, over 12x faster than feedparser on a 30-item feed. (#530) by @gaborbernat.Policy gains transform_tags: a map that renames elements while sanitizing, sanitize-html's transformTags. Map a source tag to a string to rename it, or to a Transform to rename it and add attributes (sanitize-html's simpleTransform). The rename runs before the allowlist in the same C walk, so the renamed element is re-checked from scratch -- a transform decides an element's name but never its safety: mapping a tag to script still drops it, and an added attribute is scrubbed like the element's own. (#531) by @gaborbernat.saxparse module adds a DOM-less, event-driven parse. sax_parse drives a document through the WHATWG tree builder and fires a callback on a SaxHandler subclass for each construct it builds -- a start tag, an end tag, a run of text, a comment, the doctype, and a <?...> processing instruction -- while iter_events yields the same stream as typed records. The events reflect the fully spec-correct tree (implied html/head/body, foster parenting, the adoption agency), so unlike HTMLParser you see the tree the parser built; no per-node Python object is created and nothing is retained after the parse, so a one-pass extraction never builds a document-sized object graph. The tokenization, tree construction, and walk all run in C. (#532) by @gaborbernat.turbohtml.clean.Policy gains allowed_styles, a per-element, per-property value allowlist for the style attribute keyed {tag: {property: [pattern, ...]}} with "*" matching every tag. A declaration survives only when its value matches one of the property's patterns, porting sanitize-html's allowedStyles. It narrows css_properties by value and never weakens the baseline that drops expression() and disallowed-scheme url(). (#533) by @gaborbernat.Policy gained isolate_named_props: with it on, sanitizing prefixes every kept id and name value with user-content-, moving it out of the property namespace so it cannot shadow a built-in document or form property through named access (DOM clobbering, where <input name="attributes"> makes form.attributes resolve to the input and <img name="body"> hides document.body). An already-prefixed value is left alone, so re-sanitizing is a fixpoint. This matches DOMPurify's SANITIZE_NAMED_PROPS. (#534) by @gaborbernat.Html gained xml: with xml=True, serialize, encode, and serialize_iter emit XML/XHTML instead of HTML -- the equivalent of lxml's tostring(method="xml"). Every empty element self-closes (<br/>), foreign SVG and MathML subtrees carry their namespace declarations, and text and attribute values follow the XML escaping rules, with no HTML void-element or raw-text special casing. It composes with sort_attributes and an Indent layout. (#535) by @gaborbernat.Policy gained a predicate-based custom-element allowance and split content profiles, porting DOMPurify's CUSTOM_ELEMENT_HANDLING and USE_PROFILES. custom_element_check keeps an unlisted hyphenated custom element (my-widget, x-card) when a caller-supplied matcher admits its name, custom_attribute_check extends the same idea to that element's attributes, and allow_customized_builtins keeps an is attribute whose value names a custom element. allow_html, allow_svg, and allow_mathml gate each namespace independently, so a policy can keep SVG but drop MathML, or the reverse. All of it runs in the one C sanitize walk, and the non-configurable safety baseline -- on* handlers, javascript: URLs, unsafe tags -- still applies to whatever a matcher keeps. (#536) by @gaborbernat.transform adds a full XSLT 1.0 processor, the job lxml's etree.XSLT does. Transform compiles a stylesheet (parsed with parse_xml) and applies it to source documents, and transform does both in one call. The whole transform runs in the C extension, reusing turbohtml's XPath 1.0 engine for every match pattern and select expression. It covers the entire XSLT 1.0 instruction set: templates with match/name/mode/priority, apply-templates with sort and with-param, call-template, for-each, if, choose, value-of, copy/copy-of, element/ attribute/text, variable/param, multi-level number, key with the key() function, strip-space/preserve-space, attribute-set with use-attribute-sets, namespace-alias, fallback, simplified literal-result-element stylesheets, xsl:import with import precedence (resolved against a base_url), cdata-section-elements, and the xml/html/text output methods (html auto-selected for a null-namespace html root, with <meta> injection). Validated against libxslt's XSLT 1.0 Recommendation corpus at 76 of 79 cases byte-for-byte; the three remaining need a locale-collation, DTD, or XPath-namespace-axis layer turbohtml does not carry. (#537) by @gaborbernat.canonicalize serializes a subtree to Canonical XML (c14n), the byte-exact form an XML signature signs. A Canonical config selects the algorithm: Canonical XML 1.0 or 1.1, the exclusive variant that renders only the namespaces a subtree visibly uses, the with-comments variant, and an inclusive_ns_prefixes prefix list for exclusive mode. Attributes are reordered (namespace declarations first, then by namespace URI and local name), redundant namespace declarations are dropped, empty elements are written as start-end pairs, and character references are normalized, matching lxml's tostring(method="c14n") byte-for-byte over the same infoset. (#538) by @gaborbernat.XMLSchema and RelaxNG validate a document parsed with parse_xml against an XSD 1.0 or RELAX NG schema, mirroring lxml's etree.XMLSchema / etree.RelaxNG. A schema compiles once in the C core and each validate returns a ValidationResult -- a valid flag plus one ValidationError per violation, each with the document-order path that located it. XSD covers the element/attribute declarations, the sequence/choice/all content models with minOccurs/maxOccurs, references, complex/simple types with extension, the built-in datatypes, and the constraining facets; RELAX NG covers the full XML-syntax pattern set (including interleave) through the derivative algorithm. (#539) by @gaborbernat.parse_xml parses a document under XML 1.0 well-formedness instead of the WHATWG HTML tree builder, returning the same navigable Document. Names stay case-sensitive, <x/> self-closes any element, CDATA sections and processing instructions become CData and ProcessingInstruction nodes, only the five predefined entities and numeric references resolve, and a namespace prefix must be declared with xmlns. Names follow the exact XML 1.0 NameStartChar /NameChar productions, and the Namespaces in XML 1.0 well-formedness constraints hold in full: the reserved xml and xmlns prefixes and their namespace names cannot be rebound, a prefix declaration cannot be empty, a processing-instruction target carries no colon, and no two attributes share an expanded name. There is no HTML recovery: the first well-formedness violation -- a mismatched or unclosed tag, an undeclared prefix, an undefined entity, a duplicate attribute -- raises HTMLParseError. This is the equivalent of lxml.etree.fromstring / etree.XMLParser over turbohtml's dependency-free, fully typed node API. (#540) by @gaborbernat.check walks a parsed document and returns a ConformanceReport -- a valid verdict plus every ConformanceMessage, each carrying a stable code, a severity ("error", "warning", or "info"), a human-readable message, and a source line and column. It flags the document-conformance requirements the parser does not raise as a ParseError: a missing img alt, obsolete presentational elements and attributes, duplicate ids, invalid or redundant ARIA roles, empty headings, a section without a heading, and a document with no title or lang. The document is valid exactly when nothing is an error, so warnings and info notes never change the verdict. The whole walk runs in the C core against the WHATWG authoring rules and WAI-ARIA 1.2, the model the Nu Html Checker (validator.nu) uses; check_html parses a markup string first. (#541) by @gaborbernat.xpath gained the string subset of XPath 2.0: ends-with, string-join(seq, sep), lower-case and upper-case (Unicode case mapping), and the regex matches(input, pattern[, flags]) and replace(input, pattern, repl[, flags]) spellings, where replace reads $1-style group references and rewrites every match. They dispatch in the compiled-C engine alongside the XPath 1.0 core and the EXSLT namespaces, so an expression ported from elementpath, lxml, or htmlquery that leans on them runs without registration. (#542) by @gaborbernat.normalize returns text in a Unicode normalization form (UAX #15) -- NFC, NFD, NFKC, or NFKD -- the C successor to normalize, and is_normalized tests membership. Both run over tables generated from the interpreter's own unicodedata, so they agree with it exactly, and a quick check returns already-normalized text without allocating. (#543) by @gaborbernat.rewrite transforms HTML in a single streaming pass without building a tree, the model Cloudflare's lol-html popularized. It runs the WHATWG tokenizer over the input while tracking only the open-element stack, hands each element a CSS selector matches -- and, on request, each run of text, each comment, and the doctype -- to a Python handler that edits it in place (set or remove an attribute, insert markup before, after, or around it, replace its inner content, unwrap it, or drop it), and emits the result incrementally. Working memory stays proportional to the open-element depth, not the document size, so a multi-megabyte page rewrites in a fixed footprint, and an untouched construct is reproduced verbatim. Because the pass never looks ahead, the matchable selector subset is the one decidable from an element and its ancestors -- type, universal, id, class, and attribute selectors, the descendant and child combinators, :root, and :is()/:where()/:not() over that subset; a sibling combinator, a positional or structural pseudo-class, or :has() raises SelectorSyntaxError. (#544) by @gaborbernat.treebuild module retargets the parser at a tree of your own. parse_into runs the WHATWG tree builder and drives a builder object -- a create_* method per node kind plus an append that links a child under its parent -- to construct the tree directly, returning whatever the builder made its document root. No navigable Node is materialized and the tree is walked only once, so an index, a diff tree, or another library's nodes is populated straight from the parse rather than by a second descent. Each element carries its namespace URI and its attributes as (name, value) pairs, a <template>'s content is appended under the template handle, and a bogus <?...> construct reaches a distinct create_pi. This is Rust html5ever's TreeSink and Node parse5's TreeAdapter in turbohtml shape; the tree construction, the walk, and the string extraction all run in C. (#545) by @gaborbernat.cssom runs the CSS Object Model cascade: computed_style resolves the getComputedStyle of an element by collecting every <style> sheet plus the inline style along its ancestor chain, matching the native selector engine, ordering the declarations by origin importance, the style attribute, specificity, and source order, then applying inheritance, shorthand expansion, and each property's initial value -- all in the C core under the per-tree critical section. Alongside it, StyleSheet, RuleList, StyleRule, and StyleDeclaration are the read-only, turbohtml-native spelling of the CSSOM CSSStyleSheet / CSSRuleList / CSSStyleRule / CSSStyleDeclaration interfaces. The returned value is the computed value, not the used value: turbohtml runs no layout, so lengths and percentages come back as written, the same boundary jsdom and cssstyle draw. Shorthand expansion covers the distributive families (margin, padding, border-width/style/color, overflow) and the <line-width> || <line-style> || <color> shorthands border, each border-<side>, and outline, whose components resolve in any order and reset every longhand they cover. (#546) by @gaborbernat.to_source losslessly serializes a tree back to HTML, re-emitting the verbatim source bytes of every element and text run a parse left untouched and reserializing only the parts a mutation changed. Parse with source_locations=True and an unedited round trip reproduces the input byte for byte -- author quoting, tag-name case, character-reference spelling, and insignificant whitespace intact -- for markup that parsed without implied elements or content reordering; after an edit only the changed node's markup is rewritten while every untouched sibling and subtree keeps its original span. It is the tree-based counterpart to the streaming rewrite, the model Cloudflare's lol-html popularized. (#547) by @gaborbernat.parse, parse_fragment, and IncrementalParser gained a source_locations flag (default False) that records the granular source spans parse5 exposes as sourceCodeLocationInfo. With it on, each element's source_location returns a SourceLocation giving the SourceSpan of its start tag, its end tag (None when the source never closed it), and each attribute's whole name="value", every span carrying start/end line, column, and code-point offset so source[start_offset:end_offset] slices the construct out. The tokenizer stamps the spans in C as it runs and the tree builder hangs the record off each element, so the feature is zero-overhead when off; it implies positions when on, keeping source_line and position available beside the spans. (#548) by @gaborbernat.<template> carrying a shadowrootmode of open or closed on a valid shadow host, it attaches a shadow root to the template's parent and parses the template's content into it, reusing the Shadow DOM tree model -- the template element never joins the light tree. shadowrootdelegatesfocus and shadowrootclonable set the matching flags, readable as the new delegates_focus and clonable properties. Following the WHATWG per-document flag, parse honors declarative shadow roots by default (a browser navigation) while parse_fragment does not (an innerHTML assignment); the new allow_declarative_shadow_roots argument flips either default, matching setHTMLUnsafe when turned on for a fragment. (#549) by @gaborbernat.TreeWalker and NodeIterator, with the NodeFilter constants for the what_to_show bitmask and the filter verdicts. A TreeWalker is a movable cursor over a subtree -- parent_node, first_child, last_child, next_sibling, previous_sibling, next_node, previous_node -- while a NodeIterator is the flat, filtered forward/backward view and iterates directly in a for loop. Both take a what_to_show node-type mask and an optional filter callback returning FILTER_ACCEPT, FILTER_REJECT, or FILTER_SKIP; reject drops a node and its whole subtree while skip drops only the node, so a TreeWalker prunes where a NodeIterator (having no subtree) treats the two alike. The state machine and the what_to_show test run in the C core; the filter is the one callback into Python. This ports traversal code written against the browser DOM or jsdom. (#550) by @gaborbernat.parse and parse_fragment gained a scripting flag (default False). With it on, turbohtml sets the WHATWG scripting flag: <noscript> becomes a raw-text element, so its content is one text run rather than parsed markup and serializes back unescaped, reproducing the tree a scripting browser builds. The flag is a property of the parsed tree, so the serializer and inner_html stay consistent with how it was parsed. parse5 and html5ever default this on for browser fidelity; turbohtml keeps it off so <noscript> fallback content stays navigable. (#551) by @gaborbernat.Range and StaticRange types. A Range holds two boundary points -- each a (container, offset) pair -- and carries the full boundary API (set_start/set_end and their _before/_after variants, select_node, select_node_contents, collapse), the derived collapsed and common_ancestor_container properties, the comparisons (compare_boundary_points, compare_point, is_point_in_range, intersects_node), and the content operations (clone_contents, extract_contents, delete_contents, insert_node, surround_contents, clone_range), each following the WHATWG boundary-point ordering and extract/clone/delete algorithms in C under the per-tree critical section. StaticRange is the immutable four-value snapshot. Offsets index code points in character data and children elsewhere, so a Python string's own indexing lines up with a text-node offset. (#552) by @gaborbernat.attach_shadow attaches an open or closed shadow tree and returns a ShadowRoot -- a document-fragment-like root held off the light tree, so it never appears among the host's children or in its serialization -- reachable through shadow_root (None for a closed root) and carrying mode, host, set_inner_html, and append. <slot> elements assign the host's children by name (the unnamed default slot takes the rest): assigned_nodes and assigned_elements read what a slot received, with a flatten option that falls back to a slot's own children and expands nested shadow slots, and assigned_slot gives the slot a child landed in. flattened_children returns the composed tree with every slot replaced by its assigned nodes. The assignment and flattening algorithms run in C under the per-tree critical section and are computed on demand, so they always reflect the current tree. (#553) by @gaborbernat.MutationObserver, a synchronous take on the DOM MutationObserver for recording tree edits. Register a node with observe and the DOM options (child_list, attributes, character_data, subtree, attribute_old_value, character_data_old_value, attribute_filter); every change made through the mutation API queues a MutationRecord carrying the added and removed nodes, the surrounding siblings, and the attribute name and old value when asked, following the WHATWG "queue a mutation record" algorithm in C under the per-tree critical section. Because turbohtml has no event loop, delivery is synchronous rather than microtask-scheduled: take_records returns and clears the queued batch, and deliver drains it and calls the observer's callback. disconnect stops observing and discards pending records. (#554) by @gaborbernat.Policy gained xml: with it on, the sanitizer serializes the cleaned tree as well-formed XML/XHTML instead of HTML. Every kept empty element self-closes (<br/>), foreign SVG and MathML subtrees declare their namespace, text and attribute values follow the XML escaping rules, and a kept comment, a control character outside XML's Char production, or an attribute name XML cannot hold is neutralized, so the output always reparses through parse_xml. The walk and the safety baseline are unchanged, so an XML-mode policy is exactly as safe as its HTML-mode twin. This clones DOMPurify's PARSER_MEDIA_TYPE: 'application/xhtml+xml' and replaces the brittle .replace("<br>", "<br/>") a bleach-based cleaner needs to feed a strict XHTML consumer such as Reportlab's RML. inner_xml exposes the same children-only XML serialization for any node. (#565) by @gaborbernat.rewrite benchmark now runs against a fair in-process peer. lxml and BeautifulSoup do the same edits -- rel=nofollow on every link, loading=lazy on every image, every comment dropped -- through the parse, mutate, and serialize round trip that rewrite skips, and the table reports each party's peak resident memory beside throughput, so the tree the streaming rewriter never builds shows up as memory it never holds. The lol-html migration guide carries the numbers. (#612) by @gaborbernat.~turbohtml.clean.Policy gained strip_template_markers: with it on, sanitizing collapses template-engine expressions ({{ }}, ${ }, <% %>) in kept text and attribute values to a single space, so the output cannot re-inject when a template engine renders it. This matches DOMPurify's SAFE_FOR_TEMPLATES. (527) by gaborbernat.
turbohtml.clean.sanitize_report (and turbohtml.clean.Sanitizer.sanitize_report) sanitize a fragment and return what the policy dropped alongside the cleaned HTML: one turbohtml.clean.Removed record per removed element or stripped attribute, in walk order. This matches DOMPurify's DOMPurify.removed. (528) by gaborbernat.
turbohtml.convert.css_specificity returns the (a, b, c) specificity of each selector in a comma-separated list, per CSS Selectors Level 4 §17, the value cssselect exposes as Selector.specificity(). It weighs the parsed selector in one C pass, with :is()/:not()/:has() taking their most specific argument and :where() contributing zero. (529) by gaborbernat.
turbohtml.extract.feed normalizes an RSS 2.0, Atom 1.0, or RDF/RSS-1.0 document into one frozen, typed ~turbohtml.extract.Feed of ~turbohtml.extract.Entry records, the feedparser.parse entry point over turbohtml.Document.feed. It detects the format from the root element and maps each dialect's spelling of a field -- the entry title, link, id, updated/published, summary/content, and author -- onto one shape in a single C walk of the parsed tree, over 12x faster than feedparser on a 30-item feed. (530) by gaborbernat.
turbohtml.clean.Policy gains transform_tags: a map that renames elements while sanitizing, sanitize-html's transformTags. Map a source tag to a string to rename it, or to a turbohtml.clean.Transform to rename it and add attributes (sanitize-html's simpleTransform). The rename runs before the allowlist in the same C walk, so the renamed element is re-checked from scratch -- a transform decides an element's name but never its safety: mapping a tag to script still drops it, and an added attribute is scrubbed like the element's own. (531) by gaborbernat.
A new turbohtml.saxparse module adds a DOM-less, event-driven parse. turbohtml.saxparse.sax_parse drives a document through the WHATWG tree builder and fires a callback on a turbohtml.saxparse.SaxHandler subclass for each construct it builds -- a start tag, an end tag, a run of text, a comment, the doctype, and a <?...> processing instruction -- while turbohtml.saxparse.iter_events yields the same stream as typed records. The events reflect the fully spec-correct tree (implied html/head/body, foster parenting, the adoption agency), so unlike html.parser.HTMLParser you see the tree the parser built; no per-node Python object is created and nothing is retained after the parse, so a one-pass extraction never builds a document-sized object graph. The tokenization, tree construction, and walk all run in C. (532) by gaborbernat.
turbohtml.clean.Policy gains allowed_styles, a per-element, per-property value allowlist for the style attribute keyed {tag: {property: [pattern, ...]}} with "*" matching every tag. A declaration survives only when its value matches one of the property's patterns, porting sanitize-html's allowedStyles. It narrows css_properties by value and never weakens the baseline that drops expression() and disallowed-scheme url(). (533) by gaborbernat.
~turbohtml.clean.Policy gained isolate_named_props: with it on, sanitizing prefixes every kept id and name value with user-content-, moving it out of the property namespace so it cannot shadow a built-in document or form property through named access (DOM clobbering, where <input name="attributes"> makes form.attributes resolve to the input and <img name="body"> hides document.body). An already-prefixed value is left alone, so re-sanitizing is a fixpoint. This matches DOMPurify's SANITIZE_NAMED_PROPS. (534) by gaborbernat.
~turbohtml.Html gained xml: with xml=True, ~turbohtml.Node.serialize, ~turbohtml.Node.encode, and ~turbohtml.Node.serialize_iter emit XML/XHTML instead of HTML -- the equivalent of lxml's tostring(method="xml"). Every empty element self-closes (<br/>), foreign SVG and MathML subtrees carry their namespace declarations, and text and attribute values follow the XML escaping rules, with no HTML void-element or raw-text special casing. It composes with sort_attributes and an ~turbohtml.Indent layout. (535) by gaborbernat.
~turbohtml.clean.Policy gained a predicate-based custom-element allowance and split content profiles, porting DOMPurify's CUSTOM_ELEMENT_HANDLING and USE_PROFILES. custom_element_check keeps an unlisted hyphenated custom element (my-widget, x-card) when a caller-supplied matcher admits its name, custom_attribute_check extends the same idea to that element's attributes, and allow_customized_builtins keeps an is attribute whose value names a custom element. allow_html, allow_svg, and allow_mathml gate each namespace independently, so a policy can keep SVG but drop MathML, or the reverse. All of it runs in the one C sanitize walk, and the non-configurable safety baseline -- on* handlers, javascript: URLs, unsafe tags -- still applies to whatever a matcher keeps. (536) by gaborbernat.
turbohtml.transform adds a full XSLT 1.0 processor, the job lxml's etree.XSLT does. turbohtml.transform.Transform compiles a stylesheet (parsed with turbohtml.parse_xml) and applies it to source documents, and turbohtml.transform.transform does both in one call. The whole transform runs in the C extension, reusing turbohtml's XPath 1.0 engine for every match pattern and select expression. It covers the entire XSLT 1.0 instruction set: templates with match/name/mode/priority, apply-templates with sort and with-param, call-template, for-each, if, choose, value-of, copy/copy-of, element/ attribute/text, variable/param, multi-level number, key with the key() function, strip-space/preserve-space, attribute-set with use-attribute-sets, namespace-alias, fallback, simplified literal-result-element stylesheets, xsl:import with import precedence (resolved against a base_url), cdata-section-elements, and the xml/html/text output methods (html auto-selected for a null-namespace html root, with <meta> injection). Validated against libxslt's XSLT 1.0 Recommendation corpus at 76 of 79 cases byte-for-byte; the three remaining need a locale-collation, DTD, or XPath-namespace-axis layer turbohtml does not carry. (537) by gaborbernat.
turbohtml.Node.canonicalize serializes a subtree to Canonical XML (c14n), the byte-exact form an XML signature signs. A turbohtml.Canonical config selects the algorithm: Canonical XML 1.0 or 1.1, the exclusive variant that renders only the namespaces a subtree visibly uses, the with-comments variant, and an inclusive_ns_prefixes prefix list for exclusive mode. Attributes are reordered (namespace declarations first, then by namespace URI and local name), redundant namespace declarations are dropped, empty elements are written as start-end pairs, and character references are normalized, matching lxml's tostring(method="c14n") byte-for-byte over the same infoset. (538) by gaborbernat.
turbohtml.validate.XMLSchema and turbohtml.validate.RelaxNG validate a document parsed with turbohtml.parse_xml against an XSD 1.0 or RELAX NG schema, mirroring lxml's etree.XMLSchema / etree.RelaxNG. A schema compiles once in the C core and each ~turbohtml.validate.XMLSchema.validate returns a ~turbohtml.validate.ValidationResult -- a valid flag plus one ~turbohtml.validate.ValidationError per violation, each with the document-order path that located it. XSD covers the element/attribute declarations, the sequence/choice/all content models with minOccurs/maxOccurs, references, complex/simple types with extension, the built-in datatypes, and the constraining facets; RELAX NG covers the full XML-syntax pattern set (including interleave) through the derivative algorithm. (539) by gaborbernat.
turbohtml.parse_xml parses a document under XML 1.0 well-formedness instead of the WHATWG HTML tree builder, returning the same navigable ~turbohtml.Document. Names stay case-sensitive, <x/> self-closes any element, CDATA sections and processing instructions become ~turbohtml.CData and ~turbohtml.ProcessingInstruction nodes, only the five predefined entities and numeric references resolve, and a namespace prefix must be declared with xmlns. Names follow the exact XML 1.0 NameStartChar /NameChar productions, and the Namespaces in XML 1.0 well-formedness constraints hold in full: the reserved xml and xmlns prefixes and their namespace names cannot be rebound, a prefix declaration cannot be empty, a processing-instruction target carries no colon, and no two attributes share an expanded name. There is no HTML recovery: the first well-formedness violation -- a mismatched or unclosed tag, an undeclared prefix, an undefined entity, a duplicate attribute -- raises ~turbohtml.HTMLParseError. This is the equivalent of lxml.etree.fromstring / etree.XMLParser over turbohtml's dependency-free, fully typed node API. (540) by gaborbernat.
Added an HTML5 authoring-conformance checker with a severity model. turbohtml.conformance.check walks a parsed document and returns a ~turbohtml.conformance.ConformanceReport -- a valid verdict plus every ~turbohtml.conformance.ConformanceMessage, each carrying a stable code, a severity ("error", "warning", or "info"), a human-readable message, and a source line and column. It flags the document-conformance requirements the parser does not raise as a ~turbohtml.ParseError: a missing img alt, obsolete presentational elements and attributes, duplicate ids, invalid or redundant ARIA roles, empty headings, a section without a heading, and a document with no title or lang. The document is valid exactly when nothing is an error, so warnings and info notes never change the verdict. The whole walk runs in the C core against the WHATWG authoring rules and WAI-ARIA 1.2, the model the Nu Html Checker (validator.nu) uses; ~turbohtml.conformance.check_html parses a markup string first. (541) by gaborbernat.
~turbohtml.Node.xpath gained the string subset of XPath 2.0: ends-with, string-join(seq, sep), lower-case and upper-case (Unicode case mapping), and the regex matches(input, pattern[, flags]) and replace(input, pattern, repl[, flags]) spellings, where replace reads $1-style group references and rewrites every match. They dispatch in the compiled-C engine alongside the XPath 1.0 core and the EXSLT namespaces, so an expression ported from elementpath, lxml, or htmlquery that leans on them runs without registration. (542) by gaborbernat.
turbohtml.detect.normalize returns text in a Unicode normalization form (UAX #15) -- NFC, NFD, NFKC, or NFKD -- the C successor to python:unicodedata.normalize, and turbohtml.detect.is_normalized tests membership. Both run over tables generated from the interpreter's own unicodedata, so they agree with it exactly, and a quick check returns already-normalized text without allocating. (543) by gaborbernat.
turbohtml.rewrite.rewrite transforms HTML in a single streaming pass without building a tree, the model Cloudflare's lol-html popularized. It runs the WHATWG tokenizer over the input while tracking only the open-element stack, hands each element a CSS selector matches -- and, on request, each run of text, each comment, and the doctype -- to a Python handler that edits it in place (set or remove an attribute, insert markup before, after, or around it, replace its inner content, unwrap it, or drop it), and emits the result incrementally. Working memory stays proportional to the open-element depth, not the document size, so a multi-megabyte page rewrites in a fixed footprint, and an untouched construct is reproduced verbatim. Because the pass never looks ahead, the matchable selector subset is the one decidable from an element and its ancestors -- type, universal, id, class, and attribute selectors, the descendant and child combinators, :root, and :is()/:where()/:not() over that subset; a sibling combinator, a positional or structural pseudo-class, or :has() raises ~turbohtml.SelectorSyntaxError. (544) by gaborbernat.
A new turbohtml.treebuild module retargets the parser at a tree of your own. turbohtml.treebuild.parse_into runs the WHATWG tree builder and drives a builder object -- a create_* method per node kind plus an append that links a child under its parent -- to construct the tree directly, returning whatever the builder made its document root. No navigable turbohtml.Node is materialized and the tree is walked only once, so an index, a diff tree, or another library's nodes is populated straight from the parse rather than by a second descent. Each element carries its namespace URI and its attributes as (name, value) pairs, a <template>'s content is appended under the template handle, and a bogus <?...> construct reaches a distinct create_pi. This is Rust html5ever's TreeSink and Node parse5's TreeAdapter in turbohtml shape; the tree construction, the walk, and the string extraction all run in C. (545) by gaborbernat.
turbohtml.cssom runs the CSS Object Model cascade: ~turbohtml.cssom.computed_style resolves the getComputedStyle of an element by collecting every <style> sheet plus the inline style along its ancestor chain, matching the native selector engine, ordering the declarations by origin importance, the style attribute, specificity, and source order, then applying inheritance, shorthand expansion, and each property's initial value -- all in the C core under the per-tree critical section. Alongside it, ~turbohtml.cssom.StyleSheet, ~turbohtml.cssom.RuleList, ~turbohtml.cssom.StyleRule, and ~turbohtml.cssom.StyleDeclaration are the read-only, turbohtml-native spelling of the CSSOM CSSStyleSheet / CSSRuleList / CSSStyleRule / CSSStyleDeclaration interfaces. The returned value is the computed value, not the used value: turbohtml runs no layout, so lengths and percentages come back as written, the same boundary jsdom and cssstyle draw. Shorthand expansion covers the distributive families (margin, padding, border-width/style/color, overflow) and the <line-width> || <line-style> || <color> shorthands border, each border-<side>, and outline, whose components resolve in any order and reset every longhand they cover. (546) by gaborbernat.
turbohtml.Node.to_source losslessly serializes a tree back to HTML, re-emitting the verbatim source bytes of every element and text run a parse left untouched and reserializing only the parts a mutation changed. Parse with source_locations=True and an unedited round trip reproduces the input byte for byte -- author quoting, tag-name case, character-reference spelling, and insignificant whitespace intact -- for markup that parsed without implied elements or content reordering; after an edit only the changed node's markup is rewritten while every untouched sibling and subtree keeps its original span. It is the tree-based counterpart to the streaming turbohtml.rewrite.rewrite, the model Cloudflare's lol-html popularized. (547) by gaborbernat.
turbohtml.parse, turbohtml.parse_fragment, and ~turbohtml.IncrementalParser gained a source_locations flag (default False) that records the granular source spans parse5 exposes as sourceCodeLocationInfo. With it on, each element's ~turbohtml.Node.source_location returns a ~turbohtml.SourceLocation giving the ~turbohtml.SourceSpan of its start tag, its end tag (None when the source never closed it), and each attribute's whole name="value", every span carrying start/end line, column, and code-point offset so source[start_offset:end_offset] slices the construct out. The tokenizer stamps the spans in C as it runs and the tree builder hangs the record off each element, so the feature is zero-overhead when off; it implies positions when on, keeping ~turbohtml.Node.source_line and ~turbohtml.Node.position available beside the spans. (548) by gaborbernat.
Added declarative Shadow DOM to the parser. When the tree builder meets a <template> carrying a shadowrootmode of open or closed on a valid shadow host, it attaches a shadow root to the template's parent and parses the template's content into it, reusing the Shadow DOM tree model -- the template element never joins the light tree. shadowrootdelegatesfocus and shadowrootclonable set the matching flags, readable as the new ~turbohtml.ShadowRoot.delegates_focus and ~turbohtml.ShadowRoot.clonable properties. Following the WHATWG per-document flag, turbohtml.parse honors declarative shadow roots by default (a browser navigation) while turbohtml.parse_fragment does not (an innerHTML assignment); the new allow_declarative_shadow_roots argument flips either default, matching setHTMLUnsafe when turned on for a fragment. (549) by gaborbernat.
Added the DOM Living Standard traversal objects turbohtml.TreeWalker and turbohtml.NodeIterator, with the turbohtml.NodeFilter constants for the what_to_show bitmask and the filter verdicts. A TreeWalker is a movable cursor over a subtree -- parent_node, first_child, last_child, next_sibling, previous_sibling, next_node, previous_node -- while a NodeIterator is the flat, filtered forward/backward view and iterates directly in a for loop. Both take a what_to_show node-type mask and an optional filter callback returning FILTER_ACCEPT, FILTER_REJECT, or FILTER_SKIP; reject drops a node and its whole subtree while skip drops only the node, so a TreeWalker prunes where a NodeIterator (having no subtree) treats the two alike. The state machine and the what_to_show test run in the C core; the filter is the one callback into Python. This ports traversal code written against the browser DOM or jsdom. (550) by gaborbernat.
turbohtml.parse and turbohtml.parse_fragment gained a scripting flag (default False). With it on, turbohtml sets the WHATWG scripting flag: <noscript> becomes a raw-text element, so its content is one text run rather than parsed markup and serializes back unescaped, reproducing the tree a scripting browser builds. The flag is a property of the parsed tree, so the serializer and inner_html stay consistent with how it was parsed. parse5 and html5ever default this on for browser fidelity; turbohtml keeps it off so <noscript> fallback content stays navigable. (551) by gaborbernat.
Added the DOM Living Standard ~turbohtml.Range and ~turbohtml.StaticRange types. A Range holds two boundary points -- each a (container, offset) pair -- and carries the full boundary API (~turbohtml.Range.set_start/~turbohtml.Range.set_end and their _before/_after variants, ~turbohtml.Range.select_node, ~turbohtml.Range.select_node_contents, ~turbohtml.Range.collapse), the derived ~turbohtml.Range.collapsed and ~turbohtml.Range.common_ancestor_container properties, the comparisons (~turbohtml.Range.compare_boundary_points, ~turbohtml.Range.compare_point, ~turbohtml.Range.is_point_in_range, ~turbohtml.Range.intersects_node), and the content operations (~turbohtml.Range.clone_contents, ~turbohtml.Range.extract_contents, ~turbohtml.Range.delete_contents, ~turbohtml.Range.insert_node, ~turbohtml.Range.surround_contents, ~turbohtml.Range.clone_range), each following the WHATWG boundary-point ordering and extract/clone/delete algorithms in C under the per-tree critical section. StaticRange is the immutable four-value snapshot. Offsets index code points in character data and children elsewhere, so a Python string's own indexing lines up with a text-node offset. (552) by gaborbernat.
Added the DOM Living Standard Shadow DOM tree model. ~turbohtml.Element.attach_shadow attaches an open or closed shadow tree and returns a ~turbohtml.ShadowRoot -- a document-fragment-like root held off the light tree, so it never appears among the host's children or in its serialization -- reachable through ~turbohtml.Element.shadow_root (None for a closed root) and carrying ~turbohtml.ShadowRoot.mode, ~turbohtml.ShadowRoot.host, ~turbohtml.ShadowRoot.set_inner_html, and ~turbohtml.ShadowRoot.append. <slot> elements assign the host's children by name (the unnamed default slot takes the rest): ~turbohtml.Element.assigned_nodes and ~turbohtml.Element.assigned_elements read what a slot received, with a flatten option that falls back to a slot's own children and expands nested shadow slots, and ~turbohtml.Node.assigned_slot gives the slot a child landed in. ~turbohtml.Node.flattened_children returns the composed tree with every slot replaced by its assigned nodes. The assignment and flattening algorithms run in C under the per-tree critical section and are computed on demand, so they always reflect the current tree. (553) by gaborbernat.
Added ~turbohtml.MutationObserver, a synchronous take on the DOM MutationObserver for recording tree edits. Register a node with ~turbohtml.MutationObserver.observe and the DOM options (child_list, attributes, character_data, subtree, attribute_old_value, character_data_old_value, attribute_filter); every change made through the mutation API queues a ~turbohtml.MutationRecord carrying the added and removed nodes, the surrounding siblings, and the attribute name and old value when asked, following the WHATWG "queue a mutation record" algorithm in C under the per-tree critical section. Because turbohtml has no event loop, delivery is synchronous rather than microtask-scheduled: ~turbohtml.MutationObserver.take_records returns and clears the queued batch, and ~turbohtml.MutationObserver.deliver drains it and calls the observer's callback. ~turbohtml.MutationObserver.disconnect stops observing and discards pending records. (554) by gaborbernat.
~turbohtml.clean.Policy gained xml: with it on, the sanitizer serializes the cleaned tree as well-formed XML/XHTML instead of HTML. Every kept empty element self-closes (<br/>), foreign SVG and MathML subtrees declare their namespace, text and attribute values follow the XML escaping rules, and a kept comment, a control character outside XML's Char production, or an attribute name XML cannot hold is neutralized, so the output always reparses through turbohtml.parse_xml. The walk and the safety baseline are unchanged, so an XML-mode policy is exactly as safe as its HTML-mode twin. This clones DOMPurify's PARSER_MEDIA_TYPE: 'application/xhtml+xml' and replaces the brittle .replace("<br>", "<br/>") a bleach-based cleaner needs to feed a strict XHTML consumer such as Reportlab's RML. turbohtml.Node.inner_xml exposes the same children-only XML serialization for any node. (565) by gaborbernat.
The rewrite benchmark now runs against a fair in-process peer. lxml and BeautifulSoup do the same edits -- rel=nofollow on every link, loading=lazy on every image, every comment dropped -- through the parse, mutate, and serialize round trip that turbohtml.rewrite.rewrite skips, and the table reports each party's peak resident memory beside throughput, so the tree the streaming rewriter never builds shows up as memory it never holds. The lol-html migration guide carries the numbers. (612) by gaborbernat.
Query a tree with the full Selectors Level 4 grammar (:is(), :where(), :has(), :not(), :nth-child(An+B of S), the structural, input, :lang(), :dir(),
<a name="release-1-0-0-added"></a>
:is(), :where(), :has(), :not(), :nth-child(An+B of S), the structural, input, :lang(), :dir(), and :scope pseudo-classes) and an XPath 1.0 engine: xpath, a compiled reusable XPath, the EXSLT function set, and namespace, variable, and extension binding. A pyquery-style Query, a soupsieve-shaped matcher, and css_to_xpath cover the BeautifulSoup, cssselect, parsel, and pyquery surfaces. (#179) by @gaborbernat.serialize_iter), and minify HTML, CSS, and JavaScript through native engines under clean. Every transform is round-trip safe, replacing rcssmin, csscompressor, rjsmin, jsmin, minify-html, and htmlmin. (#343, #346) by @gaborbernat.(start, end, label) spans, and extract a page's main article, boilerplate paragraphs, publication date, tables, links, and structured data (JSON-LD, Microdata, RDFa, Dublin Core, Open Graph) through extract, replacing markdownify, html2text, inscriptis, trafilatura, readability, htmldate, extruct, and microdata. (#273, #276) by @gaborbernat.detect module, which reports confidence and a BOM label, covers 69 languages across nine scripts, and replaces chardet, charset-normalizer, and cchardet. (#315, #474) by @gaborbernat.IncrementalParser, read the WHATWG parse errors recovery swallows through errors, and locate each element in the source through source_line and source_col. (#210, #212) by @gaborbernat.Policy that is safe with no arguments and scrubs inline and embedded CSS, foreign namespaces, and media hosts, and auto-link URLs and email addresses, together replacing bleach. (#8, #9) by @gaborbernat.E and document, edit the class token set and inner HTML or text, wrap and unwrap subtrees, trim a document to a selector with prune, read and fill form fields, and compare two subtrees with equals. (#275, #225, #468) by @gaborbernat.extract, backed by a native URL pipeline (WHATWG splitting, percent-coding, relative-reference joining, UTS #46 IDNA, and Public Suffix List registrable-domain filtering), and run the toolkit from a turbohtml command line covering minify, detect, to-markdown, to-text, and sanitize. (#321, #470) by @gaborbernat.<a name="release-1-0-0-fixed"></a>
<meta> prescan. (#54, #423) by @gaborbernat.:is()/:where() lists, quirks-mode case folding, CSS escape decoding, namespace prefixes, whitespace-only :empty, and :scope resolution inside :has(). (#174) by @gaborbernat.<pre> leading newline, ordinal <li value>, and raw-text suppression in every namespace. (#384) by @gaborbernat.itemref merging, table rowspan bounds, and the WHATWG form select/optgroup submission rules. (#385, #408) by @gaborbernat.calc() type mixing, duplicate-declaration fallbacks, currentcolor, conditional folding, and adjacent-string-literal concatenation. (#415) by @gaborbernat.<a name="release-1-0-0-documentation"></a>
llms.txt maps, a sitemap, and per-page meta descriptions. (#478) by @gaborbernat.<a name="release-1-0-0-breaking-changes"></a>
turbohtml.match into query; the sanitizer, linkifier, and every minifier gather under clean; a malformed selector raises one SelectorSyntaxError from every parse path; the two Detector classes split into EncodingDetector and LinkDetector; and each surface with more than six arguments takes one frozen options config. (#478) by @gaborbernat.layout argument in place of indent, so serialize(indent=2) becomes serialize(layout=Indent(2)) and Minify selects minified output. (#171) by @gaborbernat.<x a>) as the empty string rather than None in attrs, matching the WHATWG tokenizer and the DOM. (#87) by @gaborbernat.<a name="release-1-0-0-security"></a>
<a name="release-1-0-0-performance"></a>
find several times faster, :has() evaluates in one amortized-linear pass, streaming serialization sizes its buffer up front, and link-time optimization re-inlines across a subsystem-first C layout. (#162, #509) by @gaborbernat.<a name="release-1-0-0-packaging"></a>
.so and 46 KB from the macOS bundle; the source distribution still carries every test, tool, and generated table needed to build from source. (#478) by @gaborbernat.Query a tree with the full Selectors Level 4 grammar (:is(), :where(), :has(), :not(), :nth-child(An+B of S), the structural, input, :lang(), :dir(), and :scope pseudo-classes) and an XPath 1.0 engine: ~turbohtml.Node.xpath, a compiled reusable turbohtml.XPath, the EXSLT function set, and namespace, variable, and extension binding. A pyquery-style turbohtml.query.Query, a soupsieve-shaped matcher, and turbohtml.convert.css_to_xpath cover the BeautifulSoup, cssselect, parsel, and pyquery surfaces. (179) by gaborbernat.
Serialize back to HTML with pretty-print, whitespace minification, and lazy streaming (~turbohtml.Node.serialize_iter), and minify HTML, CSS, and JavaScript through native engines under turbohtml.clean. Every transform is round-trip safe, replacing rcssmin, csscompressor, rjsmin, jsmin, minify-html, and htmlmin. (343, 346) by gaborbernat.
Convert a tree to GitHub-Flavored Markdown, layout-aware text, or annotated (start, end, label) spans, and extract a page's main article, boilerplate paragraphs, publication date, tables, links, and structured data (JSON-LD, Microdata, RDFa, Dublin Core, Open Graph) through turbohtml.extract, replacing markdownify, html2text, inscriptis, trafilatura, readability, htmldate, extruct, and microdata. (273, 276) by gaborbernat.
Detect a byte stream's encoding and a text's natural language from the standalone turbohtml.detect module, which reports confidence and a BOM label, covers 69 languages across nine scripts, and replaces chardet, charset-normalizer, and cchardet. (315, 474) by gaborbernat.
Parse incrementally from a stream with turbohtml.IncrementalParser, read the WHATWG parse errors recovery swallows through ~turbohtml.Document.errors, and locate each element in the source through ~turbohtml.Node.source_line and ~turbohtml.Node.source_col. (210, 212) by gaborbernat.
Sanitize untrusted HTML against a frozen allowlist turbohtml.clean.Policy that is safe with no arguments and scrubs inline and embedded CSS, foreign namespaces, and media hosts, and auto-link URLs and email addresses, together replacing bleach. (8, 9) by gaborbernat.
Build and edit the tree in place: construct nodes and a whole HTML5 page with turbohtml.build.E and turbohtml.build.document, edit the class token set and inner HTML or text, wrap and unwrap subtrees, trim a document to a selector with ~turbohtml.Node.prune, read and fill form fields, and compare two subtrees with ~turbohtml.Node.equals. (275, 225, 468) by gaborbernat.
Clean, canonicalize, and extract page URLs through turbohtml.extract, backed by a native URL pipeline (WHATWG splitting, percent-coding, relative-reference joining, UTS #46 IDNA, and Public Suffix List registrable-domain filtering), and run the toolkit from a turbohtml command line covering minify, detect, to-markdown, to-text, and sanitize. (321, 470) by gaborbernat.
Bring tree construction to WHATWG conformance across foster parenting, foreign content, the select, table, and template insertion modes, doctype and quirks detection, duplicate and void-element handling, validated against the html5lib-tests corpus. (32) by gaborbernat.
Resolve every label in the WHATWG Encoding Standard, decode the replacement and gb18030 families and the windows-1252 C1 bytes, and honor the 1024-byte <meta> prescan. (54, 423) by gaborbernat.
Match the Selectors Level 4 corrections: forgiving :is()/:where() lists, quirks-mode case folding, CSS escape decoding, namespace prefixes, whitespace-only :empty, and :scope resolution inside :has(). (174) by gaborbernat.
Fix XPath 1.0 semantics: shortest round-tripping number formatting, half-to-positive-infinity rounding, fixed function arity, node-set typing, and arena-safe predicate compilation. (398) by gaborbernat.
Correct the Markdown and text exporters on nested and loose lists, link and image escaping, the <pre> leading newline, ordinal <li value>, and raw-text suppression in every namespace. (384) by gaborbernat.
Fix extraction on landmark-wrapped and list-structured articles, Microdata itemref merging, table rowspan bounds, and the WHATWG form select/optgroup submission rules. (385, 408) by gaborbernat.
Keep the CSS and JavaScript minifiers value-safe: calc() type mixing, duplicate-declaration fallbacks, currentcolor, conditional folding, and adjacent-string-literal concatenation. (415) by gaborbernat.
Raise a precise, typed error from every public failure path in place of a silent wrong result or a leaked low-level type, and document each callable's exceptions. (434) by gaborbernat.
Ship a migration guide for each library turbohtml replaces, every one carrying a monthly-downloads badge, a measured benchmark, and a speed-up multiplier, with the index ordered by adoption. (313) by gaborbernat.
Restructure the reference, how-to, and migration trees around the eight-namespace taxonomy (parse/DOM, detect, query, clean, convert, extract, build, serialize), and add llms.txt maps, a sitemap, and per-page meta descriptions. (478) by gaborbernat.
Add a written security policy, a "How turbohtml was built" page, and the seven design principles that shape the library. (500) by gaborbernat.
Give the public surface one name per concept. CSS matching folds from turbohtml.match into turbohtml.query; the sanitizer, linkifier, and every minifier gather under turbohtml.clean; a malformed selector raises one turbohtml.SelectorSyntaxError from every parse path; the two Detector classes split into turbohtml.detect.EncodingDetector and turbohtml.clean.LinkDetector; and each surface with more than six arguments takes one frozen options config. (478) by gaborbernat.
Select a serialization mode with a single layout argument in place of indent, so serialize(indent=2) becomes serialize(layout=Indent(2)) and ~turbohtml.Minify selects minified output. (171) by gaborbernat.
Report a valueless attribute (<x a>) as the empty string rather than None in turbohtml.Element.attrs, matching the WHATWG tokenizer and the DOM. (87) by gaborbernat.
Harden against untrusted input: ASan and UBSan fuzz gates on every entry point, a DOMPurify XSS oracle and an html5lib-tests tree-equality oracle over the sanitizer, mutation-XSS namespace checks, caps on element nesting and duplicate attributes, and one overflow-safe buffer-growth helper across the C core. (503, 511) by gaborbernat.
Speed the read path: a per-tree atom index runs a tag-pinned ~turbohtml.Node.find several times faster, :has() evaluates in one amortized-linear pass, streaming serialization sizes its buffer up front, and link-time optimization re-inlines across a subsystem-first C layout. (162, 509) by gaborbernat.
Build the release wheels with profile-guided, link-time optimization trained offline over a real-world corpus of clean, malformed, legacy-encoded, and structured-data markup. (481) by gaborbernat.
Pin every network-sourced C data table (IANA TLDs, the Public Suffix List, and the Unicode IDNA and NFC tables) to a named source commit and a SHA-256 checksum, so a rebuild is reproducible and aborts on a poisoned upstream. (478) by gaborbernat.
Strip the compiled extension's local symbol table from the release wheels at link time, trimming about 65 KB from the Linux .so and 46 KB from the macOS bundle; the source distribution still carries every test, tool, and generated table needed to build from source. (478) by gaborbernat.
Build and edit the tree, not just read it: construct Element, Text, and Comment nodes and rearrange them with the full set of insert, wrap, extract, a
<a name="release-0-4-0-added"></a>
Element, Text, and Comment nodes and rearrange them with the full set of insert, wrap, extract, and normalize methods, with attrs and .text/.data as live setters. copy, deepcopy, and pickle duplicate a subtree. (#19) by @gaborbernat.ProcessingInstruction and CData join the hierarchy, Doctype exposes its public_id and system_id, and every node type supports structural pattern matching. (#22) by @gaborbernat.<a name="release-0-4-0-documentation"></a>
Build and edit the tree, not just read it: construct ~turbohtml.Element, ~turbohtml.Text, and ~turbohtml.Comment nodes and rearrange them with the full set of insert, wrap, extract, and normalize methods, with ~turbohtml.Element.attrs and .text/.data as live setters. copy, deepcopy, and pickle duplicate a subtree. (19) by gaborbernat.
Round out the node model: ~turbohtml.ProcessingInstruction and ~turbohtml.CData join the hierarchy, ~turbohtml.Doctype exposes its ~turbohtml.Doctype.public_id and ~turbohtml.Doctype.system_id, and every node type supports structural pattern matching. (22) by gaborbernat.
Learn the write path through new tutorial, how-to, and explanation docs, backed by benchmarks showing turbohtml builds and rewrites trees about twice as fast as lxml and an order of magnitude faster than BeautifulSoup. (19) by gaborbernat.
Port to turbohtml with migration guides from BeautifulSoup, lxml, selectolax, html5lib, and the standard library, each mapping the source library's idioms to their turbohtml equivalents and flagging behavior differences. (23) by gaborbernat.
Query any node with CSS through select and select_one, a native matcher covering type, universal, #id, .class, and attribute selectors (all operators
<a name="release-0-3-0-added"></a>
select and select_one, a native matcher covering type, universal, #id, .class, and attribute selectors (all operators plus the case-sensitivity flag) across the descendant, child, adjacent, and sibling combinators, returning comma groups in document order. An invalid selector raises ValueError. (#14) by @gaborbernat.find and find_all filter grammar: match the tag and attributes by string, regex, bool, callable, or list (including class_ and the attrs mapping), and choose the search direction with the axis keyword. find_all takes a limit and returns a list. (#15) by @gaborbernat.matches and closest: matches() reports whether the node satisfies a CSS selector in context, and closest() returns the nearest matching ancestor (or the node itself), or None. (#16) by @gaborbernat.next_siblings, previous_siblings, document-order following and preceding, plus the strings and stripped_strings text iterators. (#17) by @gaborbernat.class, rel, headers, sizes, sandbox, and the rest) as a list[str] in attrs, split on ASCII whitespace; other attributes stay strings and valueless ones stay None. (#18) by @gaborbernat.inner_html returns the children, while serialize and encode take a formatter (the Formatter enum picks the escape policy) and an indent for pretty output. The default stays WHATWG-conformant HTML. (#20) by @gaborbernat.bytes directly: parse sniffs the encoding with the WHATWG algorithm (BOM, encoding argument, <meta> charset, then windows-1252), decodes with U+FFFD replacement, and reports the result in encoding. (#21) by @gaborbernat.Query any node with CSS through ~turbohtml.Node.select and ~turbohtml.Node.select_one, a native matcher covering type, universal, #id, .class, and attribute selectors (all operators plus the case-sensitivity flag) across the descendant, child, adjacent, and sibling combinators, returning comma groups in document order. An invalid selector raises ValueError. (14) by gaborbernat.
Search with a richer ~turbohtml.Node.find and ~turbohtml.Node.find_all filter grammar: match the tag and attributes by string, regex, bool, callable, or list (including class_ and the attrs mapping), and choose the search direction with the axis keyword. find_all takes a limit and returns a list. (15) by gaborbernat.
Test a node against a selector with ~turbohtml.Node.matches and ~turbohtml.Node.closest: matches() reports whether the node satisfies a CSS selector in context, and closest() returns the nearest matching ancestor (or the node itself), or None. (16) by gaborbernat.
Walk the tree by axis with new iterators: ~turbohtml.Node.next_siblings, ~turbohtml.Node.previous_siblings, document-order ~turbohtml.Node.following and ~turbohtml.Node.preceding, plus the ~turbohtml.Node.strings and ~turbohtml.Node.stripped_strings text iterators. (17) by gaborbernat.
Read HTML token-list attributes (class, rel, headers, sizes, sandbox, and the rest) as a list[str] in turbohtml.Element.attrs, split on ASCII whitespace; other attributes stay strings and valueless ones stay None. (18) by gaborbernat.
Control serialization on any node: ~turbohtml.Node.inner_html returns the children, while ~turbohtml.Node.serialize and ~turbohtml.Node.encode take a formatter (the ~turbohtml.Formatter enum picks the escape policy) and an indent for pretty output. The default stays WHATWG-conformant HTML. (20) by gaborbernat.
Parse bytes directly: turbohtml.parse sniffs the encoding with the WHATWG algorithm (BOM, encoding argument, <meta> charset, then windows-1252), decodes with U+FFFD replacement, and reports the result in ~turbohtml.Document.encoding. (21) by gaborbernat.
Tokenize HTML directly with a WHATWG-conformant tokenizer: tokenize for whole strings, the streaming Tokenizer, and the Token / TokenType types, valid
<a name="release-0-2-0-added"></a>
tokenize for whole strings, the streaming Tokenizer, and the Token / TokenType types, validated against the html5lib-tests tokenizer conformance suite. (#6) by @gaborbernat.escape and unescape faster: vectorized scanning and bulk copying speed up both calls, with unescaping of real escaped HTML about three times faster than the general lookup path. The benchmark now uses pyperf over multi-MiB real documents. (#7) by @gaborbernat.Tokenize HTML directly with a WHATWG-conformant tokenizer: turbohtml.tokenize() for whole strings, the streaming turbohtml.Tokenizer , and the turbohtml.Token / turbohtml.TokenType types, validated against the html5lib-tests tokenizer conformance suite. ( #6 ) by @gaborbernat .
Run turbohtml.escape() and turbohtml.unescape() faster: vectorized scanning and bulk copying speed up both calls, with unescaping of real escaped HTML about three times faster than the general lookup path. The benchmark now uses pyperf over multi-MiB real documents. ( #7 ) by @gaborbernat .
Tokenize HTML directly with a WHATWG-conformant tokenizer: turbohtml.tokenize for whole strings, the streaming turbohtml.Tokenizer, and the turbohtml.Token / turbohtml.TokenType types, validated against the html5lib-tests tokenizer conformance suite. (6) by gaborbernat.
Run turbohtml.escape and turbohtml.unescape faster: vectorized scanning and bulk copying speed up both calls, with unescaping of real escaped HTML about three times faster than the general lookup path. The benchmark now uses pyperf over multi-MiB real documents. (7) by gaborbernat.
Speed up entity handling with C-accelerated escape and unescape, drop-in replacements for escape and unescape, shipped as wheels for CPython 3.10 thro
<a name="release-0-1-1-added"></a>
escape and unescape, drop-in replacements for escape and unescape, shipped as wheels for CPython 3.10 through 3.15. (#1) by @gaborbernat.escape. (#3) by @gaborbernat.<a name="release-0-1-1-documentation"></a>
escape/unescape speedups in the README and docs, reproduce them with tox -e bench, and browse a typed API reference with intersphinx links. (#2) by @gaborbernat.<a name="release-0-1-1-packaging"></a>
sigstore.oidc.ExpiredIdentity failure that blocked the first upload. (#4) by @gaborbernat.Speed up entity handling with C-accelerated turbohtml.escape() and turbohtml.unescape() , drop-in replacements for html.escape() and html.unescape() , shipped as wheels for CPython 3.10 through 3.15. ( #1 ) by @gaborbernat .
Escape non-ASCII text that needs no escaping several times faster with a vectorized special-character scan, ahead of html.escape() . ( #3 ) by @gaborbernat .
See the measured turbohtml.escape() / turbohtml.unescape() speedups in the README and docs, reproduce them with tox -e bench , and browse a typed API reference with intersphinx links. ( #2 ) by @gaborbernat .
Install reliably from PyPI again: publishing each wheel in its own job keeps PEP 740 attestations within the Sigstore identity’s lifetime, fixing the sigstore.oidc.ExpiredIdentity failure that blocked the first upload. ( #4 ) by @gaborbernat .
On this page
Changelog
vUnreleased (2026-11-16)
v1.15.11 (2026-11-16)
Fixed
Security
Performance
Packaging
v1.15.10 (2026-11-07)
Fixed
v1.15.9 (2026-11-06)
Fixed
v1.15.8 (2026-11-05)
Fixed
v1.15.7 (2026-11-04)
Fixed
Security
v1.15.6 (2026-11-03)
Security
v1.15.5 (2026-11-03)
Fixed
Security
v1.15.4 (2026-10-27)
Documentation
v1.15.3 (2026-10-19)
Fixed
v1.15.2 (2026-10-15)
Fixed
Packaging
v1.15.1 (2026-10-12)
Fixed
Documentation
Packaging
v1.15.0 (2026-10-10)
Added
Fixed
v1.14.1 (2026-10-10)
Fixed
v1.14.0 (2026-10-09)
Added
Fixed
v1.13.1 (2026-10-01)
Fixed
v1.13.0 (2026-09-30)
Added
Fixed
Documentation
v1.12.0 (2026-09-29)
Added
v1.11.0 (2026-09-29)
Added
Fixed
v1.10.0 (2026-09-24)
Added
Fixed
v1.9.0 (2026-09-14)
Added
Fixed
v1.8.0 (2026-09-08)
Added
Fixed
Documentation
v1.7.0 (2026-08-29)
Added
v1.6.1 (2026-08-15)
Fixed
v1.6.0 (2026-08-11)
Added
Fixed
v1.5.1 (2026-07-27)
Fixed
v1.5.0 (2026-07-21)
Added
Documentation
v1.4.0 (2026-07-11)
Added
Fixed
v1.3.1 (2026-07-10)
v1.3.0 (2026-07-10)
Added
Fixed
Documentation
Packaging
v1.2.0 (2026-07-09)
Added
Fixed
Breaking changes
v1.1.1 (2026-07-08)
v1.1.0 (2026-07-08)
Added
v1.0.0 (2026-07-05)
Added
Fixed
Documentation
Breaking changes
Security
Performance
Packaging
v0.4.0 (2026-06-16)
Added
Documentation
v0.3.0 (2026-06-16)
Added
v0.2.0 (2026-06-11)
Added
v0.1.1 (2026-06-09)
Added
Documentation
Packaging
Speed up entity handling with C-accelerated turbohtml.escape and turbohtml.unescape, drop-in replacements for python:html.escape and python:html.unescape, shipped as wheels for CPython 3.10 through 3.15. (1) by gaborbernat.
Escape non-ASCII text that needs no escaping several times faster with a vectorized special-character scan, ahead of python:html.escape. (3) by gaborbernat.
See the measured turbohtml.escape/turbohtml.unescape speedups in the README and docs, reproduce them with tox -e bench, and browse a typed API reference with intersphinx links. (2) by gaborbernat.
Install reliably from PyPI again: publishing each wheel in its own job keeps PEP 740 attestations within the Sigstore identity's lifetime, fixing the sigstore.oidc.ExpiredIdentity failure that blocked the first upload. (4) by gaborbernat.