1
// Copyright 2010 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
13
"code.google.com/p/go.net/html/atom"
16
// A TokenType is the type of a Token.
20
// ErrorToken means that an error occurred during tokenization.
21
ErrorToken TokenType = iota
22
// TextToken means a text node.
24
// A StartTagToken looks like <a>.
26
// An EndTagToken looks like </a>.
28
// A SelfClosingTagToken tag looks like <br/>.
30
// A CommentToken looks like <!--x-->.
32
// A DoctypeToken looks like <!DOCTYPE x>
36
// String returns a string representation of the TokenType.
37
func (t TokenType) String() string {
47
case SelfClosingTagToken:
48
return "SelfClosingTag"
54
return "Invalid(" + strconv.Itoa(int(t)) + ")"
57
// An Attribute is an attribute namespace-key-value triple. Namespace is
58
// non-empty for foreign attributes like xlink, Key is alphabetic (and hence
59
// does not contain escapable characters like '&', '<' or '>'), and Val is
60
// unescaped (it looks like "a<b" rather than "a<b").
62
// Namespace is only used by the parser, not the tokenizer.
63
type Attribute struct {
64
Namespace, Key, Val string
67
// A Token consists of a TokenType and some Data (tag name for start and end
68
// tags, content for text, comments and doctypes). A tag Token may also contain
69
// a slice of Attributes. Data is unescaped for all Tokens (it looks like "a<b"
70
// rather than "a<b"). For tag Tokens, DataAtom is the atom for Data, or
71
// zero if Data is not a known tag name.
79
// tagString returns a string representation of a tag Token's Data and Attr.
80
func (t Token) tagString() string {
84
buf := bytes.NewBufferString(t.Data)
85
for _, a := range t.Attr {
87
buf.WriteString(a.Key)
95
// String returns a string representation of the Token.
96
func (t Token) String() string {
101
return EscapeString(t.Data)
103
return "<" + t.tagString() + ">"
105
return "</" + t.tagString() + ">"
106
case SelfClosingTagToken:
107
return "<" + t.tagString() + "/>"
109
return "<!--" + t.Data + "-->"
111
return "<!DOCTYPE " + t.Data + ">"
113
return "Invalid(" + strconv.Itoa(int(t.Type)) + ")"
116
// span is a range of bytes in a Tokenizer's buffer. The start is inclusive,
117
// the end is exclusive.
122
// A Tokenizer returns a stream of HTML Tokens.
123
type Tokenizer struct {
124
// r is the source of the HTML text.
126
// tt is the TokenType of the current token.
128
// err is the first error encountered during tokenization. It is possible
129
// for tt != Error && err != nil to hold: this means that Next returned a
130
// valid token but the subsequent Next call will return an error token.
131
// For example, if the HTML text input was just "plain", then the first
132
// Next call would set z.err to io.EOF but return a TextToken, and all
133
// subsequent Next calls would return an ErrorToken.
134
// err is never reset. Once it becomes non-nil, it stays non-nil.
136
// buf[raw.start:raw.end] holds the raw bytes of the current token.
137
// buf[raw.end:] is buffered input that will yield future tokens.
140
// buf[data.start:data.end] holds the raw bytes of the current token's data:
141
// a text token's text, a tag token's tag name, etc.
143
// pendingAttr is the attribute key and value currently being tokenized.
144
// When complete, pendingAttr is pushed onto attr. nAttrReturned is
145
// incremented on each call to TagAttr.
149
// rawTag is the "script" in "</script>" that closes the next token. If
150
// non-empty, the subsequent call to Next will return a raw or RCDATA text
151
// token: one that treats "<p>" as text instead of an element.
152
// rawTag's contents are lower-cased.
154
// textIsRaw is whether the current text token's data is not escaped.
156
// convertNUL is whether NUL bytes in the current token's data should
157
// be converted into \ufffd replacement characters.
159
// allowCDATA is whether CDATA sections are allowed in the current context.
163
// AllowCDATA sets whether or not the tokenizer recognizes <![CDATA[foo]]> as
164
// the text "foo". The default value is false, which means to recognize it as
165
// a bogus comment "<!-- [CDATA[foo]] -->" instead.
167
// Strictly speaking, an HTML5 compliant tokenizer should allow CDATA if and
168
// only if tokenizing foreign content, such as MathML and SVG. However,
169
// tracking foreign-contentness is difficult to do purely in the tokenizer,
170
// as opposed to the parser, due to HTML integration points: an <svg> element
171
// can contain a <foreignObject> that is foreign-to-SVG but not foreign-to-
172
// HTML. For strict compliance with the HTML5 tokenization algorithm, it is the
173
// responsibility of the user of a tokenizer to call AllowCDATA as appropriate.
174
// In practice, if using the tokenizer without caring whether MathML or SVG
175
// CDATA is text or comments, such as tokenizing HTML to find all the anchor
176
// text, it is acceptable to ignore this responsibility.
177
func (z *Tokenizer) AllowCDATA(allowCDATA bool) {
178
z.allowCDATA = allowCDATA
181
// NextIsNotRawText instructs the tokenizer that the next token should not be
182
// considered as 'raw text'. Some elements, such as script and title elements,
183
// normally require the next token after the opening tag to be 'raw text' that
184
// has no child elements. For example, tokenizing "<title>a<b>c</b>d</title>"
185
// yields a start tag token for "<title>", a text token for "a<b>c</b>d", and
186
// an end tag token for "</title>". There are no distinct start tag or end tag
187
// tokens for the "<b>" and "</b>".
189
// This tokenizer implementation will generally look for raw text at the right
190
// times. Strictly speaking, an HTML5 compliant tokenizer should not look for
191
// raw text if in foreign content: <title> generally needs raw text, but a
192
// <title> inside an <svg> does not. Another example is that a <textarea>
193
// generally needs raw text, but a <textarea> is not allowed as an immediate
194
// child of a <select>; in normal parsing, a <textarea> implies </select>, but
195
// one cannot close the implicit element when parsing a <select>'s InnerHTML.
196
// Similarly to AllowCDATA, tracking the correct moment to override raw-text-
197
// ness is difficult to do purely in the tokenizer, as opposed to the parser.
198
// For strict compliance with the HTML5 tokenization algorithm, it is the
199
// responsibility of the user of a tokenizer to call NextIsNotRawText as
200
// appropriate. In practice, like AllowCDATA, it is acceptable to ignore this
201
// responsibility for basic usage.
203
// Note that this 'raw text' concept is different from the one offered by the
204
// Tokenizer.Raw method.
205
func (z *Tokenizer) NextIsNotRawText() {
209
// Err returns the error associated with the most recent ErrorToken token.
210
// This is typically io.EOF, meaning the end of tokenization.
211
func (z *Tokenizer) Err() error {
212
if z.tt != ErrorToken {
218
// readByte returns the next byte from the input stream, doing a buffered read
219
// from z.r into z.buf if necessary. z.buf[z.raw.start:z.raw.end] remains a contiguous byte
220
// slice that holds all the bytes read so far for the current token.
221
// It sets z.err if the underlying reader returns an error.
222
// Pre-condition: z.err == nil.
223
func (z *Tokenizer) readByte() byte {
224
if z.raw.end >= len(z.buf) {
225
// Our buffer is exhausted and we have to read from z.r.
226
// We copy z.buf[z.raw.start:z.raw.end] to the beginning of z.buf. If the length
227
// z.raw.end - z.raw.start is more than half the capacity of z.buf, then we
228
// allocate a new buffer before the copy.
230
d := z.raw.end - z.raw.start
233
buf1 = make([]byte, d, 2*c)
237
copy(buf1, z.buf[z.raw.start:z.raw.end])
238
if x := z.raw.start; x != 0 {
239
// Adjust the data/attr spans to refer to the same contents after the copy.
242
z.pendingAttr[0].start -= x
243
z.pendingAttr[0].end -= x
244
z.pendingAttr[1].start -= x
245
z.pendingAttr[1].end -= x
246
for i := range z.attr {
247
z.attr[i][0].start -= x
248
z.attr[i][0].end -= x
249
z.attr[i][1].start -= x
250
z.attr[i][1].end -= x
253
z.raw.start, z.raw.end, z.buf = 0, d, buf1[:d]
254
// Now that we have copied the live bytes to the start of the buffer,
255
// we read from z.r into the remainder.
256
n, err := z.r.Read(buf1[d:cap(buf1)])
263
x := z.buf[z.raw.end]
268
// skipWhiteSpace skips past any white space.
269
func (z *Tokenizer) skipWhiteSpace() {
279
case ' ', '\n', '\r', '\t', '\f':
288
// readRawOrRCDATA reads until the next "</foo>", where "foo" is z.rawTag and
289
// is typically something like "script" or "textarea".
290
func (z *Tokenizer) readRawOrRCDATA() {
291
if z.rawTag == "script" {
313
if z.readRawEndTag() || z.err != nil {
317
z.data.end = z.raw.end
318
// A textarea's or title's RCDATA can contain escaped entities.
319
z.textIsRaw = z.rawTag != "textarea" && z.rawTag != "title"
323
// readRawEndTag attempts to read a tag like "</foo>", where "foo" is z.rawTag.
324
// If it succeeds, it backs up the input position to reconsume the tag and
325
// returns true. Otherwise it returns false. The opening "</" has already been
327
func (z *Tokenizer) readRawEndTag() bool {
328
for i := 0; i < len(z.rawTag); i++ {
333
if c != z.rawTag[i] && c != z.rawTag[i]-('a'-'A') {
343
case ' ', '\n', '\r', '\t', '\f', '/', '>':
344
// The 3 is 2 for the leading "</" plus 1 for the trailing character c.
345
z.raw.end -= 3 + len(z.rawTag)
352
// readScript reads until the next </script> tag, following the byzantine
353
// rules for escaping/hiding the closing tag.
354
func (z *Tokenizer) readScript() {
356
z.data.end = z.raw.end
366
goto scriptDataLessThanSign
370
scriptDataLessThanSign:
377
goto scriptDataEndTagOpen
379
goto scriptDataEscapeStart
384
scriptDataEndTagOpen:
385
if z.readRawEndTag() || z.err != nil {
390
scriptDataEscapeStart:
396
goto scriptDataEscapeStartDash
401
scriptDataEscapeStartDash:
407
goto scriptDataEscapedDashDash
419
goto scriptDataEscapedDash
421
goto scriptDataEscapedLessThanSign
423
goto scriptDataEscaped
425
scriptDataEscapedDash:
432
goto scriptDataEscapedDashDash
434
goto scriptDataEscapedLessThanSign
436
goto scriptDataEscaped
438
scriptDataEscapedDashDash:
445
goto scriptDataEscapedDashDash
447
goto scriptDataEscapedLessThanSign
451
goto scriptDataEscaped
453
scriptDataEscapedLessThanSign:
459
goto scriptDataEscapedEndTagOpen
461
if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
462
goto scriptDataDoubleEscapeStart
467
scriptDataEscapedEndTagOpen:
468
if z.readRawEndTag() || z.err != nil {
471
goto scriptDataEscaped
473
scriptDataDoubleEscapeStart:
475
for i := 0; i < len("script"); i++ {
480
if c != "script"[i] && c != "SCRIPT"[i] {
482
goto scriptDataEscaped
490
case ' ', '\n', '\r', '\t', '\f', '/', '>':
491
goto scriptDataDoubleEscaped
494
goto scriptDataEscaped
496
scriptDataDoubleEscaped:
503
goto scriptDataDoubleEscapedDash
505
goto scriptDataDoubleEscapedLessThanSign
507
goto scriptDataDoubleEscaped
509
scriptDataDoubleEscapedDash:
516
goto scriptDataDoubleEscapedDashDash
518
goto scriptDataDoubleEscapedLessThanSign
520
goto scriptDataDoubleEscaped
522
scriptDataDoubleEscapedDashDash:
529
goto scriptDataDoubleEscapedDashDash
531
goto scriptDataDoubleEscapedLessThanSign
535
goto scriptDataDoubleEscaped
537
scriptDataDoubleEscapedLessThanSign:
543
goto scriptDataDoubleEscapeEnd
546
goto scriptDataDoubleEscaped
548
scriptDataDoubleEscapeEnd:
549
if z.readRawEndTag() {
550
z.raw.end += len("</script>")
551
goto scriptDataEscaped
556
goto scriptDataDoubleEscaped
559
// readComment reads the next comment token starting with "<!--". The opening
560
// "<!--" has already been consumed.
561
func (z *Tokenizer) readComment() {
562
z.data.start = z.raw.end
564
if z.data.end < z.data.start {
565
// It's a comment with no data, like <!-->.
566
z.data.end = z.data.start
569
for dashCount := 2; ; {
572
// Ignore up to two dashes at EOF.
576
z.data.end = z.raw.end - dashCount
585
z.data.end = z.raw.end - len("-->")
592
z.data.end = z.raw.end
596
z.data.end = z.raw.end - len("--!>")
605
// readUntilCloseAngle reads until the next ">".
606
func (z *Tokenizer) readUntilCloseAngle() {
607
z.data.start = z.raw.end
611
z.data.end = z.raw.end
615
z.data.end = z.raw.end - len(">")
621
// readMarkupDeclaration reads the next token starting with "<!". It might be
622
// a "<!--comment-->", a "<!DOCTYPE foo>", a "<![CDATA[section]]>" or
623
// "<!a bogus comment". The opening "<!" has already been consumed.
624
func (z *Tokenizer) readMarkupDeclaration() TokenType {
625
z.data.start = z.raw.end
627
for i := 0; i < 2; i++ {
630
z.data.end = z.raw.end
634
if c[0] == '-' && c[1] == '-' {
642
if z.allowCDATA && z.readCDATA() {
646
// It's a bogus comment.
647
z.readUntilCloseAngle()
651
// readDoctype attempts to read a doctype declaration and returns true if
652
// successful. The opening "<!" has already been consumed.
653
func (z *Tokenizer) readDoctype() bool {
655
for i := 0; i < len(s); i++ {
658
z.data.end = z.raw.end
661
if c != s[i] && c != s[i]+('a'-'A') {
662
// Back up to read the fragment of "DOCTYPE" again.
663
z.raw.end = z.data.start
667
if z.skipWhiteSpace(); z.err != nil {
668
z.data.start = z.raw.end
669
z.data.end = z.raw.end
672
z.readUntilCloseAngle()
676
// readCDATA attempts to read a CDATA section and returns true if
677
// successful. The opening "<!" has already been consumed.
678
func (z *Tokenizer) readCDATA() bool {
680
for i := 0; i < len(s); i++ {
683
z.data.end = z.raw.end
687
// Back up to read the fragment of "[CDATA[" again.
688
z.raw.end = z.data.start
692
z.data.start = z.raw.end
697
z.data.end = z.raw.end
705
z.data.end = z.raw.end - len("]]>")
716
// startTagIn returns whether the start tag in z.buf[z.data.start:z.data.end]
717
// case-insensitively matches any element of ss.
718
func (z *Tokenizer) startTagIn(ss ...string) bool {
720
for _, s := range ss {
721
if z.data.end-z.data.start != len(s) {
724
for i := 0; i < len(s); i++ {
725
c := z.buf[z.data.start+i]
726
if 'A' <= c && c <= 'Z' {
738
// readStartTag reads the next start tag token. The opening "<a" has already
739
// been consumed, where 'a' means anything in [A-Za-z].
740
func (z *Tokenizer) readStartTag() TokenType {
745
// Several tags flag the tokenizer's next token as raw.
746
c, raw := z.buf[z.data.start], false
747
if 'A' <= c && c <= 'Z' {
752
raw = z.startTagIn("iframe")
754
raw = z.startTagIn("noembed", "noframes", "noscript")
756
raw = z.startTagIn("plaintext")
758
raw = z.startTagIn("script", "style")
760
raw = z.startTagIn("textarea", "title")
762
raw = z.startTagIn("xmp")
765
z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end]))
767
// Look for a self-closing token like "<br/>".
768
if z.err == nil && z.buf[z.raw.end-2] == '/' {
769
return SelfClosingTagToken
774
// readTag reads the next tag token and its attributes. If saveAttr, those
775
// attributes are saved in z.attr, otherwise z.attr is set to an empty slice.
776
// The opening "<a" or "</a" has already been consumed, where 'a' means anything
778
func (z *Tokenizer) readTag(saveAttr bool) {
781
// Read the tag name and attribute key/value pairs.
783
if z.skipWhiteSpace(); z.err != nil {
788
if z.err != nil || c == '>' {
794
// Save pendingAttr if saveAttr and that attribute has a non-empty key.
795
if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end {
796
z.attr = append(z.attr, z.pendingAttr)
798
if z.skipWhiteSpace(); z.err != nil {
804
// readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end)
805
// is positioned such that the first byte of the tag name (the "d" in "<div")
806
// has already been consumed.
807
func (z *Tokenizer) readTagName() {
808
z.data.start = z.raw.end - 1
812
z.data.end = z.raw.end
816
case ' ', '\n', '\r', '\t', '\f':
817
z.data.end = z.raw.end - 1
821
z.data.end = z.raw.end
827
// readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>".
828
// Precondition: z.err == nil.
829
func (z *Tokenizer) readTagAttrKey() {
830
z.pendingAttr[0].start = z.raw.end
834
z.pendingAttr[0].end = z.raw.end
838
case ' ', '\n', '\r', '\t', '\f', '/':
839
z.pendingAttr[0].end = z.raw.end - 1
843
z.pendingAttr[0].end = z.raw.end
849
// readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>".
850
func (z *Tokenizer) readTagAttrVal() {
851
z.pendingAttr[1].start = z.raw.end
852
z.pendingAttr[1].end = z.raw.end
853
if z.skipWhiteSpace(); z.err != nil {
864
if z.skipWhiteSpace(); z.err != nil {
867
quote := z.readByte()
877
z.pendingAttr[1].start = z.raw.end
881
z.pendingAttr[1].end = z.raw.end
885
z.pendingAttr[1].end = z.raw.end - 1
891
z.pendingAttr[1].start = z.raw.end - 1
895
z.pendingAttr[1].end = z.raw.end
899
case ' ', '\n', '\r', '\t', '\f':
900
z.pendingAttr[1].end = z.raw.end - 1
904
z.pendingAttr[1].end = z.raw.end
911
// Next scans the next token and returns its type.
912
func (z *Tokenizer) Next() TokenType {
917
z.raw.start = z.raw.end
918
z.data.start = z.raw.end
919
z.data.end = z.raw.end
921
if z.rawTag == "plaintext" {
922
// Read everything up to EOF.
926
z.data.end = z.raw.end
931
if z.data.end > z.data.start {
950
// Check if the '<' we have just read is part of a tag, comment
951
// or doctype. If not, it's part of the accumulated text token.
956
var tokenType TokenType
958
case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
959
tokenType = StartTagToken
961
tokenType = EndTagToken
962
case c == '!' || c == '?':
963
// We use CommentToken to mean any of "<!--actual comments-->",
964
// "<!DOCTYPE declarations>" and "<?xml processing instructions?>".
965
tokenType = CommentToken
970
// We have a non-text token, but we might have accumulated some text
971
// before that. If so, we return the text first, and return the non-
972
// text token on the subsequent call to Next.
973
if x := z.raw.end - len("<a"); z.raw.start < x {
981
z.tt = z.readStartTag()
989
// "</>" does not generate a token at all.
990
// Reset the tokenizer state and start again.
991
z.raw.start = z.raw.end
992
z.data.start = z.raw.end
993
z.data.end = z.raw.end
996
if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
1006
z.readUntilCloseAngle()
1011
z.tt = z.readMarkupDeclaration()
1015
z.readUntilCloseAngle()
1020
if z.raw.start < z.raw.end {
1021
z.data.end = z.raw.end
1029
// Raw returns the unmodified text of the current token. Calling Next, Token,
1030
// Text, TagName or TagAttr may change the contents of the returned slice.
1031
func (z *Tokenizer) Raw() []byte {
1032
return z.buf[z.raw.start:z.raw.end]
1035
// convertNewlines converts "\r" and "\r\n" in s to "\n".
1036
// The conversion happens in place, but the resulting slice may be shorter.
1037
func convertNewlines(s []byte) []byte {
1038
for i, c := range s {
1044
if src >= len(s) || s[src] != '\n' {
1052
if src+1 < len(s) && s[src+1] == '\n' {
1068
nul = []byte("\x00")
1069
replacement = []byte("\ufffd")
1072
// Text returns the unescaped text of a text, comment or doctype token. The
1073
// contents of the returned slice may change on the next call to Next.
1074
func (z *Tokenizer) Text() []byte {
1076
case TextToken, CommentToken, DoctypeToken:
1077
s := z.buf[z.data.start:z.data.end]
1078
z.data.start = z.raw.end
1079
z.data.end = z.raw.end
1080
s = convertNewlines(s)
1081
if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) {
1082
s = bytes.Replace(s, nul, replacement, -1)
1085
s = unescape(s, false)
1092
// TagName returns the lower-cased name of a tag token (the `img` out of
1093
// `<IMG SRC="foo">`) and whether the tag has attributes.
1094
// The contents of the returned slice may change on the next call to Next.
1095
func (z *Tokenizer) TagName() (name []byte, hasAttr bool) {
1096
if z.data.start < z.data.end {
1098
case StartTagToken, EndTagToken, SelfClosingTagToken:
1099
s := z.buf[z.data.start:z.data.end]
1100
z.data.start = z.raw.end
1101
z.data.end = z.raw.end
1102
return lower(s), z.nAttrReturned < len(z.attr)
1108
// TagAttr returns the lower-cased key and unescaped value of the next unparsed
1109
// attribute for the current tag token and whether there are more attributes.
1110
// The contents of the returned slices may change on the next call to Next.
1111
func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
1112
if z.nAttrReturned < len(z.attr) {
1114
case StartTagToken, SelfClosingTagToken:
1115
x := z.attr[z.nAttrReturned]
1117
key = z.buf[x[0].start:x[0].end]
1118
val = z.buf[x[1].start:x[1].end]
1119
return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
1122
return nil, nil, false
1125
// Token returns the next Token. The result's Data and Attr values remain valid
1126
// after subsequent Next calls.
1127
func (z *Tokenizer) Token() Token {
1128
t := Token{Type: z.tt}
1130
case TextToken, CommentToken, DoctypeToken:
1131
t.Data = string(z.Text())
1132
case StartTagToken, SelfClosingTagToken, EndTagToken:
1133
name, moreAttr := z.TagName()
1136
key, val, moreAttr = z.TagAttr()
1137
t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)})
1139
if a := atom.Lookup(name); a != 0 {
1140
t.DataAtom, t.Data = a, a.String()
1142
t.DataAtom, t.Data = 0, string(name)
1148
// NewTokenizer returns a new HTML Tokenizer for the given Reader.
1149
// The input is assumed to be UTF-8 encoded.
1150
func NewTokenizer(r io.Reader) *Tokenizer {
1151
return NewTokenizerFragment(r, "")
1154
// NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for
1155
// tokenizing an exisitng element's InnerHTML fragment. contextTag is that
1156
// element's tag, such as "div" or "iframe".
1158
// For example, how the InnerHTML "a<b" is tokenized depends on whether it is
1159
// for a <p> tag or a <script> tag.
1161
// The input is assumed to be UTF-8 encoded.
1162
func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer {
1165
buf: make([]byte, 0, 4096),
1167
if contextTag != "" {
1168
switch s := strings.ToLower(contextTag); s {
1169
case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp":