1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
mod entity;
fn decode_named_entity(entity: &str) -> Option<char> {
entity::ENTITIES
.binary_search_by_key(&entity, |t| t.0)
.map(|idx| entity::ENTITIES[idx].1)
.ok()
}
fn parse_html_entity(ent_name: &str) -> Option<char> {
let d = decode_named_entity(ent_name);
if d.is_some() {
return d;
}
let num = ent_name.strip_prefix("#")?;
if num.chars().next()? == 'x' {
u32::from_str_radix(&num[1..].to_lowercase(), 16)
} else {
u32::from_str_radix(num, 10)
}
.ok()
.filter(|n| !matches!(n, 9 | 10 | 13 | 32))
.and_then(|n| char::from_u32(n))
}
fn html_entitities_to_text(s: &str) -> String {
let mut out = String::new();
let mut parts = s.split('&');
out.push_str(parts.next().unwrap());
for part in parts {
let end = part
.find(|c: char| c.is_whitespace() || c == ';')
.unwrap_or_else(|| part.len());
if let Some(entity) = parse_html_entity(&part[..end]) {
out.push(entity);
let skip = &part[end..]
.chars()
.next()
.unwrap()
.len_utf8();
out.push_str(&part[end + skip..]);
} else {
out.push('&');
out.push_str(part);
}
}
out
}
fn handle_tag(s: &str) -> (String, usize) {
let (tag, more) = match s.split_once('>') {
Some((tag, more)) if !tag.is_empty() => (tag, more),
_ => {
return (String::from("<"), 0);
}
};
let (name, attribs) = if let Some((name, attribs)) = tag.split_once(char::is_whitespace) {
(name, Some(attribs))
} else {
(tag, None)
};
match name.to_lowercase().as_str() {
"a" => {
let href = attribs
.and_then(|attribs| {
Some(
attribs
.split_once("href")?
.1
.trim_start()
.strip_prefix('=')?
.trim_start(),
)
})
.and_then(|href_value|
match href_value.chars().next()? {
start @ '\'' | start @ '"' => {
let (end, _) = href_value
.char_indices()
.skip(1)
.find(|(_, c)| *c == start)?;
Some(href_value[1..end].to_string())
}
_ => None,
})
.filter(|href| !href.starts_with("javascript:"))
.map(|href| html_entitities_to_text(&href));
let more = more.to_ascii_lowercase();
let end = more
.find("</a")
.map(|i| i + 3)
.and_then(|end_tag| more[end_tag..].find('>').map(|i| end_tag + i + 1))
.unwrap_or_else(|| more.len());
(href.unwrap_or_default(), tag.len() + 1 + end)
}
"br" | "br/" | "li" | "/ol" | "/ul" => (String::from("\r\n"), tag.len() + 1),
"p" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "/h1" | "/h2" | "/h3" | "/h4" | "/h5"
| "/h6" => (String::from("\r\n\r\n"), tag.len() + 1),
name @ "head" | name @ "script" | name @ "style" => {
let more = more.to_ascii_lowercase();
let end = more
.find(&format!("</{}", name))
.map(|i| i + 2 + name.len())
.and_then(|end_tag| more[end_tag..].find('>').map(|i| i + end_tag + 1))
.unwrap_or_else(|| more.len());
(String::new(), tag.len() + 1 + end)
}
"!--" => {
(String::new(), s.find("-->").map_or(s.len(), |n| n + 3))
}
_ => (String::new(), tag.len() + 1),
}
}
pub fn html2text(html: &str) -> String {
let html = html.split_whitespace().collect::<Vec<_>>().join(" ");
let mut out = String::new();
let mut i = 0;
while i < html.len() {
match html[i..].find('<') {
None => {
out += &html_entitities_to_text(&html[i..]);
break;
}
Some(text_segment) => {
if text_segment > 0 {
out += &html_entitities_to_text(&html[i..i + text_segment]);
i += text_segment;
}
i += 1;
let (s, advance) = handle_tag(&html[i..]);
if !s.is_empty() {
if out.ends_with("\r\n\r\n") || out.is_empty() {
out += &s.trim_start();
} else {
out += &s;
}
}
i += advance;
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test {
($name:ident, $from:literal, $to:literal $(,)?) => {
#[test]
fn $name() {
assert_eq!(&html2text($from), $to);
}
};
($($name:ident: $from:literal to $to:literal,)* $(,)?) => {
$(test!{$name, $from, $to})*
};
}
test! {
plaintext: "blah" to "blah",
tag: "<div></div>" to "",
tag_contents: "<div>simple text</div>" to "simple text",
link:
"click <a href=\"test\">here</a>"
to "click test",
links_ignore_attributes:
"click <a class=\"x\" href=\"test\">here</a>"
to "click test",
link_entities_in_url:
"click <a href=\"ents/'x'\">here</a>"
to "click ents/'x'",
link_javascript:
"click <a href=\"javascript:void(0)\">here</a>"
to "click ",
link_ignore_content_tags:
"click <a href=\"test\"><span>here</span> or here</a>"
to "click test",
link_absolute_url:
"click <a href=\"http://bit.ly/2n4wXRs\">news</a>"
to "click http://bit.ly/2n4wXRs",
link_ignore_attributes_2:
"<a rel=\"mw:WikiLink\" href=\"/wiki/yet#English\" title=\"yet\">yet</a>, <a rel=\"mw:WikiLink\" href=\"/wiki/not_yet#English\" title=\"not yet\">not yet</a>"
to "/wiki/yet#English, /wiki/not_yet#English",
ignore_inline:
"strong <strong>text</strong>"
to "strong text",
ignore_inline_attributes:
"some <div id=\"a\" class=\"b\">div</div>"
to "some div",
collapse_spaces:
"should ignore more spaces" to "should ignore more spaces",
collapse_linebreaks:
"a\nb\nc" to "a b c",
collapse_mixed:
"should \nignore \r\nnew lines" to "should ignore new lines",
br_tag:
"two<br>line<br/>breaks" to "two\r\nline\r\nbreaks",
paragraph:
"<p>two</p><p>paragraphs</p>" to "two\r\n\r\nparagraphs",
h1:
"<h1>First</h1>main text" to "First\r\n\r\nmain text",
h2_inline:
"First<h2>Second</h2>next section"
to "First\r\n\r\nSecond\r\n\r\nnext section",
h2:
"<h2>Second</h2>next section" to "Second\r\n\r\nnext section",
h3_inline:
"Second<h3>Third</h3>next section"
to "Second\r\n\r\nThird\r\n\r\nnext section",
h3:
"<h3>Third</h3>next section" to "Third\r\n\r\nnext section",
h4_inline:
"Third<h4>Fourth</h4>next section"
to "Third\r\n\r\nFourth\r\n\r\nnext section",
h4:
"<h4>Fourth</h4>next section" to "Fourth\r\n\r\nnext section",
h5_inline:
"Fourth<h5>Fifth</h5>next section"
to "Fourth\r\n\r\nFifth\r\n\r\nnext section",
h5:
"<h5>Fifth</h5>next section" to "Fifth\r\n\r\nnext section",
h6_inline:
"Fifth<h6>Sixth</h6>next section"
to "Fifth\r\n\r\nSixth\r\n\r\nnext section",
h6:
"<h6>Sixth</h6>next section" to "Sixth\r\n\r\nnext section",
no_h7:
"<h7>Not Header</h7>next section" to "Not Headernext section",
entity_nbsp:
"two spaces" to "two spaces",
entity_copy:
"© 2017 K3A" to "© 2017 K3A",
entity_tag:
"<printtag>" to "<printtag>",
entity_currencies:
"would you pay in ¢, £, ¥ or €?"
to "would you pay in ¢, £, ¥ or €?",
ampersand_not_entity:
"Tom & Jerry is not an entity" to "Tom & Jerry is not an entity",
entity_unknown:
"this &neither; as you see" to "this &neither; as you see",
entity_amp:
"fish & chips" to "fish & chips",
unordered_list:
"list of items<ul><li>One</li><li>Two</li><li>Three</li></ul>"
to "list of items\r\nOne\r\nTwo\r\nThree\r\n",
entity_quot:
""I'm sorry, Dave. I'm afraid I can't do that." – HAL, 2001: A Space Odyssey"
to "\"I'm sorry, Dave. I'm afraid I can't do that.\" – HAL, 2001: A Space Odyssey",
entity_reg:
"Google ®" to "Google ®",
entity_large_unknown:
"&abcdefghij;" to "&abcdefghij;",
entity_numeric:
"⁌ decimal and hex entities supported ⁍"
to "⁌ decimal and hex entities supported ⁍",
entity_numeric_2:
"'single quotes' and 츝"
to "'single quotes' and 츝",
empty: "" to "",
full_html:
"<html><head><title>Good</title></head><body>x</body>" to "x",
ignore_script:
"we are not <script type=\"javascript\"></script>interested in scripts"
to "we are not interested in scripts",
ignore_unknown_tag:
"<aa>hello</aa>" to "hello",
ignore_unknown_tag_whitespace:
"<aa >hello</aa>" to "hello",
ignore_unknown_tag_attributes:
"<aa x=\"1\">hello</aa>" to "hello",
}
}