pub fn looks_like_html(content_type: Option<&str>, body: &str) -> bool {
let ct = content_type.unwrap_or("").to_ascii_lowercase();
if ct.contains("text/html") || ct.contains("application/xhtml") {
return true;
}
if ct.contains("json")
|| ct.starts_with("image/")
|| ct.starts_with("audio/")
|| ct.starts_with("video/")
{
return false;
}
let head: String = body
.trim_start_matches('\u{feff}')
.trim_start()
.chars()
.take(15)
.collect::<String>()
.to_ascii_lowercase();
head.starts_with("<!doctype html") || head.starts_with("<html")
}
const SKIPPED: &[&str] = &["script", "style", "template", "svg", "noscript"];
const BLOCKS: &[&str] = &[
"address",
"article",
"aside",
"blockquote",
"body",
"dd",
"details",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hr",
"html",
"main",
"nav",
"ol",
"p",
"pre",
"section",
"table",
"title",
"ul",
];
#[derive(Default)]
struct Out {
buf: String,
pending_breaks: u8,
pending_space: bool,
}
impl Out {
fn breaks(&mut self, n: u8) {
self.pending_breaks = self.pending_breaks.max(n);
self.pending_space = false;
}
fn flush_pending(&mut self) {
if !self.buf.is_empty() {
for _ in 0..self.pending_breaks {
self.buf.push('\n');
}
if self.pending_breaks == 0 && self.pending_space {
self.buf.push(' ');
}
}
self.pending_breaks = 0;
self.pending_space = false;
}
fn text(&mut self, s: &str) {
if s.starts_with(char::is_whitespace) {
self.pending_space = true;
}
for word in s.split_whitespace() {
self.flush_pending();
self.buf.push_str(word);
self.pending_space = true;
}
if !s.ends_with(char::is_whitespace) {
self.pending_space = false;
}
}
fn raw(&mut self, s: &str) {
let s = s.trim_matches('\n');
if s.trim().is_empty() {
return;
}
self.flush_pending();
self.buf.push_str(s);
self.pending_space = false;
}
}
pub fn to_text(html: &str) -> String {
let mut out = Out::default();
let mut pre_depth = 0usize;
let mut links: Vec<Option<String>> = Vec::new();
let mut link_start: Vec<usize> = Vec::new();
let mut rest = html;
while !rest.is_empty() {
let Some(lt) = rest.find('<') else {
emit_text(&mut out, rest, pre_depth > 0);
break;
};
emit_text(&mut out, &rest[..lt], pre_depth > 0);
rest = &rest[lt..];
if let Some(after) = rest.strip_prefix("<!--") {
rest = after.find("-->").map_or("", |i| &after[i + 3..]);
continue;
}
let next = rest[1..].chars().next();
if !matches!(next, Some(c) if c.is_ascii_alphabetic() || c == '/' || c == '!' || c == '?') {
emit_text(&mut out, "<", pre_depth > 0);
rest = &rest[1..];
continue;
}
let Some(end) = tag_end(rest) else {
break;
};
let tag = &rest[1..end];
rest = &rest[end + 1..];
if tag.starts_with('!') || tag.starts_with('?') {
continue;
}
let closing = tag.starts_with('/');
let body = tag.trim_start_matches('/').trim_end_matches('/');
let name_end = body
.find(|c: char| c.is_whitespace() || c == '/')
.unwrap_or(body.len());
let name = body[..name_end].to_ascii_lowercase();
let attrs = &body[name_end..];
if !closing && SKIPPED.contains(&name.as_str()) {
rest = skip_element(rest, &name);
continue;
}
match (name.as_str(), closing) {
("br", _) => out.breaks(1),
("li", false) => {
out.breaks(1);
out.flush_pending();
out.buf.push_str("- ");
}
("tr", _) | ("li", true) => out.breaks(1),
("td" | "th", false) => out.pending_space = true,
("pre", false) => {
out.breaks(2);
pre_depth += 1;
}
("pre", true) => {
pre_depth = pre_depth.saturating_sub(1);
out.breaks(2);
}
("a", false) => {
links.push(attr_value(attrs, "href").filter(|h| link_worth_showing(h)));
link_start.push(out.buf.len());
}
("a", true) => {
if let (Some(Some(href)), Some(start)) = (links.pop(), link_start.pop()) {
let label = out.buf.get(start..).unwrap_or("").trim();
if !label.is_empty() && label != href {
out.pending_space = true;
out.text(&format!("({href})"));
}
}
}
(n, _) if BLOCKS.contains(&n) => out.breaks(2),
_ => {}
}
}
let mut text = out.buf;
text.truncate(text.trim_end().len());
text
}
fn emit_text(out: &mut Out, raw: &str, in_pre: bool) {
if raw.is_empty() {
return;
}
let decoded = decode_entities(raw);
if in_pre {
out.raw(&decoded);
} else {
out.text(&decoded);
}
}
fn tag_end(s: &str) -> Option<usize> {
let mut quote: Option<char> = None;
for (i, c) in s.char_indices().skip(1) {
match (quote, c) {
(Some(q), c) if c == q => quote = None,
(Some(_), _) => {}
(None, '"' | '\'') => quote = Some(c),
(None, '>') => return Some(i),
_ => {}
}
}
None
}
fn skip_element<'a>(rest: &'a str, name: &str) -> &'a str {
let lower = rest.to_ascii_lowercase();
let needle = format!("</{name}");
match lower.find(&needle) {
Some(i) => match rest[i..].find('>') {
Some(j) => &rest[i + j + 1..],
None => "",
},
None => "",
}
}
fn attr_value(attrs: &str, wanted: &str) -> Option<String> {
let lower = attrs.to_ascii_lowercase();
let mut from = 0;
while let Some(i) = lower[from..].find(wanted) {
let at = from + i;
from = at + wanted.len();
let boundary = at == 0 || lower.as_bytes()[at - 1].is_ascii_whitespace();
let tail = attrs[from..].trim_start();
let Some(tail) = tail.strip_prefix('=') else {
continue;
};
if !boundary {
continue;
}
let tail = tail.trim_start();
let value = match tail.chars().next()? {
q @ ('"' | '\'') => tail[1..].split(q).next()?,
_ => tail.split(char::is_whitespace).next()?,
};
return Some(decode_entities(value).trim().to_string());
}
None
}
fn link_worth_showing(href: &str) -> bool {
let h = href.to_ascii_lowercase();
!h.is_empty() && !h.starts_with('#') && !h.starts_with("javascript:")
}
pub fn decode_entities(s: &str) -> String {
if !s.contains('&') {
return s.to_string();
}
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find('&') {
out.push_str(&rest[..i]);
rest = &rest[i..];
let decoded = rest[1..]
.find(';')
.filter(|&n| n <= 10)
.and_then(|n| entity(&rest[1..1 + n]).map(|c| (c, n + 2)));
match decoded {
Some((c, len)) => {
out.push(c);
rest = &rest[len..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
fn entity(name: &str) -> Option<char> {
if let Some(num) = name.strip_prefix('#') {
let code = match num.strip_prefix(['x', 'X']) {
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
None => num.parse().ok()?,
};
return Some(
char::from_u32(code)
.filter(|&c| c != '\0')
.unwrap_or('\u{fffd}'),
);
}
Some(match name {
"amp" => '&',
"lt" => '<',
"gt" => '>',
"quot" => '"',
"apos" => '\'',
"nbsp" => '\u{a0}',
"copy" => '©',
"reg" => '®',
"trade" => '™',
"hellip" => '…',
"mdash" => '—',
"ndash" => '–',
"lsquo" => '‘',
"rsquo" => '’',
"ldquo" => '“',
"rdquo" => '”',
"laquo" => '«',
"raquo" => '»',
"bull" => '•',
"middot" => '·',
"euro" => '€',
"pound" => '£',
"yen" => '¥',
"cent" => '¢',
"deg" => '°',
"times" => '×',
"larr" => '←',
"rarr" => '→',
"sect" => '§',
"para" => '¶',
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_html_by_content_type_or_prefix() {
assert!(looks_like_html(Some("text/html; charset=utf-8"), "plain"));
assert!(looks_like_html(Some("application/xhtml+xml"), ""));
assert!(looks_like_html(None, " \n<!DOCTYPE html><p>x"));
assert!(looks_like_html(Some("text/plain"), "<html lang=en>"));
assert!(!looks_like_html(
Some("text/plain"),
"just text <html> later"
));
assert!(!looks_like_html(Some("application/json"), "<html>"));
assert!(!looks_like_html(None, "{\"a\":1}"));
}
#[test]
fn strips_tags_scripts_and_comments_and_keeps_paragraphs() {
let html = "<!doctype html><html><head><title>Hi</title><style>p{color:red}</style>\
<script>var x = '<p>no</p>';</script></head><body><!-- hidden -->\
<h1>Heading</h1><p>First para\n with <b>bold</b> and <i>italic</i>.</p>\
<p>Second</p></body></html>";
assert_eq!(
to_text(html),
"Hi\n\nHeading\n\nFirst para with bold and italic.\n\nSecond"
);
}
#[test]
fn decodes_entities_named_and_numeric() {
assert_eq!(
to_text("<p>a & b <c> "d" AB … &bogus; AT&T</p>"),
"a & b <c> \"d\" AB … &bogus; AT&T"
);
assert_eq!(decode_entities("��"), "\u{fffd}\u{fffd}");
assert_eq!(to_text("x y"), "x y");
}
#[test]
fn lists_breaks_links_and_pre() {
let html =
"<ul><li>one</li><li>two <a href=\"https://e.com/x?a=1&b=2\">link</a></li></ul>\
line<br>next <a href=\"#top\">top</a> <a href=\"https://same.org\">https://same.org</a>\
<pre> keep\n this\n</pre><p>after</p>";
assert_eq!(
to_text(html),
"- 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"
);
}
#[test]
fn tolerates_malformed_and_truncated_input() {
assert_eq!(to_text("1 < 2 and 3 > 2"), "1 < 2 and 3 > 2");
assert_eq!(to_text("<p>cut <a href=\"x"), "cut");
assert_eq!(to_text("<div><p>unclosed <b>bold"), "unclosed bold");
assert_eq!(to_text("<script>never closed"), "");
assert_eq!(to_text("<p title=\"a > b\">ok</p>"), "ok");
assert_eq!(to_text(""), "");
assert_eq!(to_text("a<b>b</b>c <i>d</i> e"), "abc d e");
assert_eq!(
to_text("<table><tr><td>a</td><td>b</td></tr><tr><td>c</td></tr></table>"),
"a b\nc"
);
}
}