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