-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml.go
102 lines (88 loc) · 1.57 KB
/
html.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
package main
import (
"bufio"
"bytes"
"io"
)
type Toker interface {
// Next returns io.EOF when done. It may also return a token at the same time.
Next() (token *Token, err error)
}
type Token struct {
index uint
typ TokenType
text string
}
type TokenType int
const (
// TokMetadata are things that are not body text and so should not be formatted: HTML tags.
TokMetadata = iota
// TokContent is actual content
TokContent
)
type HtmlToker struct {
rdr *bufio.Reader
inTag bool
index uint
text bytes.Buffer
}
func NewHtmlToker(r io.Reader) *HtmlToker {
return &HtmlToker{
rdr: bufio.NewReader(r),
}
}
func (h *HtmlToker) Next() (token *Token, err error) {
for {
var r rune
r, _, err = h.rdr.ReadRune()
if err != nil {
if !h.currentTokenIsEmpty() {
token = h.mkCurrentToken()
}
return
}
if h.inTag {
h.text.WriteRune(r)
if r == '>' {
token = h.mkCurrentToken()
h.inTag = false
return
}
} else {
if r == '<' {
empty := h.currentTokenIsEmpty()
if !empty {
token = h.mkCurrentToken()
}
h.inTag = true
if !empty {
h.text.WriteRune(r)
return
}
}
h.text.WriteRune(r)
}
}
return
}
func (h *HtmlToker) currentTokenIsEmpty() bool {
return h.text.Len() == 0
}
func (h *HtmlToker) mkCurrentToken() (tok *Token) {
if h.inTag {
tok = h.mkToken(TokMetadata)
} else {
tok = h.mkToken(TokContent)
}
h.index++
return
}
func (h *HtmlToker) mkToken(typ TokenType) *Token {
txt := h.text.String()
h.text.Reset()
return &Token{
index: h.index,
typ: typ,
text: txt,
}
}