Debian Codegraph @

crates/mdbook-html/src/html/tree.rs

raw ◀ ▶
1 Debian patch touch this file
1 //! Tree data structure for representing a markdown document.
2 //!
3 //! [`MarkdownTreeBuilder::build`] is the primary entry point of this module.
4 //! It takes events from [`pulldown_cmark`], and generates a [`Tree`]
5 //! structure of [`Node`] elements. It also handles all the various
6 //! transformations that mdbook performs, such as creating header links.
7
8 use super::tokenizer::parse_html;
9 use super::{HtmlRenderOptions, hide_lines, wrap_rust_main};
10 use crate::utils::{id_from_content, unique_id};
11 use ego_tree::{NodeId, NodeRef, Tree};
12 use html5ever::tendril::{SliceExt, StrTendril};
13 use html5ever::tokenizer::{TagKind, Token};
14 use html5ever::{LocalName, QualName};
15 use indexmap::IndexMap;
16 use mdbook_core::config::RustEdition;
17 use mdbook_core::static_regex;
18 use pulldown_cmark::{Alignment, CodeBlockKind, CowStr, Event, LinkType, Tag, TagEnd};
19 use std::borrow::Cow;
20 use std::collections::{HashMap, HashSet};
21 use std::ops::Deref;
22 use tracing::{trace, warn};
23
24 /// Helper to create a [`QualName`].
25 macro_rules! attr_qual_name {
26 ($name:expr) => {
27 QualName::new(None, html5ever::ns!(), LocalName::from($name))
28 };
29 }
30
31 /// A node in the [`Tree`].
32 #[derive(Debug)]
33 pub(crate) enum Node {
34 /// An HTML [`Element`].
35 Element(Element),
36 /// Plain text.
37 ///
38 /// This will be escaped when serialized.
39 Text(StrTendril),
40 /// An HTML comment.
41 Comment(StrTendril),
42 /// Root node of a tree fragment.
43 ///
44 /// This is a general purpose node whenever it is convenient to have a
45 /// container of other nodes.
46 Fragment,
47 /// Raw data that should be copied into the output as-is without escaping.
48 RawData(StrTendril),
49 }
50
51 impl Node {
52 /// If this is an [`Element`], return it.
53 pub(crate) fn as_element(&self) -> Option<&Element> {
54 if let Node::Element(el) = self {
55 Some(el)
56 } else {
57 None
58 }
59 }
60
61 /// If this is an [`Element`], return it (mutable).
62 fn as_element_mut(&mut self) -> Option<&mut Element> {
63 if let Node::Element(el) = self {
64 Some(el)
65 } else {
66 None
67 }
68 }
69 }
70
71 /// An HTML element.
72 #[derive(Debug, Clone)]
73 pub(crate) struct Element {
74 /// The tag name.
75 pub(crate) name: QualName,
76 /// Element attributes.
77 pub(crate) attrs: Attributes,
78 /// True if this tag ends with `/>`.
79 pub(crate) self_closing: bool,
80 /// True if this was raw HTML written in the markdown.
81 pub(crate) was_raw: bool,
82 }
83
84 impl Element {
85 /// Creates a new HTML element.
86 pub(crate) fn new(tag_name: &str) -> Element {
87 let name = QualName::new(None, html5ever::ns!(html), LocalName::from(tag_name));
88 Element {
89 name,
90 attrs: Attributes::new(),
91 self_closing: false,
92 was_raw: false,
93 }
94 }
95
96 /// The name of this element.
97 pub(crate) fn name(&self) -> &str {
98 self.name.local.deref()
99 }
100
101 /// If this is a heading element, returns the level of the heading.
102 #[allow(dead_code, reason = "currently only used in search")]
103 pub(crate) fn heading_level(&self) -> Option<u8> {
104 let name = self.name();
105 if matches!(name, "h1" | "h2" | "h3" | "h4" | "h5" | "h6") {
106 Some(name.as_bytes()[1] - b'0')
107 } else {
108 None
109 }
110 }
111
112 /// Returns the value of an attribute.
113 pub(crate) fn attr(&self, name: &str) -> Option<&str> {
114 let qname = attr_qual_name!(name);
115 self.attrs.get(&qname).map(Deref::deref)
116 }
117
118 /// Inserts an attribute.
119 pub(crate) fn insert_attr(&mut self, name: &str, value: StrTendril) {
120 let name = attr_qual_name!(name);
121 self.attrs.insert(name, value);
122 }
123 }
124
125 /// A map of attributes on an [`Element`].
126 type Attributes = IndexMap<QualName, StrTendril>;
127
128 /// Helper to convert [`CowStr`] to a [`StrTendril`].
129 trait ToTendril {
130 /// Converts self to a [`StrTendril`].
131 fn into_tendril(self) -> StrTendril;
132 }
133
134 impl ToTendril for CowStr<'_> {
135 fn into_tendril(self) -> StrTendril {
136 match self {
137 CowStr::Boxed(s) => {
138 let s: String = s.into();
139 StrTendril::from(s)
140 }
141 CowStr::Borrowed(s) => StrTendril::from(s),
142 CowStr::Inlined(s) => StrTendril::from(s.as_ref()),
143 }
144 }
145 }
146
147 /// Tracks the current state of parsing a table.
148 ///
149 /// This is used to determine if it should generate `<th>` or `<td>` tags.
150 enum TableState {
151 /// Currently in the table head.
152 Head,
153 /// Currently in the table body.
154 Body,
155 }
156
157 /// A builder used to create a [`Tree`] of [`Node`] elements.
158 ///
159 /// Parts of this are based on pulldown-cmark's serializer (like table handling).
160 pub(crate) struct MarkdownTreeBuilder<'opts, 'event, EventIter> {
161 /// [`pulldown_cmark`] iterator of [`pulldown_cmark::Event`] elements.
162 events: EventIter,
163 /// Options for how to generate the HTML.
164 options: &'opts HtmlRenderOptions<'opts>,
165 /// The tree that is being built.
166 tree: Tree<Node>,
167 /// The ID of the current [`Node`].
168 current_node: NodeId,
169 /// The tag stack.
170 ///
171 /// This is used to set the `current_node` as the parser enters and leaves
172 /// a tag.
173 tag_stack: Vec<NodeId>,
174 /// When parsing a table, whether or not we are currently in the head or
175 /// the body.
176 table_state: TableState,
177 /// When parsing a table, the alignments of the columns.
178 ///
179 /// The count should match the number of columns.
180 table_alignments: Vec<Alignment>,
181 /// What parsing a table, the index of the current column.
182 table_cell_index: usize,
183 /// Mapping of footnote numbers.
184 ///
185 /// This is used for generating linkbacks in the definitions.
186 ///
187 /// This is a map of `name -> (number, count)`.
188 ///
189 /// - `name` is the name of the footnote.
190 /// - `number` is the footnote number displayed in the output.
191 /// - `count` is the number of references to this footnote (used for multiple
192 /// linkbacks, and checking for unused footnotes).
193 footnote_numbers: HashMap<CowStr<'event>, (usize, u32)>,
194 /// Footnote definitions.
195 ///
196 /// This is a map of `name -> NodeId` of each footnote definition. When
197 /// parsing footnotes, they are initially left in the position where they
198 /// were defined as an `<li>` tag. The [`NodeId`] here is the id of that
199 /// tag. After the document has been parsed, all the definitions are moved
200 /// to the end of the document.
201 footnote_defs: HashMap<CowStr<'event>, NodeId>,
202 }
203
204 impl<'opts, 'event, EventIter> MarkdownTreeBuilder<'opts, 'event, EventIter>
205 where
206 EventIter: Iterator<Item = Event<'event>>,
207 {
208 /// Processes a [`pulldown_cmark`] iterator of [`pulldown_cmark::Event`]
209 /// values, and generates a tree of [`Node`] values.
210 pub(crate) fn build(options: &'opts HtmlRenderOptions<'opts>, events: EventIter) -> Tree<Node> {
211 let tree = Tree::new(Node::Fragment);
212 let root = tree.root().id();
213
214 let mut builder = Self {
215 events,
216 options,
217 tree,
218 current_node: root,
219 tag_stack: vec![root],
220 table_state: TableState::Head,
221 table_alignments: Vec::new(),
222 table_cell_index: 0,
223 footnote_numbers: HashMap::new(),
224 footnote_defs: HashMap::new(),
225 };
226 builder.process_events();
227 builder.add_header_links();
228 builder.update_code_blocks();
229 builder.convert_fontawesome();
230 builder.tree
231 }
232
233 /// Append a new child to the current node.
234 ///
235 /// Returns the [`NodeId`] of the new node.
236 fn append(&mut self, node: Node) -> NodeId {
237 self.tree
238 .get_mut(self.current_node)
239 .unwrap()
240 .append(node)
241 .id()
242 }
243
244 /// Appends text to the current node.
245 ///
246 /// If the previous sibling is a text node, then it merges with that node.
247 /// This makes some processing more convenient.
248 fn append_text(&mut self, text: StrTendril) {
249 let mut current = self.tree.get_mut(self.current_node).unwrap();
250 if let Some(mut prev) = current.last_child()
251 && let Node::Text(prev_text) = prev.value()
252 {
253 prev_text.push_slice(&text);
254 } else {
255 self.append(Node::Text(text));
256 }
257 }
258
259 /// Append a new child to the current node, and make the new node the current node.
260 ///
261 /// This should only be used if you expect `pop` to be called.
262 fn push(&mut self, node: Node) {
263 let new_node = self.append(node);
264 self.tag_stack.push(new_node);
265 self.current_node = new_node;
266 }
267
268 /// Append a new child to the current node, and make the new node the current node.
269 ///
270 /// As compared to `push`, it is *not* expected that there will be a `pop` called
271 /// for this node. The next call to `pop` will unwind the stack past this node.
272 fn push_no_stack(&mut self, node: Node) {
273 let new_node = self.append(node);
274 self.current_node = new_node;
275 }
276
277 /// Switch the current node to the current node's parent.
278 fn pop(&mut self) {
279 self.tag_stack.pop();
280 if let Some(&parent) = self.tag_stack.last() {
281 self.current_node = parent;
282 } else {
283 panic!("pop too far processing `{}`", self.options.path.display());
284 }
285 }
286
287 /// Returns all of the [`NodeId`]s, filtering out just the [`Element`]
288 /// nodes where the given callback returns `true` based on the element
289 /// name.
290 fn node_ids_for_tag(&self, filter: &dyn Fn(&str) -> bool) -> Vec<NodeId> {
291 self.tree
292 .nodes()
293 .filter(|node| {
294 let Node::Element(el) = node.value() else {
295 return false;
296 };
297 filter(el.name())
298 })
299 .map(|node| node.id())
300 .collect()
301 }
302
303 /// The main processing loop. Processes all events until the end.
304 fn process_events(&mut self) {
305 while let Some(event) = self.events.next() {
306 trace!("event={event:?}");
307 match event {
308 Event::Start(tag) => self.start_tag(tag),
309 Event::End(tag) => self.end_tag(tag),
310 Event::Text(text) => {
311 self.append_text(text.into_tendril());
312 }
313 Event::Code(code) => {
314 self.push(Node::Element(Element::new("code")));
315 self.append(Node::Text(code.into_tendril()));
316 self.pop();
317 }
318 Event::InlineMath(text) => {
319 let mut span = Element::new("span");
320 span.insert_attr("class", "math math-inline".into());
321 self.push(Node::Element(span));
322 self.append(Node::Text(text.into_tendril()));
323 self.pop();
324 }
325 Event::DisplayMath(text) => {
326 let mut span = Element::new("span");
327 span.insert_attr("class", "math math-display".into());
328 self.push(Node::Element(span));
329 self.append(Node::Text(text.into_tendril()));
330 self.pop();
331 }
332 Event::Html(html) => {
333 // The loop in Tag::HtmlBlock should have consumed all
334 // Html events.
335 panic!(
336 "`{}` unexpected Html event: {html}",
337 self.options.path.display()
338 );
339 }
340 Event::InlineHtml(html) => self.append_html(&html),
341 Event::FootnoteReference(name) => self.footnote_reference(name),
342 Event::SoftBreak => {
343 self.append_text("\n".into());
344 }
345 Event::HardBreak => {
346 self.append(Node::Element(Element::new("br")));
347 }
348 Event::Rule => {
349 self.append(Node::Element(Element::new("hr")));
350 }
351 Event::TaskListMarker(checked) => {
352 let mut input = Element::new("input");
353 input.insert_attr("disabled", "".into());
354 input.insert_attr("type", "checkbox".into());
355 if checked {
356 input.insert_attr("checked", "".into());
357 }
358 self.push(Node::Element(input));
359 // Add some space before whatever follows.
360 self.append(Node::Text(" ".into()));
361 self.pop();
362 }
363 }
364 }
365 self.finish_stack();
366 self.collect_footnote_defs();
367 }
368
369 fn start_tag(&mut self, tag: Tag<'event>) {
370 let element = match tag {
371 Tag::Paragraph => Element::new("p"),
372 Tag::Heading {
373 level,
374 id,
375 classes,
376 attrs,
377 } => {
378 let mut el = Element::new(&level.to_string());
379 for (name, value) in attrs {
380 let name =
381 QualName::new(None, html5ever::ns!(), LocalName::from(Cow::from(name)));
382 let value = value.unwrap_or_else(|| CowStr::from(""));
383 el.attrs.insert(name, value.into_tendril());
384 }
385 if let Some(id) = id {
386 el.insert_attr("id", id.into_tendril());
387 }
388 if !classes.is_empty() {
389 let classes = classes.join(" ");
390 el.insert_attr("class", classes.into());
391 }
392 el
393 }
394 Tag::BlockQuote(kind) => {
395 let mut b = Element::new("blockquote");
396 if let Some(kind) = kind {
397 let (class_kind, icon, text) = super::admonitions::select_tag(kind);
398 let class = format!("blockquote-tag blockquote-tag-{class_kind}");
399 b.insert_attr("class", class.into());
400 self.push(Node::Element(b));
401
402 let mut title = Element::new("p");
403 title.insert_attr("class", "blockquote-tag-title".into());
404 self.push(Node::Element(title));
405
406 let mut svg = Element::new("svg");
407 svg.insert_attr("viewbox", "0 0 16 16".into());
408 svg.insert_attr("width", "18".into());
409 svg.insert_attr("height", "18".into());
410 self.push(Node::Element(svg));
411 self.append_html(icon);
412 self.pop();
413
414 self.append(Node::Text(text.into()));
415
416 self.pop();
417 return;
418 }
419 b
420 }
421 Tag::CodeBlock(kind) => {
422 let mut code = Element::new("code");
423 match kind {
424 CodeBlockKind::Fenced(info) => {
425 let mut infos =
426 info.split([' ', '\t', ',']).filter(|info| !info.is_empty());
427 if let Some(lang) = infos.next() {
428 let mut classes = String::with_capacity(info.len() + 10);
429 // The first element in the infostring is treated as the language.
430 classes.push_str("language-");
431 classes.push_str(lang);
432 // The rest are just added as classes.
433 while let Some(info) = infos.next() {
434 classes.push(' ');
435 classes.push_str(info);
436 }
437 code.insert_attr("class", classes.into());
438 }
439 }
440 CodeBlockKind::Indented => {}
441 }
442 self.push_no_stack(Node::Element(Element::new("pre")));
443 code
444 }
445 Tag::HtmlBlock => {
446 // To process the HTML correctly, this needs to
447 // collect it all into a single string.
448 let mut html = String::new();
449 while let Some(event) = self.events.next() {
450 match event {
451 Event::Html(text) | Event::Text(text) => html.push_str(&text),
452 Event::End(TagEnd::HtmlBlock) => break,
453 _ => panic!(
454 "`{}` unexpected event in html block {event:?}",
455 self.options.path.display()
456 ),
457 }
458 }
459 self.append_html(&html);
460 // TagEnd::HtmlBlock must not pop.
461 return;
462 }
463 Tag::List(Some(start)) => {
464 let mut ol = Element::new("ol");
465 if start != 1 {
466 ol.insert_attr("start", format!("{start}").into());
467 }
468 ol
469 }
470 Tag::List(None) => Element::new("ul"),
471 Tag::Item => Element::new("li"),
472 Tag::FootnoteDefinition(name) => {
473 if self.footnote_defs.contains_key(&name) {
474 warn!(
475 "footnote `{name}` in {} defined multiple times - \
476 not updating to new definition",
477 self.options.path.display()
478 );
479 self.eat_till_end();
480 return;
481 } else {
482 let mut el = Element::new("li");
483 el.insert_attr("id", format!("footnote-{name}").into());
484 self.push(Node::Element(el));
485 self.footnote_defs.insert(name, self.current_node);
486 return;
487 }
488 }
489 Tag::DefinitionList => Element::new("dl"),
490 Tag::DefinitionListTitle => Element::new("dt"),
491 Tag::DefinitionListDefinition => Element::new("dd"),
492 Tag::Table(alignments) => {
493 self.table_alignments = alignments.clone();
494 // This div wrapper around the table is used to apply
495 // `overflow-x: auto` so that wide tables can be scrolled
496 // horizontally, rather than overflowing or scrolling the
497 // entire page. See
498 // https://github.com/rust-lang/mdBook/pull/1617
499 let mut div = Element::new("div");
500 div.insert_attr("class", "table-wrapper".into());
501 self.push_no_stack(Node::Element(div));
502 Element::new("table")
503 }
504 Tag::TableHead => {
505 self.table_state = TableState::Head;
506 self.table_cell_index = 0;
507 let thead = Element::new("thead");
508 self.push_no_stack(Node::Element(thead));
509 Element::new("tr")
510 }
511 Tag::TableRow => {
512 self.table_cell_index = 0;
513 Element::new("tr")
514 }
515 Tag::TableCell => {
516 let mut cell = match self.table_state {
517 TableState::Head => Element::new("th"),
518 TableState::Body => Element::new("td"),
519 };
520 let style = match self.table_alignments.get(self.table_cell_index) {
521 Some(&Alignment::Left) => "text-align: left",
522 Some(&Alignment::Center) => "text-align: center",
523 Some(&Alignment::Right) => "text-align: right",
524 Some(&Alignment::None) | None => "",
525 };
526 if !style.is_empty() {
527 cell.insert_attr("style", style.into());
528 }
529 cell
530 }
531 Tag::Emphasis => Element::new("em"),
532 Tag::Strong => Element::new("strong"),
533 Tag::Strikethrough => Element::new("del"),
534 Tag::Superscript => Element::new("sup"),
535 Tag::Subscript => Element::new("sub"),
536 Tag::Link {
537 link_type,
538 dest_url,
539 title,
540 id: _,
541 } => {
542 let href: StrTendril = if matches!(link_type, LinkType::Email) {
543 format!("mailto:{dest_url}").into()
544 } else {
545 fix_link(dest_url).into_tendril()
546 };
547 let mut a = Element::new("a");
548 a.insert_attr("href", href);
549 if !title.is_empty() {
550 a.insert_attr("title", title.into_tendril());
551 }
552 a
553 }
554 Tag::Image {
555 link_type: _,
556 dest_url,
557 title,
558 id: _,
559 } => {
560 let mut img = Element::new("img");
561 let src = fix_link(dest_url).into_tendril();
562 img.insert_attr("src", src);
563 if !title.is_empty() {
564 img.insert_attr("title", title.into_tendril());
565 }
566 // This will eat TagEnd::Image
567 let alt = self.text_for_img_alt();
568 img.insert_attr("alt", alt.to_tendril());
569
570 // If the image is not being rendered inside a link, we can enable the "zoom-in"
571 // feature.
572 if !self
573 .tag_stack
574 .iter()
575 .filter_map(|node_id| {
576 self.tree
577 .get(*node_id)
578 .and_then(|el| el.value().as_element())
579 })
580 .any(|el| *el.name.local == *"a")
581 {
582 let mut label = Element::new("label");
583 label.insert_attr("class", "checkbox-label".to_tendril());
584 self.push(Node::Element(label));
585
586 let mut input = Element::new("input");
587 input.insert_attr("class", "checkbox-img".to_tendril());
588 input.insert_attr("type", "checkbox".to_tendril());
589 self.append(Node::Element(input));
590
591 self.append(Node::Element(img.clone()));
592
593 let mut wrapper = Element::new("span");
594 wrapper.insert_attr("class", "img-wrapper".to_tendril());
595 self.push_no_stack(Node::Element(wrapper));
596
597 self.append(Node::Element(img));
598
599 // We exit the `label` and the `span` (which used push_no_stack).
600 self.pop();
601 } else {
602 self.append(Node::Element(img));
603 }
604 return;
605 }
606 Tag::MetadataBlock(_) => {
607 // Eat all events till the end of MetadataBlock.
608 while let Some(event) = self.events.next() {
609 if matches!(event, Event::End(TagEnd::MetadataBlock(_))) {
610 break;
611 }
612 }
613 return;
614 }
615 };
616 self.push(Node::Element(element));
617 }
618
619 fn end_tag(&mut self, tag: TagEnd) {
620 // TODO: This should validate that the event stack is properly
621 // synchronized with the tag stack. That, would likely require keeping
622 // a parallel "expected end tag" with the tag stack, since mapping a
623 // pulldown-cmark event tag to an HTML tag isn't always clear.
624 //
625 // Check for unclosed HTML tags when exiting a markdown event.
626 while let Some(node_id) = self.tag_stack.last() {
627 let node = self.tree.get(*node_id).unwrap().value();
628 let Node::Element(el) = node else {
629 break;
630 };
631 if !el.was_raw {
632 break;
633 }
634 warn!(
635 "unclosed HTML tag `<{}>` found in `{}` while exiting {tag:?}\n\
636 HTML tags must be closed before exiting a markdown element.",
637 el.name.local,
638 self.options.path.display(),
639 );
640 self.pop();
641 }
642 self.pop();
643 match tag {
644 TagEnd::TableHead => {
645 self.table_state = TableState::Body;
646 self.push(Node::Element(Element::new("tbody")));
647 }
648 TagEnd::TableCell => {
649 self.table_cell_index += 1;
650 }
651 TagEnd::Table => {
652 // Pop tbody or thead
653 self.pop();
654 }
655 _ => {}
656 }
657 }
658
659 /// Given some HTML, parse it into [`Node`] elements and append them to
660 /// the current node.
661 fn append_html(&mut self, html: &str) {
662 let tokens = parse_html(&html);
663 let mut is_raw = false;
664 for token in tokens {
665 trace!("html token={token:?}");
666 match token {
667 Token::DoctypeToken(_) => {}
668 Token::TagToken(tag) => match tag.kind {
669 TagKind::StartTag => self.start_html_tag(tag, &mut is_raw),
670 TagKind::EndTag => self.end_html_tag(tag, &mut is_raw),
671 },
672 Token::CommentToken(comment) => {
673 self.append(Node::Comment(comment));
674 }
675 Token::CharacterTokens(chars) => {
676 if is_raw {
677 self.append(Node::RawData(chars));
678 } else {
679 self.append_text(chars);
680 }
681 }
682 Token::NullCharacterToken => {}
683 Token::EOFToken => {}
684 Token::ParseError(error) => {
685 warn!(
686 "html parse error in `{}`: {error}\n\
687 Html text was:\n\
688 {html}",
689 self.options.path.display()
690 );
691 }
692 }
693 }
694 }
695
696 /// Adds an open HTML tag.
697 fn start_html_tag(&mut self, tag: html5ever::tokenizer::Tag, is_raw: &mut bool) {
698 let is_closed = is_void_element(&tag.name) || tag.self_closing;
699 *is_raw = matches!(&*tag.name, "script" | "style");
700 let name = QualName::new(None, html5ever::ns!(html), tag.name);
701 let attrs = tag
702 .attrs
703 .into_iter()
704 .map(|attr| (attr.name, attr.value))
705 .collect();
706 let mut el = Element {
707 name,
708 attrs,
709 self_closing: tag.self_closing,
710 was_raw: true,
711 };
712 fix_html_link(&mut el);
713 self.push(Node::Element(el));
714 if is_closed {
715 // No end element.
716 self.pop();
717 }
718 }
719
720 /// Closes the given HTML tag.
721 fn end_html_tag(&mut self, tag: html5ever::tokenizer::Tag, is_raw: &mut bool) {
722 *is_raw = false;
723 if self.is_html_tag_matching(&tag.name) {
724 self.pop();
725 } else {
726 // The proper thing to do here is to recover. However, the HTML
727 // parsing algorithm for that is quite complex. See
728 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inbody
729 // and the adoption agency algorithm.
730 warn!(
731 "unexpected HTML end tag `</{}>` found in `{}`\n\
732 Check that the HTML tags are properly balanced.",
733 tag.name,
734 self.options.path.display()
735 );
736 }
737 }
738
739 /// This is used to verify HTML parsing keeps the stack of tags in sync.
740 fn is_html_tag_matching(&self, name: &str) -> bool {
741 let current = self.tree.get(self.current_node).unwrap().value();
742 if let Node::Element(el) = current
743 && el.name() == name
744 {
745 true
746 } else {
747 false
748 }
749 }
750
751 /// Eats all pulldown-cmark events until the next `End` matching the
752 /// current nesting level.
753 fn eat_till_end(&mut self) {
754 let mut nest = 0;
755 while let Some(event) = self.events.next() {
756 match event {
757 Event::Start(_) => nest += 1,
758 Event::End(_) => {
759 if nest == 0 {
760 break;
761 }
762 nest -= 1;
763 }
764 _ => {}
765 }
766 }
767 }
768
769 /// Eats events generating a plain text string, stripping out any
770 /// formatting elements.
771 fn text_for_img_alt(&mut self) -> String {
772 let mut nest = 0;
773 let mut output = String::new();
774 while let Some(event) = self.events.next() {
775 match event {
776 Event::Start(_) => nest += 1,
777 Event::End(_) => {
778 if nest == 0 {
779 break;
780 }
781 nest -= 1;
782 }
783 Event::Html(_) => {}
784 Event::InlineHtml(text) | Event::Code(text) | Event::Text(text) => {
785 output.push_str(&text);
786 }
787 Event::InlineMath(text) => {
788 output.push('$');
789 output.push_str(&text);
790 output.push('$');
791 }
792 Event::DisplayMath(text) => {
793 output.push_str("$$");
794 output.push_str(&text);
795 output.push_str("$$");
796 }
797 Event::SoftBreak | Event::HardBreak | Event::Rule => output.push(' '),
798 Event::FootnoteReference(_) => {}
799 Event::TaskListMarker(_) => {}
800 }
801 }
802 output
803 }
804
805 /// Deals with any unclosed elements on the stack.
806 fn finish_stack(&mut self) {
807 while let Some(node_id) = self.tag_stack.pop() {
808 let node = self.tree.get(node_id).unwrap().value();
809 match node {
810 Node::Fragment => {}
811 Node::Element(el) => {
812 if el.was_raw {
813 warn!(
814 "unclosed HTML tag `<{}>` found in `{}`",
815 el.name.local,
816 self.options.path.display()
817 );
818 } else {
819 panic!(
820 "internal error: expected empty tag stack.\n
821 path: `{}`\n\
822 element={el:?}",
823 self.options.path.display()
824 );
825 }
826 }
827 node => {
828 panic!(
829 "internal error: expected empty tag stack.\n
830 path: `{}`\n\
831 node={node:?}",
832 self.options.path.display()
833 );
834 }
835 }
836 }
837 }
838
839 /// Appends a new footnote reference.
840 fn footnote_reference(&mut self, name: CowStr<'event>) {
841 let len = self.footnote_numbers.len() + 1;
842 let (n, count) = self
843 .footnote_numbers
844 .entry(name.clone())
845 .or_insert((len, 0));
846 *count += 1;
847 let (n, count) = (*n, *count);
848
849 let current = self.tree.get(self.current_node).unwrap();
850 if let Some(last) = current.last_child()
851 && let Node::Element(el) = last.value()
852 {
853 if el.attr("class") == Some("footnote-reference") {
854 self.append(Node::Text(" ".into()));
855 }
856 }
857 let mut sup = Element::new("sup");
858 sup.insert_attr("class", "footnote-reference".into());
859 let id = format!("fr-{name}-{count}");
860 sup.insert_attr("id", id.into());
861 self.push(Node::Element(sup));
862 let mut a = Element::new("a");
863 a.insert_attr("href", format!("#footnote-{name}").into());
864 self.push(Node::Element(a));
865 self.append(Node::Text(format!("{n}").into()));
866 self.pop(); // a
867 self.pop(); // sup
868 }
869
870 /// This is used after parsing is complete to move the footnote
871 /// definitions to the end of the document.
872 fn collect_footnote_defs(&mut self) {
873 if self.footnote_defs.is_empty() {
874 return;
875 }
876 let defs = std::mem::take(&mut self.footnote_defs);
877 let mut defs: Vec<_> = defs.into_iter().collect();
878 // Detach nodes and remove unused.
879 defs.retain(|(name, def_id)| {
880 let mut node = self.tree.get_mut(*def_id).unwrap();
881 node.detach();
882
883 if !self.footnote_numbers.contains_key(name) {
884 warn!(
885 "footnote `{name}` in `{}` is defined but not referenced",
886 self.options.path.display()
887 );
888 false
889 } else {
890 true
891 }
892 });
893 defs.sort_by_cached_key(|(name, _)| self.footnote_numbers[name].0);
894
895 // Move defs to the end of the chapter.
896 self.append(Node::Element(Element::new("hr")));
897 let mut ol = Element::new("ol");
898 ol.insert_attr("class", "footnote-definition".into());
899 let ol_id = self.append(Node::Element(ol));
900 for (name, def_id) in defs {
901 // Generate the linkbacks.
902 let count = self.footnote_numbers[&name].1;
903 for usage in 1..=count {
904 let nth = if usage == 1 {
905 String::new()
906 } else {
907 usage.to_string()
908 };
909 let space = self.tree.orphan(Node::Text(" ".into())).id();
910 let mut backlink = Element::new("a");
911 backlink.insert_attr("href", format!("#fr-{name}-{usage}").into());
912 let mut backlink = self.tree.orphan(Node::Element(backlink));
913 backlink.append(Node::Text(format!("↩{nth}").into()));
914 let backlink = backlink.id();
915 let mut def = self.tree.get_mut(def_id).unwrap();
916 if let Some(mut last_child) = def.last_child()
917 && let value = last_child.value()
918 && let Node::Element(last_el) = value
919 && last_el.name() == "p"
920 {
921 // Put the linkback at the end of the last paragraph instead
922 // of on a line by itself.
923 last_child.append_id(space);
924 last_child.append_id(backlink);
925 } else {
926 // Not a clear place to put it in this circumstance, so put it
927 // at the end.
928 def.append_id(space);
929 def.append_id(backlink);
930 };
931 }
932 let mut ol = self.tree.get_mut(ol_id).unwrap();
933 ol.append_id(def_id);
934 }
935 }
936
937 /// This is used after parsing is complete to add a unique `id` attribute
938 /// to all header and dt elements, and to also add an `<a>` tag so that
939 /// clicking the element will set the current URL to that element's
940 /// fragment.
941 fn add_header_links(&mut self) {
942 let mut id_counter = HashSet::new();
943 let headings = self.node_ids_for_tag(&|name| {
944 matches!(name, "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "dt")
945 });
946 for heading in headings {
947 let node = self.tree.get(heading).unwrap();
948 let el = node.value().as_element().unwrap();
949 // Don't modify tags if they were manually written HTML. The
950 // user probably had some intent, and we don't want to mess it up.
951 if el.was_raw {
952 continue;
953 }
954 let href = if let Some(id) = el.attr("id") {
955 format!("#{id}")
956 } else {
957 let mut id = String::new();
958 let node_id = node.id();
959 let node_ref = self.tree.get(node_id).unwrap();
960 text_in_node(node_ref, &mut id);
961 let id = id_from_content(&id);
962 let id = unique_id(&id, &mut id_counter);
963 let mut node = self.tree.get_mut(heading).unwrap();
964 let el = node.value().as_element_mut().unwrap();
965 let href = format!("#{id}");
966 el.insert_attr("id", id.into());
967 href
968 };
969 // Insert an <a> element between the heading and its children.
970 let mut a = Element::new("a");
971 a.insert_attr("class", "header".into());
972 a.insert_attr("href", href.into());
973 let mut a = self.tree.orphan(Node::Element(a));
974 a.reparent_from_id_append(heading);
975 let a_id = a.id();
976 let mut node = self.tree.get_mut(heading).unwrap();
977 node.append_id(a_id);
978 }
979 }
980
981 /// This is used after parsing is complete to set the appropriate classes
982 /// on a code block, to wrap hidden lines in `<span>` tags, and to add an
983 /// `fn main() {}` wrapper for Rust code blocks.
984 fn update_code_blocks(&mut self) {
985 let mut code_ids = self.node_ids_for_tag(&|name| name == "code");
986 // The processing below assumes the code block is in a contiguous
987 // chunk. The text nodes should have been merged during event
988 // processing. I don't know exactly what this should do if it
989 // encounters code blocks with non-text nodes.
990 code_ids.retain(|id| {
991 let code = self.tree.get(*id).unwrap();
992 code.children().count() == 1
993 });
994
995 for code_id in code_ids.iter().copied() {
996 let mut node = self.tree.get_mut(code_id).unwrap();
997 let parent_id = node.parent().unwrap().id();
998 let code_el = node.value().as_element_mut().unwrap();
999 let class = code_el.attr("class").unwrap_or_default();
1000 let class_set: HashSet<_> = class.split(' ').collect();
1001 let is_editable = class_set.contains("editable");
1002 let is_playground = class_set.contains("language-rust")
1003 && ((!class_set.contains("ignore")
1004 && !class_set.contains("noplayground")
1005 && !class_set.contains("noplaypen")
1006 && self.options.config.playground.runnable)
1007 || class_set.contains("mdbook-runnable"));
1008 if !is_playground {
1009 continue;
1010 }
1011 let add_edition = if class_set.iter().any(|cls| cls.starts_with("edition")) {
1012 None
1013 } else {
1014 self.options.edition.map(|edition| match edition {
1015 RustEdition::E2015 => "edition2015",
1016 RustEdition::E2018 => "edition2018",
1017 RustEdition::E2021 => "edition2021",
1018 RustEdition::E2024 => "edition2024",
1019 _ => panic!("edition {edition:?} not covered"),
1020 })
1021 };
1022 if let Some(edition) = add_edition {
1023 code_el.insert_attr("class", format!("{class} {edition}").into());
1024 }
1025
1026 let mut node = self.tree.get_mut(code_id).unwrap();
1027 if !self.options.config.playground.editable || !is_editable {
1028 if let Some(mut child) = node.first_child()
1029 && let Node::Text(text) = child.value()
1030 {
1031 if let Some(new_text) = wrap_rust_main(text) {
1032 *text = new_text.into();
1033 }
1034 }
1035 }
1036
1037 let mut pre = self.tree.get_mut(parent_id).unwrap();
1038 let pre = pre.value().as_element_mut().unwrap();
1039 assert_eq!(pre.name(), "pre");
1040 pre.insert_attr("class", "playground".into());
1041 }
1042
1043 for code_id in code_ids {
1044 hide_lines(&mut self.tree, code_id, &self.options.config.code.hidelines);
1045 }
1046 }
1047
1048 /// This is used after parsing is complete to replace `<i>` tags with a
1049 /// `<span>` that includes the corresponding SVG code.
1050 fn convert_fontawesome(&mut self) {
•1051 use crate::fontawesome as fa;
1052
1053 let is = self.node_ids_for_tag(&|name| name == "i");
1054 for i_id in is {
1055 let mut icon = String::new();
1056 let mut type_ = fa::Type::Regular;
1057 let mut new_classes = String::from("fa-svg");
1058
1059 let mut node = self.tree.get_mut(i_id).unwrap();
1060 if node.first_child().is_some() {
1061 // Just to be safe, only translate <i></i>.
1062 continue;
1063 }
1064 let i_el = node.value().as_element().unwrap();
1065 let classes = i_el.attr("class").unwrap_or_default();
1066 for class in classes.split(" ") {
1067 if matches!(class, "fa" | "fa-regular") {
1068 type_ = fa::Type::Regular;
1069 } else if matches!(class, "fas" | "fa-solid") {
1070 type_ = fa::Type::Solid;
1071 } else if matches!(class, "fab" | "fa-brands") {
1072 type_ = fa::Type::Brands;
1073 } else if let Some(class) = class.strip_prefix("fa-") {
1074 icon = class.to_owned();
1075 } else {
1076 new_classes += " ";
1077 new_classes += class;
1078 }
1079 }
1080 if icon.is_empty() {
1081 continue;
1082 }
1083
1084 match fa::svg(type_, &icon) {
1085 Ok(svg) => {
1086 let mut span = Element::new("span");
1087 span.insert_attr("class", new_classes.into());
1088 for (name, value) in &i_el.attrs {
1089 if *name != attr_qual_name!("class") {
1090 span.attrs.insert(name.clone(), value.clone());
1091 }
1092 }
1093 *node.value() = Node::Element(span);
1094 node.append(Node::RawData(svg.into()));
1095 }
1096 Err(e) => {
1097 warn!(
1098 "failed to find Font Awesome icon for icon `{icon}` \
1099 with type `{type_}` in `{}`: {e}",
1100 self.options.path.display()
1101 );
1102 }
1103 }
1104 }
1105 }
1106 }
1107
1108 /// Traverse the given node, emitting any plain text into the output.
1109 ///
1110 /// This is used to generate the `id` of a header.
1111 fn text_in_node(node: NodeRef<'_, Node>, output: &mut String) {
1112 for child in node.children() {
1113 match child.value() {
1114 Node::Element(_) => {}
1115 Node::Text(text) => output.push_str(text),
1116 Node::Comment(_) => {}
1117 Node::Fragment => {}
1118 Node::RawData(_) => {}
1119 }
1120 text_in_node(child, output);
1121 }
1122 }
1123
1124 /// Modifies links to work with HTML.
1125 ///
1126 /// For local paths, this changes the `.md` extension to `.html`.
1127 fn fix_link<'a>(link: CowStr<'a>) -> CowStr<'a> {
1128 static_regex!(SCHEME_LINK, r"^[a-z][a-z0-9+.-]*:");
1129 static_regex!(MD_LINK, r"(?P<link>.*)\.md(?P<anchor>#.*)?");
1130
1131 if link.starts_with('#') {
1132 // Fragment-only link.
1133 return link;
1134 }
1135 // Don't modify links with schemes like `https`.
1136 if SCHEME_LINK.is_match(&link) {
1137 return link;
1138 }
1139
1140 // This is a relative link, adjust it as necessary.
1141 if let Some(caps) = MD_LINK.captures(&link) {
1142 let mut fixed_link = String::from(&caps["link"]);
1143 fixed_link.push_str(".html");
1144 if let Some(anchor) = caps.name("anchor") {
1145 fixed_link.push_str(anchor.as_str());
1146 }
1147 CowStr::from(fixed_link)
1148 } else {
1149 link
1150 }
1151 }
1152
1153 /// Calls [`fix_link`] for HTML elements.
1154 fn fix_html_link(el: &mut Element) {
1155 if el.name() != "a" {
1156 return;
1157 }
1158 for attr in ["href", "xlink:href"] {
1159 if let Some(value) = el.attr(attr) {
1160 let fixed = fix_link(value.into());
1161 el.insert_attr(attr, fixed.into_tendril());
1162 }
1163 }
1164 }
1165
1166 /// Whether or not this element name is a [void element].
1167 ///
1168 /// This is used to know whether or not to expect a `</>` end tag.
1169 ///
1170 /// [void element]: https://developer.mozilla.org/en-US/docs/Glossary/Void_element
1171 pub(crate) fn is_void_element(name: &str) -> bool {
1172 matches!(
1173 name,
1174 "area"
1175 | "base"
1176 | "br"
1177 | "col"
1178 | "embed"
1179 | "hr"
1180 | "img"
1181 | "input"
1182 | "link"
1183 | "meta"
1184 | "param"
1185 | "source"
1186 | "track"
1187 | "wbr"
1188 )
1189 }