-
Notifications
You must be signed in to change notification settings - Fork 0
/
plain.go
94 lines (80 loc) · 1.85 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
package rmime
import (
"bufio"
"io"
"strings"
)
// TextPlainReader decodes text/plain body parts using the "flowed" and "delsp" features.
// Note that Part.Body() already returns a TextPlainReader when Part.Type() is "text/plain".
// If flowed==false, TextPlainReader simply returns its input, r.
func TextPlainReader(r io.Reader, flowed, delsp bool) io.Reader {
if !flowed {
return r
}
s := bufio.NewScanner(r)
pr, pw := io.Pipe()
go func() {
var (
para []string
quoteDepth int
)
// TODO: reflow paragraphs
emitPara := func() {
if len(para) == 0 {
return
}
for _, line := range para {
if quoteDepth > 0 {
io.WriteString(pw, strings.Repeat(">", quoteDepth))
io.WriteString(pw, " ")
}
io.WriteString(pw, line)
io.WriteString(pw, "\n")
}
para = nil
quoteDepth = 0
}
for s.Scan() {
line := s.Text()
var isSignatureLine bool
if line == "-- " {
isSignatureLine = true
}
initLen := len(line)
line = strings.TrimLeftFunc(line, func(c rune) bool { return c == '>' })
lineQuoteDepth := initLen - len(line)
if len(line) > 0 && line[0] == ' ' {
line = line[1:]
}
if !isSignatureLine && line == "-- " {
// second check
isSignatureLine = true
}
var flowed bool
if !isSignatureLine && len(line) > 0 && line[len(line)-1] == ' ' {
flowed = true
if delsp {
line = line[:len(line)-1]
}
}
if !flowed && strings.IndexFunc(line, func(c rune) bool { return c != ' ' }) < 0 {
// space-only line is flowed
flowed = true
}
if !flowed || lineQuoteDepth != quoteDepth {
// end-of-flowed-paragraph conditions
emitPara()
}
if flowed {
para = append(para, line)
quoteDepth = lineQuoteDepth
} else {
io.WriteString(pw, line)
io.WriteString(pw, "\n")
}
}
emitPara()
pw.Close()
}()
return pr
}