eclipse-core 0.13.3

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! A small, std-only HTML-to-text converter for the `fetch` tool.
//!
//! This is a readable approximation, not a renderer: it strips tags, drops the contents
//! of `<script>`/`<style>` and similar, decodes common entities, collapses whitespace and
//! keeps rough structure (blank lines between blocks, `- ` for list items, preserved
//! `<pre>` text, link targets in parentheses). It does not run scripts, apply CSS, lay out
//! tables, or repair badly broken markup, so complex pages can come out noisy or lose
//! content that only exists after JavaScript runs.

/// Whether a response should be treated as HTML: the content type says so, or the body
/// starts with `<!doctype html` / `<html` (unless the content type is JSON or binary).
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")
}

/// Elements whose whole content is dropped.
const SKIPPED: &[&str] = &["script", "style", "template", "svg", "noscript"];

/// Elements that start and end a paragraph (blank line around them).
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,
    /// Newlines owed before the next text: 0, 1 (line) or 2 (blank line).
    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;
    }

    /// Collapsing text: runs of whitespace become one space, none at the start of a line.
    /// Inline tags alone do not add a space (`a<b>b</b>` stays `ab`).
    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;
        }
    }

    /// Whitespace-preserving text (`<pre>`).
    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;
    }
}

/// Convert an HTML document or fragment to plain text. Never fails; malformed input just
/// produces less tidy output.
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 {
            // Truncated tag at the end of the input.
            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);
    }
}

/// Index of the `>` closing the tag that starts at `s[0] == '<'`, ignoring `>` inside
/// quoted attribute values.
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
}

/// Everything after the matching `</name>` (or nothing, if it never closes).
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:")
}

/// Decode the common named entities and numeric references; anything else is kept as is.
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 &amp; b &lt;c&gt; &quot;d&quot; &#65;&#x42; &hellip; &bogus; AT&T</p>"),
            "a & b <c> \"d\" AB … &bogus; AT&T"
        );
        assert_eq!(decode_entities("&#0;&#1114112;"), "\u{fffd}\u{fffd}");
        assert_eq!(to_text("x&nbsp;&nbsp;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&amp;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"
        );
    }
}