Skip to content

Preserve whitespace when serializing without indentation, and do so by default - #26

Merged
awolverp merged 2 commits into
awolverp:masterfrom
andersk:serialize-preserve-whitespace
Oct 7, 2026
Merged

awolverp merged 2 commits into
awolverp:masterfrom
andersk:serialize-preserve-whitespace

Conversation

@andersk

@andersk andersk commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

The serializer dropped whitespace-only text nodes and trimmed trailing whitespace from all other text nodes, regardless of the indent setting. Even with indent=0, this changed the meaning of the document: "<b>a</b> <i>b</i>" serialized as "<b>a</b><i>b</i>", and <pre>, <textarea>, <script>, and <style> contents lost their trailing whitespace.

With indent=0, write text nodes unchanged. Pretty-printing with a nonzero indent still discards and trims whitespace as before.

Like other HTML and XML libraries, serialize the document exactly by default, with indent=0, and document that a nonzero indent doesn't preserve the document's meaning.

andersk and others added 2 commits October 5, 2026 10:36
The serializer dropped whitespace-only text nodes and trimmed trailing
whitespace from all other text nodes, regardless of the indent setting.
Even with indent=0, this changed the meaning of the document: "<b>a</b>
<i>b</i>" serialized as "<b>a</b><i>b</i>", and <pre>, <textarea>,
<script>, and <style> contents lost their trailing whitespace.

With indent=0, write text nodes unchanged.  Pretty-printing with a
nonzero indent still discards and trims whitespace as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
serialize() and serialize_bytes() pretty-printed with indent=4 by
default, which adds and removes whitespace and so can change the
meaning of the document: it changes the rendering of whitespace
between inline elements, and the contents of <pre>, <textarea>, and
<script> elements.  Like other HTML and XML libraries, serialize the
document exactly by default, with indent=0, and document that a
nonzero indent doesn't preserve the document's meaning.

Update the examples in the documentation and README, several of which
showed pretty-printed output, and add a warning about pretty-printing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
@awolverp
awolverp merged commit 26f2101 into awolverp:master Oct 7, 2026
12 checks passed
@andersk
andersk deleted the serialize-preserve-whitespace branch October 7, 2026 10:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants