File size: 2,274 Bytes
631bc49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""HTML -> greppable plain text. Pure stdlib: the task images have no bs4 and no internet to get it.

Whitespace inside <pre>/<code> is preserved -- these documents carry their worked examples in code
blocks, and a collapsed one ("mbarrier_init(&bar,1);// Initialize barrier") is unreadable.
"""
import re
import sys
from html.parser import HTMLParser

DROP = {"script", "style", "nav", "head", "noscript", "svg", "form"}
BLOCK = {"p", "div", "li", "tr", "br", "section", "article"}
HEAD = {"h1", "h2", "h3", "h4", "h5", "h6"}


class T(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.out, self.skip, self.pre = [], 0, 0

    def handle_starttag(self, tag, attrs):
        if tag in DROP:
            self.skip += 1
        elif tag in ("pre", "code"):
            if tag == "pre":
                self.out.append("\n")
            self.pre += 1
        elif self.pre:
            if tag == "br":
                self.out.append("\n")
        elif tag in HEAD:
            self.out.append("\n\n### ")
        elif tag in BLOCK:
            self.out.append("\n")
        elif tag in ("td", "th"):
            self.out.append("  ")

    def handle_endtag(self, tag):
        if tag in DROP and self.skip:
            self.skip -= 1
        elif tag in ("pre", "code"):
            if self.pre:
                self.pre -= 1
            if tag == "pre":
                self.out.append("\n")
        elif not self.pre and tag in HEAD | {"table"}:
            self.out.append("\n")

    def handle_data(self, d):
        if self.skip:
            return
        if self.pre:
            self.out.append(d)          # verbatim: newlines and indentation are the content
        elif d.strip():
            self.out.append(d)


def convert(src):
    p = T()
    p.feed(src)
    t = "".join(p.out)
    # collapse runs of spaces only OUTSIDE code: do it line-wise, leaving indented lines alone
    lines = []
    for ln in t.splitlines():
        lines.append(ln if ln[:1] in (" ", "\t") else re.sub(r"[ \t]{2,}", " ", ln).rstrip())
    t = "\n".join(lines)
    return re.sub(r"\n{3,}", "\n\n", t).strip() + "\n"


if __name__ == "__main__":
    sys.stdout.write(convert(open(sys.argv[1], encoding="utf-8", errors="ignore").read()))