/
textmail.go
242 lines (215 loc) · 5.48 KB
/
textmail.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
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
package textmail
import (
"bytes"
"fmt"
"github.com/moovweb/gokogiri"
"github.com/moovweb/gokogiri/xml"
"strings"
)
// Set of whitespace characters.
var whitespace = map[byte]bool{
' ': true,
'\n': true,
'\r': true,
'\t': true,
'\v': true,
}
// Set of elements we ignore.
var ignore = map[string]bool{
"audio": true,
"head": true,
"script": true,
"track": true,
"video": true,
}
// Set of HTML block elements.
var block = map[string]bool{
"address": true,
"article": true,
"aside": true,
"blockquote": true,
"body": true,
"canvas": true,
"del": true,
"div": true,
"dl": true,
"fieldset": true,
"figcaption": true,
"figure": true,
"footer": true,
"form": true,
"header": true,
"hgroup": true,
"hr": true,
"ins": true,
"menu": true,
"noscript": true,
"ol": true,
"output": true,
"p": true,
"section": true,
"table": true,
"td": true,
"tfoot": true,
"th": true,
"thead": true,
"tr": true,
"ul": true,
}
// HTML heading elements.
var heading = map[string]bool{
"h1": true,
"h2": true,
"h3": true,
"h4": true,
"h5": true,
"h6": true,
}
// HTML elements we will wrap with /
var italic = map[string]bool{
"em": true,
"i": true,
}
// HTML elements we will wrap with *
var bold = map[string]bool{
"b": true,
"strong": true,
}
type Formatter struct {
buf bytes.Buffer // Buffer
links []string // Collected urls
}
// Converts HTML into nice formatted plain text.
func Format(src []byte) (*Formatter, error) {
doc, err := gokogiri.ParseHtml(src)
if err != nil {
return nil, err
}
defer doc.Free()
f := new(Formatter)
f.walk(doc.Node)
for i, link := range f.links {
f.buf.WriteString(fmt.Sprintf("[%d] %s\n", i, link))
}
return f, nil
}
// Returns the result as byte array.
func (self *Formatter) Bytes() []byte {
return self.buf.Bytes()
}
// Returns the resutl as string.
func (self *Formatter) String() string {
return self.buf.String()
}
// Walks through the documents elements and populates the buffer.
func (self *Formatter) walk(node xml.Node) {
for c := node.FirstChild(); c != nil; c = c.NextSibling() {
self.walk(c)
}
if node.NodeType() == xml.XML_ELEMENT_NODE {
self.handleNode(node)
}
}
// Formats the content of inline elements and writes the content of block
// elements to the buffer.
func (self *Formatter) handleNode(node xml.Node) {
name := node.Name()
switch {
case ignore[name]:
// Remove ignored elements.
node.SetContent("")
case name == "pre":
// Treat pre elements as code blocks.
self.writeCodeBlock(node)
case heading[name]:
// Headings are prefixed with "# ".
self.writeBlock(node, "# ")
case name == "li":
// List items are prefixed with "- ".
self.writeBlock(node, "- ")
case name == "br":
// Preserve explicit line breaks.
node.SetContent("\n")
case italic[name]:
// Wrap italic elements with /.
node.SetContent("/" + node.Content() + "/")
case bold[name]:
// Wrap bold elements with *.
node.SetContent("*" + node.Content() + "*")
case name == "img":
// Collect the src of images and replace them with (alt)[url index]
alt, src := node.Attr("alt"), node.Attr("src")
if len(alt) > 0 && len(src) > 0 {
node.SetContent(fmt.Sprintf("(%s)[%d]", alt, len(self.links)))
self.links = append(self.links, src)
}
case name == "a":
// Collect the href and and the url index.
href, content := node.Attr("href"), node.Content()
if len(href) > 0 && len(content) > 0 {
node.SetContent(fmt.Sprintf("%s[%d]", content, len(self.links)))
self.links = append(self.links, href)
}
case block[name]:
// Write the content of block elements to the buffer.
self.writeBlock(node, "")
}
}
// Writes text blocks to the buffer.
func (self *Formatter) writeBlock(node xml.Node, prefix string) {
block := []byte(strings.TrimSpace(node.Content()))
node.SetContent("")
if len(block) == 0 {
return
}
// Position of last space, line break and max length.
sp, br, max := 0, 0, 79-len(prefix)
self.buf.WriteString(prefix)
for i, c := range block {
// Break line if exceeded max length and the position of the last space
// is greater than the position of the last line break. Don't break very
// long words.
if i-br > max && sp > br {
self.buf.WriteByte('\n')
br = sp
// Only the first line is prefixed.
for j := 0; j < len(prefix); j++ {
self.buf.WriteByte(' ')
}
}
if whitespace[c] {
// The last character was a space, so ignore this one.
if sp == i {
sp++
br++
continue
}
// Write the last word to the buffer, append a space and update
// the position of the last space.
if sp > br {
self.buf.WriteByte(' ')
}
self.buf.Write(block[sp:i])
sp = i + 1
}
}
// Write the last word to the buffer.
if sp < len(block) {
if sp > br {
self.buf.WriteByte(' ')
}
self.buf.Write(block[sp:])
}
// Close block with 2 breaks.
self.buf.Write([]byte{'\n', '\n'})
}
// Writes code blocks to the buffer.
func (self *Formatter) writeCodeBlock(node xml.Node) {
block := []byte(strings.Trim(node.Content(), "\n\r\v"))
node.SetContent("")
if len(block) == 0 {
return
}
self.buf.Write(block)
self.buf.Write([]byte{'\n', '\n'})
}