Skip to main content

parsec/
serialize.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The HTML fragment serialization algorithm, section 13.3 of the HTML
5//! Standard: `innerHTML` and `outerHTML`. With [`SerializeOptions`], also
6//! html5lib's serializer options, an indented pretty-printer, and the
7//! html5lib-tests tree dump.
8
9use crate::dom::{
10    AttrNs, Data, Document, Element, Kind, NodeId, Ns, ShadowRootMode, SlotAssignment,
11};
12use crate::tags::Tag;
13
14/// How [`Document::serialize_with`] writes a node. The default is the
15/// HTML Standard's serialization, byte for byte what
16/// [`Document::outer_html`] gives. Most fields are html5lib's serializer
17/// options, under html5lib's names.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct SerializeOptions {
20    /// Indents the markup, two spaces a level, without changing what it
21    /// means as the browser's default styles render it. An element's
22    /// children go one to a line only when every child is a block
23    /// (`div`, `p`, `li`, `table`, `tr`, `td` and the like), something
24    /// that's never rendered (`head`, `meta`, `script`, `template`...), a
25    /// comment, a doctype, or whitespace-only text, which is dropped for
26    /// the new line; and the element is itself a block, never rendered,
27    /// the document, or has at least one block child. Whitespace next to
28    /// a block collapses away, so adding it there changes nothing.
29    /// Anything else (text, an inline element such as `span`, `a`, `img`
30    /// or a custom element, foreign content) is written as it is, and so
31    /// is everything inside it, and inside `pre`, `textarea`, `listing`,
32    /// `plaintext`, `xmp`, `title`, `script`, `style`, `iframe`,
33    /// `noembed`, `noframes` and `noscript`. Nothing after `</body>` or
34    /// `</html>` starts a new line: the parser moves whitespace there to
35    /// the end of the body, where it could join text. `omit_optional_tags` is
36    /// ignored: every tag is kept, so no new whitespace ends up inside an
37    /// element whose end tag was left out. Author CSS that sets
38    /// `white-space` or `display` can make any whitespace matter, which
39    /// no pretty-printer can know. Past 100 levels the indent
40    /// goes no further, so a deep tree's output stays in proportion to it.
41    /// A `pre`, `textarea` or `listing` whose text starts with a newline
42    /// gets one more after its start tag, as the parser drops the first:
43    /// the HTML Standard's serialization leaves that out, so
44    /// `<pre>\n\nx</pre>` comes back as `<pre>x</pre>` without it.
45    pub pretty: bool,
46    /// The tree dump of html5lib-tests' tree-construction `.dat` files:
47    /// `| <html>`, `|   <head>`, each child two spaces in, attributes
48    /// sorted, foreign elements and namespaced attributes prefixed,
49    /// template contents under `content`. A shadow root, which the suite
50    /// has no line for, goes first under its host as `#shadow-root (open)`
51    /// or `(closed)`, with `delegatesfocus`, `clonable`, `serializable` and
52    /// `manual` after the mode when they're set. Every other option is
53    /// ignored.
54    pub html5test: bool,
55    /// `"` or `'` around attribute values; anything else is taken as
56    /// `"`. The one chosen is escaped inside: `&quot;` or `&#39;`.
57    pub quote_char: char,
58    /// Quote every attribute value. Off, a value goes unquoted when the
59    /// HTML syntax allows it: not empty, and no whitespace, quotes, `=`,
60    /// `>` or `` ` ``.
61    pub quote_attr_values: bool,
62    /// Quote a value with whichever quote it doesn't contain, so neither
63    /// needs escaping.
64    pub use_best_quote_char: bool,
65    /// Write an attribute without a value when its value is empty, or
66    /// when it's a boolean attribute (`disabled`, `checked`...) whose value
67    /// is its own name.
68    pub minimize_boolean_attributes: bool,
69    /// `<br />` rather than `<br>` for void elements.
70    pub use_trailing_solidus: bool,
71    /// Escape the text of `script`, `style` and the other raw text
72    /// elements as other text is; this changes what a script says.
73    pub escape_rcdata: bool,
74    /// Leave out the start and end tags the HTML Standard lets a document
75    /// leave out (section 13.1.2.4), where the parser puts back the same
76    /// tree: `</p>` before another `p`, `</li>`, `</td>`, `<tbody>`.
77    pub omit_optional_tags: bool,
78    /// Collapse each run of whitespace in text to one space, except inside
79    /// the elements `pretty` writes as they are.
80    pub strip_whitespace: bool,
81    /// Rewrite every `<meta charset>`, and the `content` of every
82    /// `<meta http-equiv=content-type>`, to name this encoding, and add a
83    /// `<meta charset>` first in a `head` that has neither.
84    pub inject_meta_charset: Option<String>,
85    /// A doctype's public and system identifiers too, as
86    /// `<!DOCTYPE html PUBLIC "..." "...">`; the HTML Standard writes the
87    /// name alone.
88    pub full_doctype: bool,
89    /// Write each shadow root marked serializable as the declarative
90    /// `<template shadowrootmode>` that makes it again, first inside its
91    /// host, as `getHTML({serializableShadowRoots: true})` does.
92    pub serializable_shadow_roots: bool,
93    /// Write these shadow roots that way too, serializable or not, as
94    /// `getHTML({shadowRoots})` does.
95    pub shadow_roots: Vec<NodeId>,
96}
97
98const DEFAULT: SerializeOptions = SerializeOptions {
99    pretty: false,
100    html5test: false,
101    quote_char: '"',
102    quote_attr_values: true,
103    use_best_quote_char: false,
104    minimize_boolean_attributes: false,
105    use_trailing_solidus: false,
106    escape_rcdata: false,
107    omit_optional_tags: false,
108    strip_whitespace: false,
109    inject_meta_charset: None,
110    full_doctype: false,
111    serializable_shadow_roots: false,
112    shadow_roots: Vec::new(),
113};
114
115impl Default for SerializeOptions {
116    fn default() -> SerializeOptions {
117        DEFAULT
118    }
119}
120
121/// How many levels deep `pretty` indents. Each level of a tree deeper
122/// than this costs as many spaces as this one, not a level more: a
123/// hundred thousand nested divs made a 17 GB string.
124const MAX_INDENT: u16 = 100;
125
126/// A node to write, with how: these flags, and its indent for `pretty`.
127#[derive(Clone, Copy)]
128struct Item {
129    id: NodeId,
130    /// Past 65,535 levels, it counts no further; [`MAX_INDENT`] caps the
131    /// indent written.
132    depth: u16,
133    flags: u8,
134}
135
136/// The element's end tag, once its children are written.
137const END: u8 = 1;
138/// Starts on a line of its own, for `pretty`.
139const LINE: u8 = 2;
140/// Under an element `pretty` writes as it is: no new lines.
141const INLINE: u8 = 4;
142/// Under `pre` or the like, where `strip_whitespace` leaves text alone.
143const KEEP_SPACE: u8 = 8;
144/// The node's children only, as `innerHTML`.
145const INNER: u8 = 16;
146/// A shadow root written as the `<template shadowrootmode>` that makes it.
147const SHADOW: u8 = 32;
148
149/// Elements with no end tag and no contents when serialized.
150fn void(e: &Element) -> bool {
151    use Tag::*;
152    e.ns == Ns::Html
153        && matches!(
154            e.tag,
155            Area | Base
156                | Basefont
157                | Bgsound
158                | Br
159                | Col
160                | Embed
161                | Frame
162                | Hr
163                | Img
164                | Input
165                | Keygen
166                | Link
167                | Meta
168                | Param
169                | Source
170                | Track
171                | Wbr
172        )
173}
174
175/// Elements whose whitespace is kept, by the parser or by their default
176/// `white-space`, or whose text is raw.
177fn keeps_space(e: &Element) -> bool {
178    use Tag::*;
179    e.ns == Ns::Html
180        && matches!(
181            e.tag,
182            Pre | Listing
183                | Plaintext
184                | Xmp
185                | Textarea
186                | Title
187                | Script
188                | Style
189                | Iframe
190                | Noembed
191                | Noframes
192                | Noscript
193        )
194}
195
196/// Elements the default styles make blocks: list items, table parts and
197/// the rest of `display: block`.
198fn block(tag: Tag) -> bool {
199    use Tag::*;
200    matches!(
201        tag,
202        Html | Body
203            | Address
204            | Article
205            | Aside
206            | Blockquote
207            | Caption
208            | Center
209            | Col
210            | Colgroup
211            | Dd
212            | Details
213            | Dialog
214            | Dir
215            | Div
216            | Dl
217            | Dt
218            | Fieldset
219            | Figcaption
220            | Figure
221            | Footer
222            | Form
223            | Frame
224            | Frameset
225            | H1
226            | H2
227            | H3
228            | H4
229            | H5
230            | H6
231            | Header
232            | Hgroup
233            | Hr
234            | Li
235            | Listing
236            | Main
237            | Menu
238            | Nav
239            | Ol
240            | Optgroup
241            | Option
242            | P
243            | Plaintext
244            | Pre
245            | Search
246            | Section
247            | Summary
248            | Table
249            | Tbody
250            | Td
251            | Tfoot
252            | Th
253            | Thead
254            | Tr
255            | Ul
256            | Xmp
257    )
258}
259
260/// Elements the default styles never render.
261fn unrendered(tag: Tag) -> bool {
262    use Tag::*;
263    matches!(
264        tag,
265        Head | Title
266            | Meta
267            | Link
268            | Style
269            | Script
270            | Base
271            | Template
272            | Datalist
273            | Param
274            | Source
275            | Track
276            | Area
277            | Noembed
278            | Noframes
279    )
280}
281
282/// HTML's boolean attributes, current and obsolete, which
283/// `minimize_boolean_attributes` writes bare when the value is the name.
284/// `irrelevant` was an early name for `hidden`.
285fn boolean(name: &str) -> bool {
286    matches!(
287        name,
288        "allowfullscreen"
289            | "async"
290            | "autofocus"
291            | "autoplay"
292            | "checked"
293            | "compact"
294            | "controls"
295            | "declare"
296            | "default"
297            | "defer"
298            | "disabled"
299            | "formnovalidate"
300            | "hidden"
301            | "inert"
302            | "irrelevant"
303            | "ismap"
304            | "itemscope"
305            | "loop"
306            | "multiple"
307            | "muted"
308            | "nohref"
309            | "nomodule"
310            | "noresize"
311            | "noshade"
312            | "novalidate"
313            | "nowrap"
314            | "open"
315            | "playsinline"
316            | "readonly"
317            | "required"
318            | "reversed"
319            | "scoped"
320            | "seamless"
321            | "selected"
322            | "shadowrootclonable"
323            | "shadowrootdelegatesfocus"
324            | "shadowrootserializable"
325            | "truespeed"
326    )
327}
328
329fn space(b: u8) -> bool {
330    matches!(b, b'\t' | b'\n' | b'\x0c' | b'\r' | b' ')
331}
332
333fn blank(s: &str) -> bool {
334    s.bytes().all(space)
335}
336
337fn newline(depth: u16, out: &mut String) {
338    out.push('\n');
339    for _ in 0..depth.min(MAX_INDENT) {
340        out.push_str("  ");
341    }
342}
343
344impl Document {
345    /// The markup for `id`'s children, as `innerHTML` returns it.
346    pub fn inner_html(&self, id: NodeId) -> String {
347        self.inner_html_with(id, &DEFAULT)
348    }
349
350    /// The markup for `id` and its children, as `outerHTML` returns it.
351    pub fn outer_html(&self, id: NodeId) -> String {
352        self.serialize_with(id, &DEFAULT)
353    }
354
355    /// The markup for `id` and its children, written as `options` say;
356    /// with the defaults, what [`Document::outer_html`] gives.
357    pub fn serialize_with(&self, id: NodeId, options: &SerializeOptions) -> String {
358        self.serialize(id, 0, options)
359    }
360
361    /// The markup for `id`'s children, written as `options` say; with the
362    /// defaults, what [`Document::inner_html`] gives.
363    pub fn inner_html_with(&self, id: NodeId, options: &SerializeOptions) -> String {
364        self.serialize(id, INNER, options)
365    }
366
367    fn serialize(&self, id: NodeId, flags: u8, o: &SerializeOptions) -> String {
368        let mut out = String::new();
369        if self.is_removed(id) {
370            return out;
371        }
372        if flags & INNER != 0
373            && !matches!(
374                self.nodes[id as usize].data,
375                Data::Element(_) | Data::Document | Data::Fragment | Data::ShadowRoot { .. }
376            )
377        {
378            return out;
379        }
380        if o.html5test {
381            self.dump(id, flags & INNER != 0, &mut out);
382            return out;
383        }
384        let flags = if o.pretty || o.strip_whitespace {
385            flags | self.context(id)
386        } else {
387            flags
388        };
389        let mut stack = vec![Item {
390            id,
391            depth: 0,
392            flags,
393        }];
394        if *o == DEFAULT {
395            if flags & INNER != 0 {
396                stack.clear();
397                if !self.element(id).is_some_and(void) {
398                    self.push_children(id, 0, 0, &mut stack);
399                }
400            }
401            self.write::<true>(stack, o, &mut out);
402        } else {
403            self.write::<false>(stack, o, &mut out);
404        }
405        out
406    }
407
408    /// What `id`'s ancestors make of it: under `pre` or the like, it's
409    /// written as it is.
410    fn context(&self, id: NodeId) -> u8 {
411        let mut at = self.parent(id);
412        while let Some(p) = at {
413            if self.element(p).is_some_and(keeps_space) {
414                return INLINE | KEEP_SPACE;
415            }
416            at = self.parent(p);
417        }
418        0
419    }
420
421    /// The flags `id`'s children are written with, given its own.
422    fn child_flags(&self, id: NodeId, flags: u8, o: &SerializeOptions) -> u8 {
423        let mut f = flags & (INLINE | KEEP_SPACE);
424        if self.element(id).is_some_and(keeps_space) {
425            f |= INLINE | KEEP_SPACE;
426        }
427        if o.pretty && f & INLINE == 0 {
428            f |= if self.breaks(id) { LINE } else { INLINE };
429        }
430        f
431    }
432
433    /// Whether `pretty` puts `id`'s children one to a line: see
434    /// [`SerializeOptions::pretty`].
435    fn breaks(&self, id: NodeId) -> bool {
436        let mut has_block = match &self.nodes[id as usize].data {
437            Data::Document => true,
438            Data::Element(e) => {
439                e.ns == Ns::Html && (block(e.tag) || (unrendered(e.tag) && e.tag != Tag::Template))
440            }
441            _ => false,
442        };
443        let contents = self.template_contents(id);
444        for c in self
445            .children(id)
446            .chain(contents.into_iter().flat_map(|t| self.children(t)))
447        {
448            match &self.nodes[c as usize].data {
449                Data::Text(s) if !blank(self.str(*s)) => return false,
450                Data::Element(e) if e.ns == Ns::Html && block(e.tag) => has_block = true,
451                Data::Element(e) if e.ns == Ns::Html && unrendered(e.tag) => {}
452                Data::Element(_) | Data::Cdata(_) => return false,
453                _ => {}
454            }
455        }
456        has_block
457    }
458
459    /// `id`'s children onto the stack, the first on top: any children it
460    /// has, then a template's contents, which it only has both of once
461    /// adopt_template_contents has moved its contents in. With `LINE`,
462    /// whitespace-only text isn't pushed. Whether the end tag goes on a
463    /// line of its own: there were children, and `LINE` still held after
464    /// them.
465    fn push_children(&self, id: NodeId, mut flags: u8, depth: u16, stack: &mut Vec<Item>) -> bool {
466        let at = stack.len();
467        if flags & LINE == 0 {
468            let item = |c| Item {
469                id: c,
470                depth,
471                flags,
472            };
473            stack.extend(self.children(id).map(item));
474            if let Some(contents) = self.template_contents(id) {
475                stack.extend(self.children(contents).map(item));
476            }
477            stack[at..].reverse();
478            return false;
479        }
480        let contents = self.template_contents(id);
481        for c in self
482            .children(id)
483            .chain(contents.into_iter().flat_map(|t| self.children(t)))
484        {
485            let data = &self.nodes[c as usize].data;
486            if flags & LINE != 0 && matches!(data, Data::Text(s) if blank(self.str(*s))) {
487                continue;
488            }
489            stack.push(Item {
490                id: c,
491                depth,
492                flags,
493            });
494            // The parser puts whitespace after `</body>` or `</html>` at
495            // the end of the body, where it could join the body's text.
496            if let Data::Element(e) = data
497                && e.ns == Ns::Html
498                && matches!(e.tag, Tag::Body | Tag::Frameset | Tag::Html)
499            {
500                flags &= !LINE;
501            }
502        }
503        stack[at..].reverse();
504        stack.len() > at && flags & LINE != 0
505    }
506
507    /// Writes what's on the stack, with a stack of its own rather than
508    /// recursion, so a tree as deep as any page makes can't overflow it.
509    /// `PLAIN` is for the default options, which then cost nothing.
510    fn write<const PLAIN: bool>(
511        &self,
512        mut stack: Vec<Item>,
513        o: &SerializeOptions,
514        out: &mut String,
515    ) {
516        let start = out.len();
517        let omit = !PLAIN && o.omit_optional_tags && !o.pretty;
518        while let Some(Item { id, depth, flags }) = stack.pop() {
519            if !PLAIN && flags & LINE != 0 && out.len() > start {
520                newline(depth, out);
521            }
522            let data = &self.nodes[id as usize].data;
523            if flags & END != 0 {
524                if let Data::Element(e) = data
525                    && !(omit && self.omit_end(id, e))
526                {
527                    out.push_str("</");
528                    out.push_str(self.element_name(e));
529                    out.push('>');
530                } else if !PLAIN && matches!(data, Data::ShadowRoot { .. }) {
531                    out.push_str("</template>");
532                }
533                continue;
534            }
535            match data {
536                Data::Element(e) => {
537                    let inner = !PLAIN && flags & INNER != 0;
538                    if !inner && !(omit && self.omit_start(id, e, o)) {
539                        self.start_tag::<PLAIN>(id, e, o, out);
540                        if !PLAIN && o.pretty && self.drops_first_newline(id, e) {
541                            out.push('\n');
542                        }
543                    }
544                    if void(e) {
545                        continue;
546                    }
547                    let children = if PLAIN {
548                        0
549                    } else {
550                        self.child_flags(id, flags, o)
551                    };
552                    let inside = if inner {
553                        depth
554                    } else {
555                        depth.saturating_add(1)
556                    };
557                    let meta = if PLAIN {
558                        None
559                    } else {
560                        self.injects_meta(id, e, o)
561                    };
562                    if let Some(charset) = meta {
563                        if children & LINE != 0 && out.len() > start {
564                            newline(inside, out);
565                        }
566                        out.push_str("<meta");
567                        self.attr("charset", charset, o, out);
568                        out.push_str(if o.use_trailing_solidus { " />" } else { ">" });
569                    }
570                    let end = stack.len();
571                    if !inner {
572                        stack.push(Item {
573                            id,
574                            depth,
575                            flags: END,
576                        });
577                    }
578                    let line = self.push_children(id, children, inside, &mut stack);
579                    // The shadow root goes first, so on the stack last.
580                    if !PLAIN && let Some(root) = self.written_shadow_root(id, o) {
581                        stack.push(Item {
582                            id: root,
583                            depth: inside,
584                            flags: children | SHADOW,
585                        });
586                    }
587                    let empty = stack.len() == end + 1;
588                    if !inner && children & LINE != 0 && (line || (empty && meta.is_some())) {
589                        stack[end].flags |= LINE;
590                    }
591                }
592                Data::Text(span) => {
593                    let text = self.str(*span);
594                    if self.raw_text_parent(id) && (PLAIN || !o.escape_rcdata) {
595                        out.push_str(text);
596                    } else if !PLAIN && o.strip_whitespace && flags & KEEP_SPACE == 0 {
597                        escape::<0>(&collapse(text), out);
598                    } else {
599                        escape::<0>(text, out);
600                    }
601                }
602                Data::Comment(span) => {
603                    out.push_str("<!--");
604                    out.push_str(self.str(*span));
605                    out.push_str("-->");
606                }
607                Data::ProcessingInstruction { target, data } => {
608                    out.push_str("<?");
609                    out.push_str(self.str(*target));
610                    out.push(' ');
611                    out.push_str(self.str(*data));
612                    out.push_str("?>");
613                }
614                Data::Cdata(span) => {
615                    out.push_str("<![CDATA[");
616                    out.push_str(self.str(*span));
617                    out.push_str("]]>");
618                }
619                Data::Doctype {
620                    name,
621                    public_id,
622                    system_id,
623                } => {
624                    out.push_str("<!DOCTYPE ");
625                    out.push_str(self.str(*name));
626                    if !PLAIN && o.full_doctype {
627                        let (public_id, system_id) = (self.str(*public_id), self.str(*system_id));
628                        if !public_id.is_empty() {
629                            out.push_str(" PUBLIC ");
630                            quoted(public_id, out);
631                        } else if !system_id.is_empty() {
632                            out.push_str(" SYSTEM");
633                        }
634                        if !system_id.is_empty() {
635                            out.push(' ');
636                            quoted(system_id, out);
637                        }
638                    }
639                    out.push('>');
640                }
641                Data::Document | Data::Fragment => {
642                    let children = if PLAIN {
643                        0
644                    } else {
645                        self.child_flags(id, flags, o)
646                    };
647                    self.push_children(id, children, depth, &mut stack);
648                }
649                Data::ShadowRoot { init, .. } => {
650                    let children = if PLAIN {
651                        0
652                    } else {
653                        self.child_flags(id, flags, o)
654                    };
655                    if flags & SHADOW == 0 {
656                        self.push_children(id, children, depth, &mut stack);
657                        continue;
658                    }
659                    out.push_str("<template shadowrootmode=\"");
660                    out.push_str(match init.mode {
661                        ShadowRootMode::Open => "open",
662                        ShadowRootMode::Closed => "closed",
663                    });
664                    out.push('"');
665                    // In the standard's order; named assignment, the
666                    // default, goes unsaid.
667                    for (on, name) in [
668                        (init.delegates_focus, " shadowrootdelegatesfocus=\"\""),
669                        (init.serializable, " shadowrootserializable=\"\""),
670                        (
671                            init.slot_assignment == SlotAssignment::Manual,
672                            " shadowrootslotassignment=\"manual\"",
673                        ),
674                        (init.clonable, " shadowrootclonable=\"\""),
675                    ] {
676                        if on {
677                            out.push_str(name);
678                        }
679                    }
680                    out.push('>');
681                    let end = stack.len();
682                    stack.push(Item {
683                        id,
684                        depth,
685                        flags: END,
686                    });
687                    let inside = depth.saturating_add(1);
688                    if self.push_children(id, children, inside, &mut stack) && children & LINE != 0
689                    {
690                        stack[end].flags |= LINE;
691                    }
692                }
693            }
694        }
695    }
696
697    /// Whether the parser would drop a newline at the start of `e`'s
698    /// text: a `pre`, `textarea` or `listing` whose first child is text
699    /// that starts with one.
700    fn drops_first_newline(&self, id: NodeId, e: &Element) -> bool {
701        e.ns == Ns::Html
702            && matches!(e.tag, Tag::Pre | Tag::Textarea | Tag::Listing)
703            && self
704                .first_child(id)
705                .is_some_and(|c| matches!(self.kind(c), Kind::Text(t) if t.starts_with('\n')))
706    }
707
708    /// The shadow root of `host` that `o` asks to be written: one marked
709    /// serializable, with `serializable_shadow_roots`, or one listed in
710    /// `shadow_roots`.
711    fn written_shadow_root(&self, host: NodeId, o: &SerializeOptions) -> Option<NodeId> {
712        if !o.serializable_shadow_roots && o.shadow_roots.is_empty() {
713            return None;
714        }
715        let root = self.shadow_root(host)?;
716        let Data::ShadowRoot { init, .. } = self.nodes[root as usize].data else {
717            return None;
718        };
719        ((o.serializable_shadow_roots && init.serializable) || o.shadow_roots.contains(&root))
720            .then_some(root)
721    }
722
723    fn start_tag<const PLAIN: bool>(
724        &self,
725        id: NodeId,
726        e: &Element,
727        o: &SerializeOptions,
728        out: &mut String,
729    ) {
730        out.push('<');
731        out.push_str(self.element_name(e));
732        if PLAIN {
733            // Names as written are the spec's serialized names:
734            // `xlink:href`, `xml:lang`, `xmlns`.
735            for (_, name, value) in self.attrs_written(id) {
736                out.push(' ');
737                out.push_str(name);
738                out.push_str("=\"");
739                escape::<b'"'>(value, out);
740                out.push('"');
741            }
742            out.push('>');
743            return;
744        }
745        let charset = o
746            .inject_meta_charset
747            .as_deref()
748            .filter(|_| e.ns == Ns::Html && e.tag == Tag::Meta)
749            .and_then(|c| Some((c, self.meta_charset(id)?)));
750        for (i, (_, name, value)) in self.attrs_written(id).enumerate() {
751            match charset {
752                Some((c, (at, false))) if at == i => self.attr(name, c, o, out),
753                Some((c, (at, true))) if at == i => {
754                    self.attr(name, &format!("text/html; charset={c}"), o, out)
755                }
756                _ => self.attr(name, value, o, out),
757            }
758        }
759        if o.use_trailing_solidus && void(e) {
760            out.push_str(" /");
761        }
762        out.push('>');
763    }
764
765    fn attr(&self, name: &str, value: &str, o: &SerializeOptions, out: &mut String) {
766        out.push(' ');
767        out.push_str(name);
768        if o.minimize_boolean_attributes
769            && (value.is_empty() || (boolean(name) && value.eq_ignore_ascii_case(name)))
770        {
771            return;
772        }
773        out.push('=');
774        if !o.quote_attr_values
775            && !value.is_empty()
776            && !value
777                .bytes()
778                .any(|b| space(b) || matches!(b, b'"' | b'\'' | b'=' | b'>' | b'`'))
779        {
780            escape::<0>(value, out);
781            return;
782        }
783        let mut quote = if o.quote_char == '\'' { b'\'' } else { b'"' };
784        if o.use_best_quote_char {
785            match (value.contains('"'), value.contains('\'')) {
786                (true, false) => quote = b'\'',
787                (false, true) => quote = b'"',
788                _ => {}
789            }
790        }
791        out.push(quote as char);
792        if quote == b'\'' {
793            escape::<b'\''>(value, out);
794        } else {
795            escape::<b'"'>(value, out);
796        }
797        out.push(quote as char);
798    }
799
800    /// A meta element's attribute that names the encoding, for
801    /// `inject_meta_charset`: its index, and whether it's the `content` of
802    /// an `http-equiv=content-type`, not a `charset`.
803    fn meta_charset(&self, id: NodeId) -> Option<(usize, bool)> {
804        let attrs: Vec<_> = self.attrs(id).collect();
805        let named = |n: &str| {
806            attrs
807                .iter()
808                .position(|&(ns, name, _)| ns == AttrNs::None && name.eq_ignore_ascii_case(n))
809        };
810        if let Some(at) = named("charset") {
811            return Some((at, false));
812        }
813        named("http-equiv")
814            .filter(|&at| attrs[at].2.eq_ignore_ascii_case("content-type"))
815            .and(named("content"))
816            .map(|at| (at, true))
817    }
818
819    /// The encoding to write a `<meta charset>` for first in `id`: a head
820    /// with no meta that names one, under `inject_meta_charset`.
821    fn injects_meta<'o>(
822        &self,
823        id: NodeId,
824        e: &Element,
825        o: &'o SerializeOptions,
826    ) -> Option<&'o str> {
827        let charset = o.inject_meta_charset.as_deref()?;
828        (e.ns == Ns::Html
829            && e.tag == Tag::Head
830            && !self.children(id).any(|c| {
831                self.element(c)
832                    .is_some_and(|m| m.ns == Ns::Html && m.tag == Tag::Meta)
833                    && self.meta_charset(c).is_some()
834            }))
835        .then_some(charset)
836    }
837
838    /// The HTML tag of `id` if it's an HTML element.
839    fn html_tag(&self, id: Option<NodeId>) -> Option<Tag> {
840        let e = self.element(id?)?;
841        (e.ns == Ns::Html).then_some(e.tag)
842    }
843
844    /// Whether `id` is there and is a comment, or text that starts with
845    /// whitespace.
846    fn space_or_comment(&self, id: Option<NodeId>) -> bool {
847        id.is_some_and(|n| match &self.nodes[n as usize].data {
848            Data::Comment(_) => true,
849            Data::Text(s) => self.str(*s).bytes().next().is_some_and(space),
850            _ => false,
851        })
852    }
853
854    /// Whether `omit_optional_tags` leaves out `id`'s start tag, by
855    /// section 13.1.2.4. Never with attributes. `<html>` is kept before
856    /// whitespace too, which the parser would otherwise drop.
857    fn omit_start(&self, id: NodeId, e: &Element, o: &SerializeOptions) -> bool {
858        if e.ns != Ns::Html || e.attrs.start != e.attrs.end {
859            return false;
860        }
861        let first = self.first_child(id);
862        let prev_omitted = |tags: &[Tag]| {
863            self.prev_sibling(id).is_some_and(|p| {
864                self.element(p).is_some_and(|pe| {
865                    pe.ns == Ns::Html && tags.contains(&pe.tag) && self.omit_end(p, pe)
866                })
867            })
868        };
869        match e.tag {
870            Tag::Html => !self.space_or_comment(first),
871            Tag::Head => {
872                self.injects_meta(id, e, o).is_some()
873                    || first.is_none_or(|f| self.element(f).is_some())
874            }
875            Tag::Body => {
876                !self.space_or_comment(first)
877                    && !matches!(
878                        self.html_tag(first),
879                        Some(
880                            Tag::Meta
881                                | Tag::Noscript
882                                | Tag::Link
883                                | Tag::Script
884                                | Tag::Style
885                                | Tag::Template
886                        )
887                    )
888            }
889            Tag::Colgroup => {
890                self.html_tag(first) == Some(Tag::Col) && !prev_omitted(&[Tag::Colgroup])
891            }
892            Tag::Tbody => {
893                self.html_tag(first) == Some(Tag::Tr)
894                    && !prev_omitted(&[Tag::Tbody, Tag::Thead, Tag::Tfoot])
895            }
896            _ => false,
897        }
898    }
899
900    /// Whether `omit_optional_tags` leaves out `id`'s end tag, by section
901    /// 13.1.2.4. `</html>` and `</body>` are kept before whitespace too,
902    /// as `</head>` is. `</p>` goes before `dir` as well, and `</tfoot>`
903    /// before `tbody`, as earlier versions of the rules had it: the parser
904    /// closes a `p` at `<dir>` and a `tfoot` at `<tbody>`.
905    fn omit_end(&self, id: NodeId, e: &Element) -> bool {
906        use Tag::*;
907        if e.ns != Ns::Html {
908            return false;
909        }
910        let next = self.next_sibling(id);
911        let last = next.is_none();
912        let tag = self.html_tag(next);
913        let is = |tags: &[Tag]| tag.is_some_and(|t| tags.contains(&t));
914        match e.tag {
915            Html | Head | Body | Colgroup | Caption => !self.space_or_comment(next),
916            Li => last || is(&[Li]),
917            Dt => is(&[Dt, Dd]),
918            Dd => last || is(&[Dd, Dt]),
919            Rt | Rp => last || is(&[Rt, Rp]),
920            Optgroup => last || is(&[Optgroup, Hr]),
921            Option => last || is(&[Option, Optgroup, Hr]),
922            Thead => is(&[Tbody, Tfoot]),
923            Tbody => last || is(&[Tbody, Tfoot]),
924            Tfoot => last || is(&[Tbody]),
925            Tr => last || is(&[Tr]),
926            Td | Th => last || is(&[Td, Th]),
927            P if last => !self.parent(id).is_some_and(|p| {
928                self.element(p).is_some_and(|pe| pe.ns == Ns::Html)
929                    && self.lower_name(p).is_some_and(|n| {
930                        matches!(
931                            n,
932                            "a" | "audio" | "del" | "ins" | "map" | "noscript" | "video"
933                        ) || n.contains('-')
934                    })
935            }),
936            P => is(&[
937                Address, Article, Aside, Blockquote, Details, Dialog, Dir, Div, Dl, Fieldset,
938                Figcaption, Figure, Footer, Form, H1, H2, H3, H4, H5, H6, Header, Hgroup, Hr, Main,
939                Menu, Nav, Ol, P, Pre, Search, Section, Table, Ul,
940            ]),
941            _ => false,
942        }
943    }
944
945    /// The node alone: an element's start tag, escaped text, a comment
946    /// or a doctype; as `outer_html` writes it, without the children. A
947    /// document or a template's contents is nothing but its children, so
948    /// it gives an empty string.
949    pub fn html_alone(&self, id: NodeId) -> String {
950        let mut out = String::new();
951        if self.is_removed(id) {
952            return out;
953        }
954        match &self.nodes[id as usize].data {
955            Data::Element(e) => self.start_tag::<true>(id, e, &DEFAULT, &mut out),
956            Data::Document | Data::Fragment | Data::ShadowRoot { .. } => {}
957            _ => out = self.outer_html(id),
958        }
959        out
960    }
961
962    fn raw_text_parent(&self, id: NodeId) -> bool {
963        use Tag::*;
964        let Some(e) = self.parent(id).and_then(|p| self.element(p)) else {
965            return false;
966        };
967        e.ns == Ns::Html
968            && (matches!(
969                e.tag,
970                Style | Script | Xmp | Iframe | Noembed | Noframes | Plaintext
971            ) || (e.tag == Noscript && self.scripting))
972    }
973
974    /// Writes the html5lib-tests tree dump of `id`, or of its children
975    /// with `inner`; see [`SerializeOptions::html5test`].
976    fn dump(&self, id: NodeId, inner: bool, out: &mut String) {
977        // (node, depth, whether it's a template's contents, under `content`)
978        let mut stack = Vec::new();
979        if inner {
980            self.push_dump(id, 0, &mut stack);
981        } else {
982            stack.push((id, 0, false));
983        }
984        while let Some((id, depth, contents)) = stack.pop() {
985            let line = |out: &mut String| {
986                if !out.is_empty() {
987                    out.push('\n');
988                }
989                out.push_str("| ");
990                for _ in 0..depth {
991                    out.push_str("  ");
992                }
993            };
994            if contents {
995                line(out);
996                match self.kind(id) {
997                    Kind::ShadowRoot(init) => {
998                        out.push_str("#shadow-root (");
999                        out.push_str(match init.mode {
1000                            ShadowRootMode::Open => "open",
1001                            ShadowRootMode::Closed => "closed",
1002                        });
1003                        for (on, flag) in [
1004                            (init.delegates_focus, " delegatesfocus"),
1005                            (init.clonable, " clonable"),
1006                            (init.serializable, " serializable"),
1007                            (init.slot_assignment == SlotAssignment::Manual, " manual"),
1008                        ] {
1009                            if on {
1010                                out.push_str(flag);
1011                            }
1012                        }
1013                        out.push(')');
1014                    }
1015                    _ => out.push_str("content"),
1016                }
1017                let at = stack.len();
1018                stack.extend(self.children(id).map(|c| (c, depth + 1, false)));
1019                stack[at..].reverse();
1020                continue;
1021            }
1022            match self.kind(id) {
1023                Kind::Document | Kind::Fragment | Kind::ShadowRoot(_) => {
1024                    self.push_dump(id, depth, &mut stack)
1025                }
1026                Kind::Doctype {
1027                    name,
1028                    public_id,
1029                    system_id,
1030                } => {
1031                    line(out);
1032                    if public_id.is_empty() && system_id.is_empty() {
1033                        out.push_str(&format!("<!DOCTYPE {name}>"));
1034                    } else {
1035                        out.push_str(&format!(
1036                            "<!DOCTYPE {name} \"{public_id}\" \"{system_id}\">"
1037                        ));
1038                    }
1039                }
1040                Kind::Element { ns, name } => {
1041                    let prefix = match ns {
1042                        Ns::Html => "",
1043                        Ns::Svg => "svg ",
1044                        Ns::MathMl => "math ",
1045                        Ns::Xml => "xml ",
1046                    };
1047                    line(out);
1048                    out.push_str(&format!("<{prefix}{name}>"));
1049                    let mut attrs: Vec<String> = self
1050                        .attrs(id)
1051                        .zip(self.attrs_written(id))
1052                        .map(|((ns, local, value), (_, written, _))| {
1053                            let name = match ns {
1054                                AttrNs::None => written.to_string(),
1055                                AttrNs::XLink => format!("xlink {local}"),
1056                                AttrNs::Xml => format!("xml {local}"),
1057                                AttrNs::Xmlns if local == "xmlns" => "xmlns".to_string(),
1058                                AttrNs::Xmlns => format!("xmlns {local}"),
1059                                AttrNs::Host(_) => local.to_string(),
1060                            };
1061                            format!("{name}=\"{value}\"")
1062                        })
1063                        .collect();
1064                    attrs.sort();
1065                    for a in attrs {
1066                        line(out);
1067                        out.push_str("  ");
1068                        out.push_str(&a);
1069                    }
1070                    self.push_dump(id, depth + 1, &mut stack);
1071                }
1072                Kind::Text(t) => {
1073                    line(out);
1074                    out.push_str(&format!("\"{t}\""));
1075                }
1076                Kind::Comment(c) => {
1077                    line(out);
1078                    out.push_str(&format!("<!-- {c} -->"));
1079                }
1080                Kind::ProcessingInstruction { target, data } => {
1081                    line(out);
1082                    out.push_str(&format!("<?{target} {data}?>"));
1083                }
1084                Kind::Cdata(c) => {
1085                    line(out);
1086                    out.push_str(&format!("<![CDATA[{c}]]>"));
1087                }
1088            }
1089        }
1090    }
1091
1092    /// `id`'s children onto the dump's stack, the first on top: a
1093    /// template's `content` or a host's `#shadow-root` first, then any
1094    /// children it has.
1095    fn push_dump(&self, id: NodeId, depth: usize, stack: &mut Vec<(NodeId, usize, bool)>) {
1096        let at = stack.len();
1097        if let Some(contents) = self.template_contents(id) {
1098            stack.push((contents, depth, true));
1099        }
1100        if let Some(root) = self.shadow_root(id) {
1101            stack.push((root, depth, true));
1102        }
1103        stack.extend(self.children(id).map(|c| (c, depth, false)));
1104        stack[at..].reverse();
1105    }
1106
1107    /// The text of `id` and everything under it, in tree order, as
1108    /// `textContent` gives it.
1109    pub fn text(&self, id: NodeId) -> String {
1110        let mut out = String::new();
1111        if self.is_removed(id) {
1112            return out;
1113        }
1114        let mut stack = vec![id];
1115        while let Some(n) = stack.pop() {
1116            if let Kind::Text(t) = self.kind(n) {
1117                out.push_str(t);
1118            }
1119            let at = stack.len();
1120            stack.extend(self.children(n));
1121            stack[at..].reverse();
1122        }
1123        out
1124    }
1125}
1126
1127/// Each run of whitespace in `s` as one space, for `strip_whitespace`.
1128fn collapse(s: &str) -> String {
1129    let mut out = String::with_capacity(s.len());
1130    let mut in_space = false;
1131    for c in s.chars() {
1132        if c.is_ascii() && space(c as u8) {
1133            if !in_space {
1134                out.push(' ');
1135            }
1136            in_space = true;
1137        } else {
1138            out.push(c);
1139            in_space = false;
1140        }
1141    }
1142    out
1143}
1144
1145/// A doctype identifier in `"`, or `'` when it has a `"` in it, which
1146/// the tokenizer only allows in an identifier the other quote ends.
1147fn quoted(s: &str, out: &mut String) {
1148    let quote = if s.contains('"') { '\'' } else { '"' };
1149    out.push(quote);
1150    out.push_str(s);
1151    out.push(quote);
1152}
1153
1154/// The spec's escaping: `&`, NO-BREAK SPACE, `<` and `>` always, and in an
1155/// attribute value the `QUOTE` around it, `"` or `'` (0 for text).
1156fn escape<const QUOTE: u8>(s: &str, out: &mut String) {
1157    let bytes = s.as_bytes();
1158    let mut from = 0;
1159    let mut i = 0;
1160    while i < bytes.len() {
1161        let replacement = match bytes[i] {
1162            b'&' => "&amp;",
1163            b'<' => "&lt;",
1164            b'>' => "&gt;",
1165            b'"' if QUOTE == b'"' => "&quot;",
1166            b'\'' if QUOTE == b'\'' => "&#39;",
1167            0xC2 if bytes.get(i + 1) == Some(&0xA0) => "&nbsp;",
1168            _ => {
1169                i += 1;
1170                continue;
1171            }
1172        };
1173        out.push_str(&s[from..i]);
1174        out.push_str(replacement);
1175        i += if bytes[i] == 0xC2 { 2 } else { 1 };
1176        from = i;
1177    }
1178    out.push_str(&s[from..]);
1179}
1180
1181#[cfg(test)]
1182mod tests {
1183    use crate::{Ns, SerializeOptions, parse, parse_fragment};
1184
1185    fn body(html: &str) -> String {
1186        let doc = parse(html, false);
1187        let html_el = doc
1188            .children(0)
1189            .find(|&c| {
1190                doc.template_contents(c).is_none()
1191                    && matches!(doc.kind(c), crate::Kind::Element { .. })
1192            })
1193            .unwrap();
1194        let body = doc.children(html_el).nth(1).unwrap();
1195        doc.inner_html(body)
1196    }
1197
1198    #[test]
1199    fn a_document_or_template_contents_alone_is_empty() {
1200        let doc = parse("<!DOCTYPE html><template><b>x</b></template><p>y", false);
1201        assert_eq!(doc.html_alone(doc.root()), "");
1202        let template = (0..doc.len() as crate::NodeId)
1203            .find_map(|n| doc.template_contents(n))
1204            .unwrap();
1205        assert_eq!(doc.html_alone(template), "");
1206        let fragment = parse_fragment("<b>x</b>", Ns::Html, "div", false);
1207        assert_eq!(fragment.html_alone(fragment.root()), "");
1208        // The rest are as before.
1209        let doctype = doc.children(doc.root()).next().unwrap();
1210        assert_eq!(doc.html_alone(doctype), "<!DOCTYPE html>");
1211    }
1212
1213    #[test]
1214    fn a_document_round_trips() {
1215        let doc = parse(
1216            "<!DOCTYPE html><html><head><title>T</title></head><body><p class=\"a\">x</p></body></html>",
1217            false,
1218        );
1219        assert_eq!(
1220            doc.inner_html(0),
1221            "<!DOCTYPE html><html><head><title>T</title></head><body><p class=\"a\">x</p></body></html>"
1222        );
1223    }
1224
1225    #[test]
1226    fn text_and_attributes_are_escaped() {
1227        assert_eq!(
1228            body("<p title='a\"b<c>&d'>1 &lt; 2 &amp; 3 &gt; 0&nbsp;!</p>"),
1229            "<p title=\"a&quot;b&lt;c&gt;&amp;d\">1 &lt; 2 &amp; 3 &gt; 0&nbsp;!</p>"
1230        );
1231    }
1232
1233    #[test]
1234    fn raw_text_is_written_as_it_is() {
1235        assert_eq!(
1236            body("<body><script>if (a < b && c) {}</script>"),
1237            "<script>if (a < b && c) {}</script>"
1238        );
1239        assert_eq!(
1240            body("<body><style>a > b {}</style>"),
1241            "<style>a > b {}</style>"
1242        );
1243        assert_eq!(
1244            body("<body><noscript><b>x</b></noscript>"),
1245            "<noscript><b>x</b></noscript>"
1246        );
1247    }
1248
1249    #[test]
1250    fn void_elements_have_no_end_tag() {
1251        assert_eq!(body("<br><img src=x><input>"), "<br><img src=\"x\"><input>");
1252        let doc = parse_fragment("<br>", Ns::Html, "div", false);
1253        let br = doc.children(0).next().unwrap();
1254        assert_eq!(doc.inner_html(br), "");
1255        assert_eq!(doc.outer_html(br), "<br>");
1256    }
1257
1258    #[test]
1259    fn templates_comments_pis_and_foreign_elements() {
1260        assert_eq!(
1261            body(
1262                "<body><template><b>x</b></template><!--c--><?t d?><svg viewBox='0 0 1 1'><clipPath/></svg>"
1263            ),
1264            "<template><b>x</b></template><!--c--><?t d?><svg viewBox=\"0 0 1 1\"><clipPath></clipPath></svg>"
1265        );
1266        assert_eq!(
1267            body("<svg xlink:href=a xml:lang=en xmlns:xlink=b></svg>"),
1268            "<svg xlink:href=\"a\" xml:lang=\"en\" xmlns:xlink=\"b\"></svg>"
1269        );
1270    }
1271
1272    #[test]
1273    fn text_content_joins_every_text_node() {
1274        let doc = parse("<p>a<b>b</b>c</p>", false);
1275        assert!(doc.text(0).ends_with("abc"));
1276    }
1277
1278    fn with(html: &str, o: &SerializeOptions) -> String {
1279        let doc = parse(html, false);
1280        doc.serialize_with(doc.root(), o)
1281    }
1282
1283    #[test]
1284    fn the_defaults_are_outer_html() {
1285        let html = "<!DOCTYPE html PUBLIC \"p\" \"s\"><p title='a\"b' hidden>x&nbsp;<br><script>a<b</script>";
1286        let doc = parse(html, false);
1287        assert_eq!(
1288            doc.serialize_with(0, &SerializeOptions::default()),
1289            doc.outer_html(0)
1290        );
1291        let body = (0..doc.len() as crate::NodeId)
1292            .find(|&n| doc.lower_name(n) == Some("body"))
1293            .unwrap();
1294        assert_eq!(
1295            doc.inner_html_with(body, &SerializeOptions::default()),
1296            doc.inner_html(body)
1297        );
1298    }
1299
1300    #[test]
1301    fn pretty_indents_blocks_and_leaves_inline_content_alone() {
1302        let o = SerializeOptions {
1303            pretty: true,
1304            ..SerializeOptions::default()
1305        };
1306        assert_eq!(
1307            with(
1308                "<!DOCTYPE html><title>T</title><div>\n  <p>a <b>b</b></p><ul><li>x<li>y</ul>\
1309                 <!--c--></div><pre>\n\n a</pre><p><span><i>s</i></span></p>",
1310                &o
1311            ),
1312            "<!DOCTYPE html>\n<html>\n  <head>\n    <title>T</title>\n  </head>\n  <body>\
1313             \n    <div>\n      <p>a <b>b</b></p>\n      <ul>\n        <li>x</li>\
1314             \n        <li>y</li>\n      </ul>\n      <!--c-->\n    </div>\
1315             \n    <pre>\n\n a</pre>\n    <p><span><i>s</i></span></p>\n  </body></html>"
1316        );
1317        // A span among the blocks keeps them all as they are.
1318        assert_eq!(
1319            with("<body><div><p>a</p></div><span>b</span>", &o),
1320            "<html>\n  <head></head>\n  <body><div><p>a</p></div><span>b</span></body></html>"
1321        );
1322        // Nothing after `</body>` gets a new line: the parser would put it
1323        // at the end of the body.
1324        assert_eq!(
1325            with("<p>x</p></body><!--after-->", &o),
1326            "<html>\n  <head></head>\n  <body>\n    <p>x</p>\n  </body><!--after--></html>"
1327        );
1328        // Inside a pre, even blocks are left alone.
1329        let doc = parse("<pre><div><p>a</p><p>b</p></div></pre>", false);
1330        let div = (0..doc.len() as crate::NodeId)
1331            .find(|&n| doc.lower_name(n) == Some("div"))
1332            .unwrap();
1333        assert_eq!(doc.serialize_with(div, &o), "<div><p>a</p><p>b</p></div>");
1334        assert_eq!(doc.inner_html_with(div, &o), "<p>a</p><p>b</p>");
1335    }
1336
1337    #[test]
1338    fn attribute_quoting_and_minimizing() {
1339        let o = SerializeOptions {
1340            quote_attr_values: false,
1341            use_best_quote_char: true,
1342            minimize_boolean_attributes: true,
1343            use_trailing_solidus: true,
1344            ..SerializeOptions::default()
1345        };
1346        assert_eq!(
1347            body_with(
1348                "<input disabled=disabled name=name value='' a=b c='d e' f='g\"h' i=\"j'k\" l='<&>'>",
1349                &o
1350            ),
1351            "<input disabled name=name value a=b c=\"d e\" f='g\"h' i=\"j'k\" l=\"&lt;&amp;&gt;\" />"
1352        );
1353        let single = SerializeOptions {
1354            quote_char: '\'',
1355            ..SerializeOptions::default()
1356        };
1357        assert_eq!(
1358            body_with("<p title=\"a'b&quot;\">", &single),
1359            "<p title='a&#39;b\"'></p>"
1360        );
1361    }
1362
1363    fn body_with(html: &str, o: &SerializeOptions) -> String {
1364        let doc = parse(html, false);
1365        let body = (0..doc.len() as crate::NodeId)
1366            .find(|&n| doc.lower_name(n) == Some("body"))
1367            .unwrap();
1368        doc.inner_html_with(body, o)
1369    }
1370
1371    #[test]
1372    fn optional_tags_are_left_out_where_the_parser_puts_them_back() {
1373        let o = SerializeOptions {
1374            omit_optional_tags: true,
1375            ..SerializeOptions::default()
1376        };
1377        assert_eq!(
1378            with(
1379                "<!DOCTYPE html><title>T</title><p>a<p>b<ul><li>c<li>d</ul>\
1380                 <table><tr><td>e<td>f</table><a><p>g</p></a>",
1381                &o
1382            ),
1383            "<!DOCTYPE html><title>T</title><p>a<p>b<ul><li>c<li>d</ul>\
1384             <table><tr><td>e<td>f</table><a><p>g</p></a>"
1385        );
1386        // A start tag with attributes is kept, and so is `<body>` before
1387        // whitespace, which would otherwise go to the head.
1388        assert_eq!(
1389            with("<html lang=en><body> <p>x", &o),
1390            "<html lang=\"en\"><body> <p>x"
1391        );
1392    }
1393
1394    #[test]
1395    fn whitespace_charset_doctype_and_raw_text_options() {
1396        let o = SerializeOptions {
1397            strip_whitespace: true,
1398            inject_meta_charset: Some("utf-8".into()),
1399            full_doctype: true,
1400            escape_rcdata: true,
1401            ..SerializeOptions::default()
1402        };
1403        assert_eq!(
1404            with(
1405                "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"x\"><meta charset=latin1>\
1406                 <meta http-equiv=Content-Type content='text/html; charset=latin1'>\
1407                 <script>a<b</script><p>a \n\t b</p><pre> a  b</pre>",
1408                &o
1409            ),
1410            "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"x\"><html><head>\
1411             <meta charset=\"utf-8\"><meta http-equiv=\"Content-Type\" \
1412             content=\"text/html; charset=utf-8\"><script>a&lt;b</script></head>\
1413             <body><p>a b</p><pre> a  b</pre></body></html>"
1414        );
1415        assert_eq!(
1416            with("<title>t</title>", &o),
1417            "<html><head><meta charset=\"utf-8\"><title>t</title></head><body></body></html>"
1418        );
1419    }
1420
1421    #[test]
1422    fn the_html5lib_tree_dump() {
1423        let o = SerializeOptions {
1424            html5test: true,
1425            ..SerializeOptions::default()
1426        };
1427        let doc = parse(
1428            "<!DOCTYPE html><p b=2 a=1>x<template><i>y</i></template><svg xlink:href=z>",
1429            false,
1430        );
1431        let p = (0..doc.len() as crate::NodeId)
1432            .find(|&n| doc.lower_name(n) == Some("p"))
1433            .unwrap();
1434        assert_eq!(
1435            doc.serialize_with(p, &o),
1436            "| <p>\n|   a=\"1\"\n|   b=\"2\"\n|   \"x\"\n|   <template>\n|     content\
1437             \n|       <i>\n|         \"y\"\n|   <svg svg>\n|     xlink href=\"z\""
1438        );
1439        assert_eq!(doc.inner_html_with(p, &o).lines().next(), Some("| \"x\""));
1440    }
1441}
1442
1443#[cfg(test)]
1444mod deep {
1445    use crate::{SerializeOptions, parse};
1446
1447    /// Serializing recursed once per level and overflowed the stack on deep
1448    /// pages; Netweir parses on threads with 2 MB stacks.
1449    #[test]
1450    fn deep_trees_serialize_on_a_small_stack() {
1451        let html = "<div>".repeat(20_000);
1452        let out = std::thread::Builder::new()
1453            .stack_size(256 * 1024)
1454            .spawn(move || {
1455                let doc = crate::parse(&html, false);
1456                for o in [
1457                    crate::SerializeOptions {
1458                        pretty: true,
1459                        ..Default::default()
1460                    },
1461                    crate::SerializeOptions {
1462                        html5test: true,
1463                        ..Default::default()
1464                    },
1465                ] {
1466                    assert!(!doc.serialize_with(0, &o).is_empty());
1467                }
1468                doc.inner_html(0).len()
1469            })
1470            .unwrap()
1471            .join()
1472            .unwrap();
1473        assert_eq!(
1474            out,
1475            "<html><head></head><body></body></html>".len() + 20_000 * 11
1476        );
1477    }
1478
1479    /// The parser drops a newline that starts a pre's, a textarea's or a
1480    /// listing's text, and the HTML Standard's serialization doesn't put
1481    /// one back, so `pretty`, which promises the same page, lost one.
1482    /// The standard's own output is left as the standard has it.
1483    #[test]
1484    fn pretty_keeps_the_newline_a_pre_starts_with() {
1485        let pretty = SerializeOptions {
1486            pretty: true,
1487            ..SerializeOptions::default()
1488        };
1489        for tag in ["pre", "textarea", "listing"] {
1490            let html = format!("<{tag}>\n\nx</{tag}>");
1491            let doc = parse(&html, false);
1492            let text = |doc: &crate::Document| {
1493                let el = (0..doc.len() as crate::NodeId)
1494                    .find(|&n| doc.lower_name(n) == Some(tag))
1495                    .unwrap();
1496                doc.text(el)
1497            };
1498            let again = parse(&doc.serialize_with(doc.root(), &pretty), false);
1499            assert_eq!(text(&again), text(&doc), "{tag}");
1500            assert_eq!(text(&doc), "\nx");
1501            assert!(
1502                doc.outer_html(doc.root())
1503                    .contains(&format!("<{tag}>\nx</{tag}>"))
1504            );
1505        }
1506        // Text that doesn't start with one, or isn't first, gets nothing.
1507        let doc = parse("<pre>x\n</pre><pre><b>\nb</b></pre>", false);
1508        let out = doc.serialize_with(doc.root(), &pretty);
1509        assert!(
1510            out.contains("<pre>x\n</pre>") && out.contains("<pre><b>\nb</b></pre>"),
1511            "{out}"
1512        );
1513    }
1514
1515    /// Two spaces a level for every level made 100,000 nested divs a
1516    /// 17 GB string.
1517    #[test]
1518    fn pretty_stops_indenting_past_a_hundred_levels() {
1519        let pretty = SerializeOptions {
1520            pretty: true,
1521            ..SerializeOptions::default()
1522        };
1523        let doc = parse(&"<div>".repeat(20_000), false);
1524        let out = doc.serialize_with(doc.root(), &pretty);
1525        assert!(out.len() < 20_000 * 2 * 220, "{} bytes", out.len());
1526        assert!(out.contains(&format!("\n{}<div>", " ".repeat(200))));
1527        assert!(!out.contains(&" ".repeat(202)));
1528    }
1529}