-
Notifications
You must be signed in to change notification settings - Fork 3
/
regexp.go
318 lines (271 loc) · 9.7 KB
/
regexp.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
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
package textplain
import (
"bytes"
"fmt"
"regexp"
"strconv"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
type RegexpConverter struct {
ignoredHTML *regexp.Regexp
comments *regexp.Regexp
imgAltDoubleQuotes submatchReplacer
imgAltSingleQuotes submatchReplacer
links submatchReplacer
headerClose submatchReplacer
headerBlockBr *regexp.Regexp
headerBlockTags *regexp.Regexp
headerBlock submatchReplacer
wrapSpans submatchReplacer
lists *regexp.Regexp
listsNoNewline *regexp.Regexp
paragraphs *regexp.Regexp
lineBreaks *regexp.Regexp
remainingTags *regexp.Regexp
shortenSpaces *regexp.Regexp
lineFeeds *regexp.Regexp
nonBreakingSpaces *regexp.Regexp
extraSpaceStartOfLine *regexp.Regexp
extraSpaceEndOfLine *regexp.Regexp
consecutiveNewlines *regexp.Regexp
fixWordWrappedParens submatchReplacer
}
// New textplain converter object
func NewRegexpConverter() Converter {
headerBlockBr := regexp.MustCompile(`(?i)<br[\s]*\/?>`)
headerBlockTags := regexp.MustCompile(`(?i)<\/?[^>]*>`)
return &RegexpConverter{
ignoredHTML: regexp.MustCompile(`(?ms)<!-- start text\/html -->.*?<!-- end text\/html -->`),
comments: regexp.MustCompile(`(?ms)<!--.*?-->`),
// imgAltDoubleQuotes replaces images with their alt tag when it is double quoted
imgAltDoubleQuotes: submatchReplacer{
regexp: regexp.MustCompile(`(?i)<img.+?alt=\"([^\"]*)\"[^>]*\>`),
handler: func(t string, submatch []int) string {
return t[submatch[2]:submatch[3]]
},
},
// imgAltSingleQuotes replaces images with their alt tag when it is single quoted
imgAltSingleQuotes: submatchReplacer{
regexp: regexp.MustCompile(`(?i)<img.+?alt=\'([^\']*)\'[^>]*\>`),
handler: func(t string, submatch []int) string {
return t[submatch[2]:submatch[3]]
},
},
// links replaces anchor links with one of "href" or "content ( href )"
links: submatchReplacer{
regexp: regexp.MustCompile(`(?i)<a\s.*?href=["'](mailto:)?([^"']*)["'][^>]*>((.|\s)*?)<\/a>`),
handler: func(t string, submatch []int) string {
href, value := strings.TrimSpace(t[submatch[4]:submatch[5]]), strings.TrimSpace(t[submatch[6]:submatch[7]])
var replace string
if strings.EqualFold(href, value) {
replace = value
} else if value != "" {
replace = fmt.Sprintf("%s ( %s )", value, href)
}
return replace
},
},
// headerClose moves `</h[1-6]>` tags to their own line as a preprocessing step for headerBlock
headerClose: submatchReplacer{
regexp: regexp.MustCompile(`(?i)(<\/h[1-6]>)`),
handler: func(t string, submatch []int) string {
return "\n" + t[submatch[2]:submatch[3]]
},
},
// used in headerBlock to do some content replacement
headerBlockBr: headerBlockBr,
headerBlockTags: headerBlockTags,
// headerBlock converts a `<h[1-6]>` block to plaintext
headerBlock: submatchReplacer{
regexp: regexp.MustCompile(`(?imsU)[\s]*<h([1-6]+)[^>]*>[\s]*(.*)[\s]*<\/h[1-6]+>`),
handler: func(t string, submatch []int) string {
headerLevel, _ := strconv.Atoi(t[submatch[2]:submatch[3]])
headerText := t[submatch[4]:submatch[5]]
headerText = headerBlockBr.ReplaceAllString(headerText, "\n")
headerText = headerBlockTags.ReplaceAllString(headerText, "")
var maxLength int
var headerLines []string
for _, line := range strings.Split(headerText, "\n") {
if trimmed := strings.TrimSpace(line); len(trimmed) > 0 {
headerLines = append(headerLines, trimmed)
if l := len(headerLines[len(headerLines)-1]); l > maxLength {
maxLength = l
}
}
}
headerText = strings.Join(headerLines, "\n")
var header string
// special case headers
switch headerLevel {
case 1:
header = strings.Repeat("*", maxLength) + "\n" + headerText + "\n" + strings.Repeat("*", maxLength)
case 2:
header = strings.Repeat("-", maxLength) + "\n" + headerText + "\n" + strings.Repeat("-", maxLength)
default:
header = headerText + "\n" + strings.Repeat("-", maxLength)
}
return "\n\n" + header + "\n\n"
},
},
// wrapSpans merges together contiguous span tags into a single line
wrapSpans: submatchReplacer{
regexp: regexp.MustCompile(`(?msi)(<\/span>)[\s]+(<span)`),
handler: func(t string, submatch []int) string {
return fmt.Sprintf("%s %s", t[submatch[2]:submatch[3]], t[submatch[4]:submatch[5]])
},
},
// these are all used as direct replacements
lists: regexp.MustCompile(`(?i)[\s]*(<li[^>]*>)[\s]*`),
listsNoNewline: regexp.MustCompile(`(?i)<\/li>[\s]*([\n]?)`),
paragraphs: regexp.MustCompile(`(?i)<\/p>`),
lineBreaks: regexp.MustCompile(`(?i)<br[\/ ]*>`),
remainingTags: regexp.MustCompile(`<\/?[^>]*>`),
shortenSpaces: regexp.MustCompile(` {2,}`),
lineFeeds: regexp.MustCompile(`\r\n?`),
nonBreakingSpaces: regexp.MustCompile(`[ \t]*\302\240+[ \t]*`),
extraSpaceStartOfLine: regexp.MustCompile(`\n[ \t]+`),
extraSpaceEndOfLine: regexp.MustCompile(`[ \t]+\n`),
consecutiveNewlines: regexp.MustCompile(`[\n]{3,}`),
// fixWordWrappedParens searches for links that got broken by word wrap and moves them
// into a single line
fixWordWrappedParens: submatchReplacer{
regexp: regexp.MustCompile(`\(([ \n])([^)]+)([\n ])\)`),
handler: func(t string, submatch []int) string {
leadingSpace, content, trailingSpace := t[submatch[2]:submatch[3]], t[submatch[4]:submatch[5]], t[submatch[6]:submatch[7]]
var out string
if leadingSpace == "\n" {
out += leadingSpace
}
out += "( " + content + " )"
if trailingSpace == "\n" {
out += leadingSpace
}
return out
},
},
}
}
// XXX: based on premailer/premailer@7c94e7a5a457b6710bada8186c6a41fccbfa08d1
// https://github.com/premailer/premailer/tree/7c94e7a5a457b6710bada8186c6a41fccbfa08d1
type submatchReplacer struct {
regexp *regexp.Regexp
handler func(string, []int) string
}
func (s *submatchReplacer) Replace(text string) string {
var start int
var finalText string
for _, submatch := range s.regexp.FindAllStringSubmatchIndex(text, -1) {
finalText += text[start:submatch[0]] + s.handler(text, submatch)
start = submatch[1]
}
return finalText + text[start:]
}
// Convert returns a text-only version of supplied document in UTF-8 format with all HTML tags removed
func (t *RegexpConverter) Convert(document string, lineLength int) (string, error) {
// Brutish way to get a fully formed html document
doc, err := html.Parse(strings.NewReader(document))
if err != nil {
return "", err
}
// Find the <body> tag within the document
var bodyElement *html.Node
if doc.Type == html.ElementNode && doc.Data == "body" {
bodyElement = doc
} else {
var scanForBody func(n *html.Node, depth int)
scanForBody = func(n *html.Node, depth int) {
if n == nil {
return
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if n.Type == html.ElementNode && n.Data == "body" {
bodyElement = n
return
}
if depth < 5 {
scanForBody(c, depth+1)
}
}
}
scanForBody(doc, 0)
}
if bodyElement == nil {
return "", ErrBodyNotFound
}
var dropNonContentTags func(*html.Node)
dropNonContentTags = func(n *html.Node) {
if n == nil {
return
}
var toRemove []*html.Node
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.DataAtom == atom.Script || c.DataAtom == atom.Style {
toRemove = append(toRemove, c)
} else {
dropNonContentTags(c)
}
}
for _, r := range toRemove {
n.RemoveChild(r)
}
}
dropNonContentTags(bodyElement)
// Reconstitute the cleaned HTML document for application
// of plaintext-conversion logic
var clean bytes.Buffer
err = html.Render(&clean, bodyElement)
if err != nil {
return "", err
}
// strip text ignored html. Useful for removing
// headers and footers that aren't needed in the
// text version
txt := t.ignoredHTML.ReplaceAllString(clean.String(), "")
// strip out html comments
txt = t.comments.ReplaceAllString(txt, "")
// replace images with their alt attributes for img tags with "" for attribute quotes
// eg. the following formats:
// <img alt="" />
// <img alt="">
txt = t.imgAltDoubleQuotes.Replace(txt)
// replace images with their alt attributes for img tags with '' for attribute quotes
// eg. the following formats:
// <img alt='' />
// <img alt=''>
txt = t.imgAltSingleQuotes.Replace(txt)
// links
txt = t.links.Replace(txt)
// handle headings (H1-H6)
txt = t.headerClose.Replace(txt)
txt = t.headerBlock.Replace(txt)
// wrap spans
txt = t.wrapSpans.Replace(txt)
// lists -- TODO: should handle ordered lists
txt = t.lists.ReplaceAllString(txt, "* ")
// list not followed by a newline
txt = t.listsNoNewline.ReplaceAllString(txt, "\n")
// paragraphs and line breaks
txt = t.paragraphs.ReplaceAllString(txt, "\n\n")
txt = t.lineBreaks.ReplaceAllString(txt, "\n")
// strip remaining tags
txt = t.remainingTags.ReplaceAllString(txt, "")
// decode HTML entities
txt = html.UnescapeString(txt)
// no more than two consecutive spaces
txt = t.shortenSpaces.ReplaceAllString(txt, " ")
// apply word wrapping
txt = WordWrap(txt, lineLength)
// remove linefeeds (\r\n and \r -> \n)
txt = t.lineFeeds.ReplaceAllString(txt, "\n")
// strip extra spaces
txt = t.nonBreakingSpaces.ReplaceAllString(txt, " ")
txt = t.extraSpaceStartOfLine.ReplaceAllString(txt, "\n")
txt = t.extraSpaceEndOfLine.ReplaceAllString(txt, "\n")
// no more than two consecutive newlines
txt = t.consecutiveNewlines.ReplaceAllString(txt, "\n\n")
// wordWrap messes up the parens
txt = t.fixWordWrappedParens.Replace(txt)
return strings.TrimSpace(txt), nil
}