1pub fn looks_like_html(content_type: Option<&str>, body: &str) -> bool {
13 let ct = content_type.unwrap_or("").to_ascii_lowercase();
14 if ct.contains("text/html") || ct.contains("application/xhtml") {
15 return true;
16 }
17 if ct.contains("json")
18 || ct.starts_with("image/")
19 || ct.starts_with("audio/")
20 || ct.starts_with("video/")
21 {
22 return false;
23 }
24 let head: String = body
25 .trim_start_matches('\u{feff}')
26 .trim_start()
27 .chars()
28 .take(15)
29 .collect::<String>()
30 .to_ascii_lowercase();
31 head.starts_with("<!doctype html") || head.starts_with("<html")
32}
33
34const SKIPPED: &[&str] = &["script", "style", "template", "svg", "noscript"];
36
37const BLOCKS: &[&str] = &[
39 "address",
40 "article",
41 "aside",
42 "blockquote",
43 "body",
44 "dd",
45 "details",
46 "div",
47 "dl",
48 "dt",
49 "fieldset",
50 "figcaption",
51 "figure",
52 "footer",
53 "form",
54 "h1",
55 "h2",
56 "h3",
57 "h4",
58 "h5",
59 "h6",
60 "header",
61 "hr",
62 "html",
63 "main",
64 "nav",
65 "ol",
66 "p",
67 "pre",
68 "section",
69 "table",
70 "title",
71 "ul",
72];
73
74#[derive(Default)]
75struct Out {
76 buf: String,
77 pending_breaks: u8,
79 pending_space: bool,
80}
81
82impl Out {
83 fn breaks(&mut self, n: u8) {
84 self.pending_breaks = self.pending_breaks.max(n);
85 self.pending_space = false;
86 }
87
88 fn flush_pending(&mut self) {
89 if !self.buf.is_empty() {
90 for _ in 0..self.pending_breaks {
91 self.buf.push('\n');
92 }
93 if self.pending_breaks == 0 && self.pending_space {
94 self.buf.push(' ');
95 }
96 }
97 self.pending_breaks = 0;
98 self.pending_space = false;
99 }
100
101 fn text(&mut self, s: &str) {
104 if s.starts_with(char::is_whitespace) {
105 self.pending_space = true;
106 }
107 for word in s.split_whitespace() {
108 self.flush_pending();
109 self.buf.push_str(word);
110 self.pending_space = true;
111 }
112 if !s.ends_with(char::is_whitespace) {
113 self.pending_space = false;
114 }
115 }
116
117 fn raw(&mut self, s: &str) {
119 let s = s.trim_matches('\n');
120 if s.trim().is_empty() {
121 return;
122 }
123 self.flush_pending();
124 self.buf.push_str(s);
125 self.pending_space = false;
126 }
127}
128
129pub fn to_text(html: &str) -> String {
132 let mut out = Out::default();
133 let mut pre_depth = 0usize;
134 let mut links: Vec<Option<String>> = Vec::new();
135 let mut link_start: Vec<usize> = Vec::new();
136 let mut rest = html;
137
138 while !rest.is_empty() {
139 let Some(lt) = rest.find('<') else {
140 emit_text(&mut out, rest, pre_depth > 0);
141 break;
142 };
143 emit_text(&mut out, &rest[..lt], pre_depth > 0);
144 rest = &rest[lt..];
145
146 if let Some(after) = rest.strip_prefix("<!--") {
147 rest = after.find("-->").map_or("", |i| &after[i + 3..]);
148 continue;
149 }
150 let next = rest[1..].chars().next();
151 if !matches!(next, Some(c) if c.is_ascii_alphabetic() || c == '/' || c == '!' || c == '?') {
152 emit_text(&mut out, "<", pre_depth > 0);
153 rest = &rest[1..];
154 continue;
155 }
156 let Some(end) = tag_end(rest) else {
157 break;
159 };
160 let tag = &rest[1..end];
161 rest = &rest[end + 1..];
162 if tag.starts_with('!') || tag.starts_with('?') {
163 continue;
164 }
165 let closing = tag.starts_with('/');
166 let body = tag.trim_start_matches('/').trim_end_matches('/');
167 let name_end = body
168 .find(|c: char| c.is_whitespace() || c == '/')
169 .unwrap_or(body.len());
170 let name = body[..name_end].to_ascii_lowercase();
171 let attrs = &body[name_end..];
172
173 if !closing && SKIPPED.contains(&name.as_str()) {
174 rest = skip_element(rest, &name);
175 continue;
176 }
177 match (name.as_str(), closing) {
178 ("br", _) => out.breaks(1),
179 ("li", false) => {
180 out.breaks(1);
181 out.flush_pending();
182 out.buf.push_str("- ");
183 }
184 ("tr", _) | ("li", true) => out.breaks(1),
185 ("td" | "th", false) => out.pending_space = true,
186 ("pre", false) => {
187 out.breaks(2);
188 pre_depth += 1;
189 }
190 ("pre", true) => {
191 pre_depth = pre_depth.saturating_sub(1);
192 out.breaks(2);
193 }
194 ("a", false) => {
195 links.push(attr_value(attrs, "href").filter(|h| link_worth_showing(h)));
196 link_start.push(out.buf.len());
197 }
198 ("a", true) => {
199 if let (Some(Some(href)), Some(start)) = (links.pop(), link_start.pop()) {
200 let label = out.buf.get(start..).unwrap_or("").trim();
201 if !label.is_empty() && label != href {
202 out.pending_space = true;
203 out.text(&format!("({href})"));
204 }
205 }
206 }
207 (n, _) if BLOCKS.contains(&n) => out.breaks(2),
208 _ => {}
209 }
210 }
211 let mut text = out.buf;
212 text.truncate(text.trim_end().len());
213 text
214}
215
216fn emit_text(out: &mut Out, raw: &str, in_pre: bool) {
217 if raw.is_empty() {
218 return;
219 }
220 let decoded = decode_entities(raw);
221 if in_pre {
222 out.raw(&decoded);
223 } else {
224 out.text(&decoded);
225 }
226}
227
228fn tag_end(s: &str) -> Option<usize> {
231 let mut quote: Option<char> = None;
232 for (i, c) in s.char_indices().skip(1) {
233 match (quote, c) {
234 (Some(q), c) if c == q => quote = None,
235 (Some(_), _) => {}
236 (None, '"' | '\'') => quote = Some(c),
237 (None, '>') => return Some(i),
238 _ => {}
239 }
240 }
241 None
242}
243
244fn skip_element<'a>(rest: &'a str, name: &str) -> &'a str {
246 let lower = rest.to_ascii_lowercase();
247 let needle = format!("</{name}");
248 match lower.find(&needle) {
249 Some(i) => match rest[i..].find('>') {
250 Some(j) => &rest[i + j + 1..],
251 None => "",
252 },
253 None => "",
254 }
255}
256
257fn attr_value(attrs: &str, wanted: &str) -> Option<String> {
258 let lower = attrs.to_ascii_lowercase();
259 let mut from = 0;
260 while let Some(i) = lower[from..].find(wanted) {
261 let at = from + i;
262 from = at + wanted.len();
263 let boundary = at == 0 || lower.as_bytes()[at - 1].is_ascii_whitespace();
264 let tail = attrs[from..].trim_start();
265 let Some(tail) = tail.strip_prefix('=') else {
266 continue;
267 };
268 if !boundary {
269 continue;
270 }
271 let tail = tail.trim_start();
272 let value = match tail.chars().next()? {
273 q @ ('"' | '\'') => tail[1..].split(q).next()?,
274 _ => tail.split(char::is_whitespace).next()?,
275 };
276 return Some(decode_entities(value).trim().to_string());
277 }
278 None
279}
280
281fn link_worth_showing(href: &str) -> bool {
282 let h = href.to_ascii_lowercase();
283 !h.is_empty() && !h.starts_with('#') && !h.starts_with("javascript:")
284}
285
286pub fn decode_entities(s: &str) -> String {
288 if !s.contains('&') {
289 return s.to_string();
290 }
291 let mut out = String::with_capacity(s.len());
292 let mut rest = s;
293 while let Some(i) = rest.find('&') {
294 out.push_str(&rest[..i]);
295 rest = &rest[i..];
296 let decoded = rest[1..]
297 .find(';')
298 .filter(|&n| n <= 10)
299 .and_then(|n| entity(&rest[1..1 + n]).map(|c| (c, n + 2)));
300 match decoded {
301 Some((c, len)) => {
302 out.push(c);
303 rest = &rest[len..];
304 }
305 None => {
306 out.push('&');
307 rest = &rest[1..];
308 }
309 }
310 }
311 out.push_str(rest);
312 out
313}
314
315fn entity(name: &str) -> Option<char> {
316 if let Some(num) = name.strip_prefix('#') {
317 let code = match num.strip_prefix(['x', 'X']) {
318 Some(hex) => u32::from_str_radix(hex, 16).ok()?,
319 None => num.parse().ok()?,
320 };
321 return Some(
322 char::from_u32(code)
323 .filter(|&c| c != '\0')
324 .unwrap_or('\u{fffd}'),
325 );
326 }
327 Some(match name {
328 "amp" => '&',
329 "lt" => '<',
330 "gt" => '>',
331 "quot" => '"',
332 "apos" => '\'',
333 "nbsp" => '\u{a0}',
334 "copy" => '©',
335 "reg" => '®',
336 "trade" => '™',
337 "hellip" => '…',
338 "mdash" => '—',
339 "ndash" => '–',
340 "lsquo" => '‘',
341 "rsquo" => '’',
342 "ldquo" => '“',
343 "rdquo" => '”',
344 "laquo" => '«',
345 "raquo" => '»',
346 "bull" => '•',
347 "middot" => '·',
348 "euro" => '€',
349 "pound" => '£',
350 "yen" => '¥',
351 "cent" => '¢',
352 "deg" => '°',
353 "times" => '×',
354 "larr" => '←',
355 "rarr" => '→',
356 "sect" => '§',
357 "para" => '¶',
358 _ => return None,
359 })
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 #[test]
367 fn detects_html_by_content_type_or_prefix() {
368 assert!(looks_like_html(Some("text/html; charset=utf-8"), "plain"));
369 assert!(looks_like_html(Some("application/xhtml+xml"), ""));
370 assert!(looks_like_html(None, " \n<!DOCTYPE html><p>x"));
371 assert!(looks_like_html(Some("text/plain"), "<html lang=en>"));
372 assert!(!looks_like_html(
373 Some("text/plain"),
374 "just text <html> later"
375 ));
376 assert!(!looks_like_html(Some("application/json"), "<html>"));
377 assert!(!looks_like_html(None, "{\"a\":1}"));
378 }
379
380 #[test]
381 fn strips_tags_scripts_and_comments_and_keeps_paragraphs() {
382 let html = "<!doctype html><html><head><title>Hi</title><style>p{color:red}</style>\
383 <script>var x = '<p>no</p>';</script></head><body><!-- hidden -->\
384 <h1>Heading</h1><p>First para\n with <b>bold</b> and <i>italic</i>.</p>\
385 <p>Second</p></body></html>";
386 assert_eq!(
387 to_text(html),
388 "Hi\n\nHeading\n\nFirst para with bold and italic.\n\nSecond"
389 );
390 }
391
392 #[test]
393 fn decodes_entities_named_and_numeric() {
394 assert_eq!(
395 to_text("<p>a & b <c> "d" AB … &bogus; AT&T</p>"),
396 "a & b <c> \"d\" AB … &bogus; AT&T"
397 );
398 assert_eq!(decode_entities("��"), "\u{fffd}\u{fffd}");
399 assert_eq!(to_text("x y"), "x y");
400 }
401
402 #[test]
403 fn lists_breaks_links_and_pre() {
404 let html =
405 "<ul><li>one</li><li>two <a href=\"https://e.com/x?a=1&b=2\">link</a></li></ul>\
406 line<br>next <a href=\"#top\">top</a> <a href=\"https://same.org\">https://same.org</a>\
407 <pre> keep\n this\n</pre><p>after</p>";
408 assert_eq!(
409 to_text(html),
410 "- one\n- two link (https://e.com/x?a=1&b=2)\n\nline\nnext top https://same.org\n\n keep\n this\n\nafter"
411 );
412 }
413
414 #[test]
415 fn tolerates_malformed_and_truncated_input() {
416 assert_eq!(to_text("1 < 2 and 3 > 2"), "1 < 2 and 3 > 2");
417 assert_eq!(to_text("<p>cut <a href=\"x"), "cut");
418 assert_eq!(to_text("<div><p>unclosed <b>bold"), "unclosed bold");
419 assert_eq!(to_text("<script>never closed"), "");
420 assert_eq!(to_text("<p title=\"a > b\">ok</p>"), "ok");
421 assert_eq!(to_text(""), "");
422 assert_eq!(to_text("a<b>b</b>c <i>d</i> e"), "abc d e");
423 assert_eq!(
424 to_text("<table><tr><td>a</td><td>b</td></tr><tr><td>c</td></tr></table>"),
425 "a b\nc"
426 );
427 }
428}