-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathplain.go
108 lines (98 loc) · 2.27 KB
/
plain.go
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
// Copyright 2005, Hǎiliàng Wáng. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package query
import (
"bytes"
"strings"
"golang.org/x/net/html"
"h12.io/html-query/expr"
)
func (n *Node) PlainText() *string {
if n == nil {
return nil
}
var w bytes.Buffer
if err := renderPlain(&w, &n.n); err != nil {
return nil
}
s := strings.TrimSpace(w.String())
return &s
}
func renderPlain(w writer, n *html.Node) error {
switch n.Type {
case html.TextNode:
w.WriteString(n.Data)
case html.DocumentNode:
for c := n.FirstChild; c != nil; c = c.NextSibling {
if err := renderPlain(w, c); err != nil {
return err
}
}
return nil
case html.ElementNode:
return renderPlainElementNode(w, n)
}
return nil
}
func renderPlainElementNode(w writer, n *html.Node) error {
if c := n.FirstChild; c != nil && c.Type == html.TextNode && strings.HasPrefix(c.Data, "\n") {
switch n.Data {
case "pre", "listing", "textarea":
if err := w.WriteByte('\n'); err != nil {
return err
}
}
}
switch n.Data {
case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "xmp":
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.TextNode {
if _, err := w.WriteString(c.Data); err != nil {
return err
}
} else {
if err := renderPlain(w, c); err != nil {
return err
}
}
}
if n.Data == "plaintext" {
return plaintextAbort
}
return nil
case "a":
if n.FirstChild != nil && isURL(n.FirstChild.Data) {
renderPlainChild(w, n)
} else if url := expr.GetAttr(n, "href"); url != nil && *url != "" {
w.WriteString("[")
renderPlainChild(w, n)
w.WriteString("](")
w.WriteString(*url)
w.WriteString(")")
} else {
renderPlainChild(w, n)
}
return nil
}
renderPlainChild(w, n)
// write break after children are written
switch n.Data {
case "p", "br", "div":
writeBreak(w)
}
return nil
}
func isURL(s string) bool {
s = strings.TrimSpace(s)
return strings.Contains(s, "http://") ||
strings.Contains(s, "@")
}
func renderPlainChild(w writer, n *html.Node) error {
for c := n.FirstChild; c != nil; c = c.NextSibling {
if err := renderPlain(w, c); err != nil {
return err
}
}
return nil
}