Debian Codegraph @

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

raw
1 //! Support for hiding code lines.
2
3 use crate::html::{Element, Node};
4 use ego_tree::{NodeId, Tree};
5 use html5ever::tendril::StrTendril;
6 use mdbook_core::static_regex;
7 use std::collections::HashMap;
8
9 /// Wraps hidden lines in a `<span>` for the given code block.
10 pub(crate) fn hide_lines(
11 tree: &mut Tree<Node>,
12 code_id: NodeId,
13 hidelines: &HashMap<String, String>,
14 ) {
15 let mut node = tree.get_mut(code_id).unwrap();
16 let el = node.value().as_element().unwrap();
17
18 let classes: Vec<_> = el.attr("class").unwrap_or_default().split(' ').collect();
19 let language = classes
20 .iter()
21 .filter_map(|cls| cls.strip_prefix("language-"))
22 .next()
23 .unwrap_or_default()
24 .to_string();
25 let hideline_info = classes
26 .iter()
27 .filter_map(|cls| cls.strip_prefix("hidelines="))
28 .map(|prefix| prefix.to_string())
29 .next();
30
31 if let Some(mut child) = node.first_child()
32 && let Node::Text(text) = child.value()
33 {
34 if language == "rust" {
35 let new_nodes = hide_lines_rust(text);
36 child.detach();
37 let root = tree.extend_tree(new_nodes);
38 let root_id = root.id();
39 let mut node = tree.get_mut(code_id).unwrap();
40 node.reparent_from_id_append(root_id);
41 } else {
42 // Use the prefix from the code block, else the prefix from config.
43 let hidelines_prefix = hideline_info
44 .as_deref()
45 .or_else(|| hidelines.get(&language).map(|p| p.as_str()));
46 if let Some(prefix) = hidelines_prefix {
47 let new_nodes = hide_lines_with_prefix(text, prefix);
48 child.detach();
49 let root = tree.extend_tree(new_nodes);
50 let root_id = root.id();
51 let mut node = tree.get_mut(code_id).unwrap();
52 node.reparent_from_id_append(root_id);
53 }
54 }
55 }
56 }
57
58 /// Wraps hidden lines in a `<span>` specifically for Rust code blocks.
59 fn hide_lines_rust(text: &StrTendril) -> Tree<Node> {
60 static_regex!(BORING_LINES_REGEX, r"^(\s*)#(.?)(.*)$");
61
62 let mut tree = Tree::new(Node::Fragment);
63 let mut root = tree.root_mut();
64 let mut lines = text.lines().peekable();
65 while let Some(line) = lines.next() {
66 // Don't include newline on the last line.
67 let newline = if lines.peek().is_none() { "" } else { "\n" };
68 if let Some(caps) = BORING_LINES_REGEX.captures(line) {
69 if &caps[2] == "#" {
70 root.append(Node::Text(
71 format!("{}{}{}{newline}", &caps[1], &caps[2], &caps[3]).into(),
72 ));
73 continue;
74 } else if matches!(&caps[2], "" | " ") {
75 let mut span = Element::new("span");
76 span.insert_attr("class", "boring".into());
77 let mut span = root.append(Node::Element(span));
78 span.append(Node::Text(
79 format!("{}{}{newline}", &caps[1], &caps[3]).into(),
80 ));
81 continue;
82 }
83 }
84 root.append(Node::Text(format!("{line}{newline}").into()));
85 }
86 tree
87 }
88
89 /// Wraps hidden lines in a `<span>` tag for lines starting with the given prefix.
90 fn hide_lines_with_prefix(content: &str, prefix: &str) -> Tree<Node> {
91 let mut tree = Tree::new(Node::Fragment);
92 let mut root = tree.root_mut();
93 for line in content.lines() {
94 if line.trim_start().starts_with(prefix) {
95 let pos = line.find(prefix).unwrap();
96 let (ws, rest) = (&line[..pos], &line[pos + prefix.len()..]);
97 let mut span = Element::new("span");
98 span.insert_attr("class", "boring".into());
99 let mut span = root.append(Node::Element(span));
100 span.append(Node::Text(format!("{ws}{rest}\n").into()));
101 } else {
102 root.append(Node::Text(format!("{line}\n").into()));
103 }
104 }
105 tree
106 }
107
108 /// If this code text is missing an `fn main`, the wrap it with `fn main` in a
109 /// fashion similar to rustdoc, with the wrapper hidden.
110 pub(crate) fn wrap_rust_main(text: &str) -> Option<String> {
111 if !text.contains("fn main") && !text.contains("quick_main!") {
112 let (attrs, code) = partition_rust_source(text);
113 let newline = if code.is_empty() || code.ends_with('\n') {
114 ""
115 } else {
116 "\n"
117 };
118 Some(format!(
119 "# #![allow(unused)]\n{attrs}# fn main() {{\n{code}{newline}# }}"
120 ))
121 } else {
122 None
123 }
124 }
125
126 /// Splits Rust inner attributes from the given source string.
127 ///
128 /// Returns `(inner_attrs, rest_of_code)`.
129 fn partition_rust_source(s: &str) -> (&str, &str) {
130 static_regex!(
131 HEADER_RE,
132 r"^(?mx)
133 (
134 (?:
135 ^[ \t]*\#!\[.* (?:\r?\n)?
136 |
137 ^\s* (?:\r?\n)?
138 )*
139 )"
140 );
141 let split_idx = match HEADER_RE.captures(s) {
142 Some(caps) => {
143 let attributes = &caps[1];
144 if attributes.trim().is_empty() {
145 // Don't include pure whitespace as an attribute. The
146 // whitespace in the regex is intended to handle multiple
147 // attributes *separated* by potential whitespace.
148 0
149 } else {
150 attributes.len()
151 }
152 }
153 None => 0,
154 };
155 s.split_at(split_idx)
156 }
157
158 #[test]
159 fn it_partitions_rust_source() {
160 assert_eq!(partition_rust_source(""), ("", ""));
161 assert_eq!(partition_rust_source("let x = 1;"), ("", "let x = 1;"));
162 assert_eq!(
163 partition_rust_source("fn main()\n{ let x = 1; }\n"),
164 ("", "fn main()\n{ let x = 1; }\n")
165 );
166 assert_eq!(
167 partition_rust_source("#![allow(foo)]"),
168 ("#![allow(foo)]", "")
169 );
170 assert_eq!(
171 partition_rust_source("#![allow(foo)]\n"),
172 ("#![allow(foo)]\n", "")
173 );
174 assert_eq!(
175 partition_rust_source("#![allow(foo)]\nlet x = 1;"),
176 ("#![allow(foo)]\n", "let x = 1;")
177 );
178 assert_eq!(
179 partition_rust_source(
180 "\n\
181 #![allow(foo)]\n\
182 \n\
183 #![allow(bar)]\n\
184 \n\
185 let x = 1;"
186 ),
187 ("\n#![allow(foo)]\n\n#![allow(bar)]\n\n", "let x = 1;")
188 );
189 assert_eq!(
190 partition_rust_source(" // Example"),
191 ("", " // Example")
192 );
193 }