Source file src/encoding/xml/xml.go

     1  // Copyright 2009 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.
     4  
     5  // Package xml implements a simple XML 1.0 parser that
     6  // understands XML name spaces.
     7  package xml
     8  
     9  // References:
    10  //    Annotated XML spec: https://www.xml.com/axml/testaxml.htm
    11  //    XML name spaces: https://www.w3.org/TR/REC-xml-names/
    12  
    13  import (
    14  	"bufio"
    15  	"bytes"
    16  	"errors"
    17  	"fmt"
    18  	"io"
    19  	"strconv"
    20  	"strings"
    21  	"unicode"
    22  	"unicode/utf8"
    23  )
    24  
    25  // A SyntaxError represents a syntax error in the XML input stream.
    26  type SyntaxError struct {
    27  	Msg  string
    28  	Line int
    29  }
    30  
    31  func (e *SyntaxError) Error() string {
    32  	return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg
    33  }
    34  
    35  // A Name represents an XML name (Local) annotated
    36  // with a name space identifier (Space).
    37  // In tokens returned by Decoder.Token, the Space identifier
    38  // is given as a canonical URL, not the short prefix used
    39  // in the document being parsed.
    40  type Name struct {
    41  	Space, Local string
    42  }
    43  
    44  // An Attr represents an attribute in an XML element (Name=Value).
    45  type Attr struct {
    46  	Name  Name
    47  	Value string
    48  }
    49  
    50  // A Token is an interface holding one of the token types:
    51  // StartElement, EndElement, CharData, Comment, ProcInst, or Directive.
    52  type Token any
    53  
    54  // A StartElement represents an XML start element.
    55  type StartElement struct {
    56  	Name Name
    57  	Attr []Attr
    58  }
    59  
    60  // Copy creates a new copy of StartElement.
    61  func (e StartElement) Copy() StartElement {
    62  	attrs := make([]Attr, len(e.Attr))
    63  	copy(attrs, e.Attr)
    64  	e.Attr = attrs
    65  	return e
    66  }
    67  
    68  // End returns the corresponding XML end element.
    69  func (e StartElement) End() EndElement {
    70  	return EndElement{e.Name}
    71  }
    72  
    73  // An EndElement represents an XML end element.
    74  type EndElement struct {
    75  	Name Name
    76  }
    77  
    78  // A CharData represents XML character data (raw text),
    79  // in which XML escape sequences have been replaced by
    80  // the characters they represent.
    81  type CharData []byte
    82  
    83  func makeCopy(b []byte) []byte {
    84  	b1 := make([]byte, len(b))
    85  	copy(b1, b)
    86  	return b1
    87  }
    88  
    89  // Copy creates a new copy of CharData.
    90  func (c CharData) Copy() CharData { return CharData(makeCopy(c)) }
    91  
    92  // A Comment represents an XML comment of the form <!--comment-->.
    93  // The bytes do not include the <!-- and --> comment markers.
    94  type Comment []byte
    95  
    96  // Copy creates a new copy of Comment.
    97  func (c Comment) Copy() Comment { return Comment(makeCopy(c)) }
    98  
    99  // A ProcInst represents an XML processing instruction of the form <?target inst?>
   100  type ProcInst struct {
   101  	Target string
   102  	Inst   []byte
   103  }
   104  
   105  // Copy creates a new copy of ProcInst.
   106  func (p ProcInst) Copy() ProcInst {
   107  	p.Inst = makeCopy(p.Inst)
   108  	return p
   109  }
   110  
   111  // A Directive represents an XML directive of the form <!text>.
   112  // The bytes do not include the <! and > markers.
   113  type Directive []byte
   114  
   115  // Copy creates a new copy of Directive.
   116  func (d Directive) Copy() Directive { return Directive(makeCopy(d)) }
   117  
   118  // CopyToken returns a copy of a Token.
   119  func CopyToken(t Token) Token {
   120  	switch v := t.(type) {
   121  	case CharData:
   122  		return v.Copy()
   123  	case Comment:
   124  		return v.Copy()
   125  	case Directive:
   126  		return v.Copy()
   127  	case ProcInst:
   128  		return v.Copy()
   129  	case StartElement:
   130  		return v.Copy()
   131  	}
   132  	return t
   133  }
   134  
   135  // A TokenReader is anything that can decode a stream of XML tokens, including a
   136  // Decoder.
   137  //
   138  // When Token encounters an error or end-of-file condition after successfully
   139  // reading a token, it returns the token. It may return the (non-nil) error from
   140  // the same call or return the error (and a nil token) from a subsequent call.
   141  // An instance of this general case is that a TokenReader returning a non-nil
   142  // token at the end of the token stream may return either io.EOF or a nil error.
   143  // The next Read should return nil, io.EOF.
   144  //
   145  // Implementations of Token are discouraged from returning a nil token with a
   146  // nil error. Callers should treat a return of nil, nil as indicating that
   147  // nothing happened; in particular it does not indicate EOF.
   148  type TokenReader interface {
   149  	Token() (Token, error)
   150  }
   151  
   152  // A Decoder represents an XML parser reading a particular input stream.
   153  // The parser assumes that its input is encoded in UTF-8.
   154  type Decoder struct {
   155  	// Strict defaults to true, enforcing the requirements
   156  	// of the XML specification.
   157  	// If set to false, the parser allows input containing common
   158  	// mistakes:
   159  	//	* If an element is missing an end tag, the parser invents
   160  	//	  end tags as necessary to keep the return values from Token
   161  	//	  properly balanced.
   162  	//	* In attribute values and character data, unknown or malformed
   163  	//	  character entities (sequences beginning with &) are left alone.
   164  	//
   165  	// Setting:
   166  	//
   167  	//	d.Strict = false
   168  	//	d.AutoClose = xml.HTMLAutoClose
   169  	//	d.Entity = xml.HTMLEntity
   170  	//
   171  	// creates a parser that can handle typical HTML.
   172  	//
   173  	// Strict mode does not enforce the requirements of the XML name spaces TR.
   174  	// In particular it does not reject name space tags using undefined prefixes.
   175  	// Such tags are recorded with the unknown prefix as the name space URL.
   176  	Strict bool
   177  
   178  	// When Strict == false, AutoClose indicates a set of elements to
   179  	// consider closed immediately after they are opened, regardless
   180  	// of whether an end element is present.
   181  	AutoClose []string
   182  
   183  	// Entity can be used to map non-standard entity names to string replacements.
   184  	// The parser behaves as if these standard mappings are present in the map,
   185  	// regardless of the actual map content:
   186  	//
   187  	//	"lt": "<",
   188  	//	"gt": ">",
   189  	//	"amp": "&",
   190  	//	"apos": "'",
   191  	//	"quot": `"`,
   192  	Entity map[string]string
   193  
   194  	// CharsetReader, if non-nil, defines a function to generate
   195  	// charset-conversion readers, converting from the provided
   196  	// non-UTF-8 charset into UTF-8. If CharsetReader is nil or
   197  	// returns an error, parsing stops with an error. One of the
   198  	// CharsetReader's result values must be non-nil.
   199  	CharsetReader func(charset string, input io.Reader) (io.Reader, error)
   200  
   201  	// DefaultSpace sets the default name space used for unadorned tags,
   202  	// as if the entire XML stream were wrapped in an element containing
   203  	// the attribute xmlns="DefaultSpace".
   204  	DefaultSpace string
   205  
   206  	r              io.ByteReader
   207  	t              TokenReader
   208  	buf            bytes.Buffer
   209  	saved          *bytes.Buffer
   210  	stk            *stack
   211  	free           *stack
   212  	needClose      bool
   213  	toClose        Name
   214  	nextToken      Token
   215  	nextByte       int
   216  	ns             map[string]string
   217  	err            error
   218  	line           int
   219  	linestart      int64
   220  	offset         int64
   221  	unmarshalDepth int
   222  }
   223  
   224  // NewDecoder creates a new XML parser reading from r.
   225  // If r does not implement io.ByteReader, NewDecoder will
   226  // do its own buffering.
   227  func NewDecoder(r io.Reader) *Decoder {
   228  	d := &Decoder{
   229  		ns:       make(map[string]string),
   230  		nextByte: -1,
   231  		line:     1,
   232  		Strict:   true,
   233  	}
   234  	d.switchToReader(r)
   235  	return d
   236  }
   237  
   238  // NewTokenDecoder creates a new XML parser using an underlying token stream.
   239  func NewTokenDecoder(t TokenReader) *Decoder {
   240  	// Is it already a Decoder?
   241  	if d, ok := t.(*Decoder); ok {
   242  		return d
   243  	}
   244  	d := &Decoder{
   245  		ns:       make(map[string]string),
   246  		t:        t,
   247  		nextByte: -1,
   248  		line:     1,
   249  		Strict:   true,
   250  	}
   251  	return d
   252  }
   253  
   254  // Token returns the next XML token in the input stream.
   255  // At the end of the input stream, Token returns nil, io.EOF.
   256  //
   257  // Slices of bytes in the returned token data refer to the
   258  // parser's internal buffer and remain valid only until the next
   259  // call to Token. To acquire a copy of the bytes, call CopyToken
   260  // or the token's Copy method.
   261  //
   262  // Token expands self-closing elements such as <br>
   263  // into separate start and end elements returned by successive calls.
   264  //
   265  // Token guarantees that the StartElement and EndElement
   266  // tokens it returns are properly nested and matched:
   267  // if Token encounters an unexpected end element
   268  // or EOF before all expected end elements,
   269  // it will return an error.
   270  //
   271  // Token implements XML name spaces as described by
   272  // https://www.w3.org/TR/REC-xml-names/. Each of the
   273  // Name structures contained in the Token has the Space
   274  // set to the URL identifying its name space when known.
   275  // If Token encounters an unrecognized name space prefix,
   276  // it uses the prefix as the Space rather than report an error.
   277  func (d *Decoder) Token() (Token, error) {
   278  	var t Token
   279  	var err error
   280  	if d.stk != nil && d.stk.kind == stkEOF {
   281  		return nil, io.EOF
   282  	}
   283  	if d.nextToken != nil {
   284  		t = d.nextToken
   285  		d.nextToken = nil
   286  	} else {
   287  		if t, err = d.rawToken(); t == nil && err != nil {
   288  			if err == io.EOF && d.stk != nil && d.stk.kind != stkEOF {
   289  				err = d.syntaxError("unexpected EOF")
   290  			}
   291  			return nil, err
   292  		}
   293  		// We still have a token to process, so clear any
   294  		// errors (e.g. EOF) and proceed.
   295  		err = nil
   296  	}
   297  	if !d.Strict {
   298  		if t1, ok := d.autoClose(t); ok {
   299  			d.nextToken = t
   300  			t = t1
   301  		}
   302  	}
   303  	switch t1 := t.(type) {
   304  	case StartElement:
   305  		// In XML name spaces, the translations listed in the
   306  		// attributes apply to the element name and
   307  		// to the other attribute names, so process
   308  		// the translations first.
   309  		for _, a := range t1.Attr {
   310  			if a.Name.Space == xmlnsPrefix {
   311  				v, ok := d.ns[a.Name.Local]
   312  				d.pushNs(a.Name.Local, v, ok)
   313  				d.ns[a.Name.Local] = a.Value
   314  			}
   315  			if a.Name.Space == "" && a.Name.Local == xmlnsPrefix {
   316  				// Default space for untagged names
   317  				v, ok := d.ns[""]
   318  				d.pushNs("", v, ok)
   319  				d.ns[""] = a.Value
   320  			}
   321  		}
   322  
   323  		d.translate(&t1.Name, true)
   324  		for i := range t1.Attr {
   325  			d.translate(&t1.Attr[i].Name, false)
   326  		}
   327  		d.pushElement(t1.Name)
   328  		t = t1
   329  
   330  	case EndElement:
   331  		d.translate(&t1.Name, true)
   332  		if !d.popElement(&t1) {
   333  			return nil, d.err
   334  		}
   335  		t = t1
   336  	}
   337  	return t, err
   338  }
   339  
   340  const (
   341  	xmlURL      = "http://www.w3.org/XML/1998/namespace"
   342  	xmlnsPrefix = "xmlns"
   343  	xmlPrefix   = "xml"
   344  )
   345  
   346  // Apply name space translation to name n.
   347  // The default name space (for Space=="")
   348  // applies only to element names, not to attribute names.
   349  func (d *Decoder) translate(n *Name, isElementName bool) {
   350  	switch {
   351  	case n.Space == xmlnsPrefix:
   352  		return
   353  	case n.Space == "" && !isElementName:
   354  		return
   355  	case n.Space == xmlPrefix:
   356  		n.Space = xmlURL
   357  	case n.Space == "" && n.Local == xmlnsPrefix:
   358  		return
   359  	}
   360  	if v, ok := d.ns[n.Space]; ok {
   361  		n.Space = v
   362  	} else if n.Space == "" {
   363  		n.Space = d.DefaultSpace
   364  	}
   365  }
   366  
   367  func (d *Decoder) switchToReader(r io.Reader) {
   368  	// Get efficient byte at a time reader.
   369  	// Assume that if reader has its own
   370  	// ReadByte, it's efficient enough.
   371  	// Otherwise, use bufio.
   372  	if rb, ok := r.(io.ByteReader); ok {
   373  		d.r = rb
   374  	} else {
   375  		d.r = bufio.NewReader(r)
   376  	}
   377  }
   378  
   379  // Parsing state - stack holds old name space translations
   380  // and the current set of open elements. The translations to pop when
   381  // ending a given tag are *below* it on the stack, which is
   382  // more work but forced on us by XML.
   383  type stack struct {
   384  	next *stack
   385  	kind int
   386  	name Name
   387  	ok   bool
   388  }
   389  
   390  const (
   391  	stkStart = iota
   392  	stkNs
   393  	stkEOF
   394  )
   395  
   396  func (d *Decoder) push(kind int) *stack {
   397  	s := d.free
   398  	if s != nil {
   399  		d.free = s.next
   400  	} else {
   401  		s = new(stack)
   402  	}
   403  	s.next = d.stk
   404  	s.kind = kind
   405  	d.stk = s
   406  	return s
   407  }
   408  
   409  func (d *Decoder) pop() *stack {
   410  	s := d.stk
   411  	if s != nil {
   412  		d.stk = s.next
   413  		s.next = d.free
   414  		d.free = s
   415  	}
   416  	return s
   417  }
   418  
   419  // Record that after the current element is finished
   420  // (that element is already pushed on the stack)
   421  // Token should return EOF until popEOF is called.
   422  func (d *Decoder) pushEOF() {
   423  	// Walk down stack to find Start.
   424  	// It might not be the top, because there might be stkNs
   425  	// entries above it.
   426  	start := d.stk
   427  	for start.kind != stkStart {
   428  		start = start.next
   429  	}
   430  	// The stkNs entries below a start are associated with that
   431  	// element too; skip over them.
   432  	for start.next != nil && start.next.kind == stkNs {
   433  		start = start.next
   434  	}
   435  	s := d.free
   436  	if s != nil {
   437  		d.free = s.next
   438  	} else {
   439  		s = new(stack)
   440  	}
   441  	s.kind = stkEOF
   442  	s.next = start.next
   443  	start.next = s
   444  }
   445  
   446  // Undo a pushEOF.
   447  // The element must have been finished, so the EOF should be at the top of the stack.
   448  func (d *Decoder) popEOF() bool {
   449  	if d.stk == nil || d.stk.kind != stkEOF {
   450  		return false
   451  	}
   452  	d.pop()
   453  	return true
   454  }
   455  
   456  // Record that we are starting an element with the given name.
   457  func (d *Decoder) pushElement(name Name) {
   458  	s := d.push(stkStart)
   459  	s.name = name
   460  }
   461  
   462  // Record that we are changing the value of ns[local].
   463  // The old value is url, ok.
   464  func (d *Decoder) pushNs(local string, url string, ok bool) {
   465  	s := d.push(stkNs)
   466  	s.name.Local = local
   467  	s.name.Space = url
   468  	s.ok = ok
   469  }
   470  
   471  // Creates a SyntaxError with the current line number.
   472  func (d *Decoder) syntaxError(msg string) error {
   473  	return &SyntaxError{Msg: msg, Line: d.line}
   474  }
   475  
   476  // Record that we are ending an element with the given name.
   477  // The name must match the record at the top of the stack,
   478  // which must be a pushElement record.
   479  // After popping the element, apply any undo records from
   480  // the stack to restore the name translations that existed
   481  // before we saw this element.
   482  func (d *Decoder) popElement(t *EndElement) bool {
   483  	s := d.pop()
   484  	name := t.Name
   485  	switch {
   486  	case s == nil || s.kind != stkStart:
   487  		d.err = d.syntaxError("unexpected end element </" + name.Local + ">")
   488  		return false
   489  	case s.name.Local != name.Local:
   490  		if !d.Strict {
   491  			d.needClose = true
   492  			d.toClose = t.Name
   493  			t.Name = s.name
   494  			return true
   495  		}
   496  		d.err = d.syntaxError("element <" + s.name.Local + "> closed by </" + name.Local + ">")
   497  		return false
   498  	case s.name.Space != name.Space:
   499  		d.err = d.syntaxError("element <" + s.name.Local + "> in space " + s.name.Space +
   500  			" closed by </" + name.Local + "> in space " + name.Space)
   501  		return false
   502  	}
   503  
   504  	// Pop stack until a Start or EOF is on the top, undoing the
   505  	// translations that were associated with the element we just closed.
   506  	for d.stk != nil && d.stk.kind != stkStart && d.stk.kind != stkEOF {
   507  		s := d.pop()
   508  		if s.ok {
   509  			d.ns[s.name.Local] = s.name.Space
   510  		} else {
   511  			delete(d.ns, s.name.Local)
   512  		}
   513  	}
   514  
   515  	return true
   516  }
   517  
   518  // If the top element on the stack is autoclosing and
   519  // t is not the end tag, invent the end tag.
   520  func (d *Decoder) autoClose(t Token) (Token, bool) {
   521  	if d.stk == nil || d.stk.kind != stkStart {
   522  		return nil, false
   523  	}
   524  	for _, s := range d.AutoClose {
   525  		if strings.EqualFold(s, d.stk.name.Local) {
   526  			// This one should be auto closed if t doesn't close it.
   527  			et, ok := t.(EndElement)
   528  			if !ok || !strings.EqualFold(et.Name.Local, d.stk.name.Local) {
   529  				return EndElement{d.stk.name}, true
   530  			}
   531  			break
   532  		}
   533  	}
   534  	return nil, false
   535  }
   536  
   537  var errRawToken = errors.New("xml: cannot use RawToken from UnmarshalXML method")
   538  
   539  // RawToken is like Token but does not verify that
   540  // start and end elements match and does not translate
   541  // name space prefixes to their corresponding URLs.
   542  func (d *Decoder) RawToken() (Token, error) {
   543  	if d.unmarshalDepth > 0 {
   544  		return nil, errRawToken
   545  	}
   546  	return d.rawToken()
   547  }
   548  
   549  func (d *Decoder) rawToken() (Token, error) {
   550  	if d.t != nil {
   551  		return d.t.Token()
   552  	}
   553  	if d.err != nil {
   554  		return nil, d.err
   555  	}
   556  	if d.needClose {
   557  		// The last element we read was self-closing and
   558  		// we returned just the StartElement half.
   559  		// Return the EndElement half now.
   560  		d.needClose = false
   561  		return EndElement{d.toClose}, nil
   562  	}
   563  
   564  	b, ok := d.getc()
   565  	if !ok {
   566  		return nil, d.err
   567  	}
   568  
   569  	if b != '<' {
   570  		// Text section.
   571  		d.ungetc(b)
   572  		data := d.text(-1, false)
   573  		if data == nil {
   574  			return nil, d.err
   575  		}
   576  		return CharData(data), nil
   577  	}
   578  
   579  	if b, ok = d.mustgetc(); !ok {
   580  		return nil, d.err
   581  	}
   582  	switch b {
   583  	case '/':
   584  		// </: End element
   585  		var name Name
   586  		if name, ok = d.nsname(); !ok {
   587  			if d.err == nil {
   588  				d.err = d.syntaxError("expected element name after </")
   589  			}
   590  			return nil, d.err
   591  		}
   592  		d.space()
   593  		if b, ok = d.mustgetc(); !ok {
   594  			return nil, d.err
   595  		}
   596  		if b != '>' {
   597  			d.err = d.syntaxError("invalid characters between </" + name.Local + " and >")
   598  			return nil, d.err
   599  		}
   600  		return EndElement{name}, nil
   601  
   602  	case '?':
   603  		// <?: Processing instruction.
   604  		var target string
   605  		if target, ok = d.name(); !ok {
   606  			if d.err == nil {
   607  				d.err = d.syntaxError("expected target name after <?")
   608  			}
   609  			return nil, d.err
   610  		}
   611  		d.space()
   612  		d.buf.Reset()
   613  		var b0 byte
   614  		for {
   615  			if b, ok = d.mustgetc(); !ok {
   616  				return nil, d.err
   617  			}
   618  			d.buf.WriteByte(b)
   619  			if b0 == '?' && b == '>' {
   620  				break
   621  			}
   622  			b0 = b
   623  		}
   624  		data := d.buf.Bytes()
   625  		data = data[0 : len(data)-2] // chop ?>
   626  
   627  		if target == "xml" {
   628  			content := string(data)
   629  			ver := procInst("version", content)
   630  			if ver != "" && ver != "1.0" {
   631  				d.err = fmt.Errorf("xml: unsupported version %q; only version 1.0 is supported", ver)
   632  				return nil, d.err
   633  			}
   634  			enc := procInst("encoding", content)
   635  			if enc != "" && enc != "utf-8" && enc != "UTF-8" && !strings.EqualFold(enc, "utf-8") {
   636  				if d.CharsetReader == nil {
   637  					d.err = fmt.Errorf("xml: encoding %q declared but Decoder.CharsetReader is nil", enc)
   638  					return nil, d.err
   639  				}
   640  				newr, err := d.CharsetReader(enc, d.r.(io.Reader))
   641  				if err != nil {
   642  					d.err = fmt.Errorf("xml: opening charset %q: %v", enc, err)
   643  					return nil, d.err
   644  				}
   645  				if newr == nil {
   646  					panic("CharsetReader returned a nil Reader for charset " + enc)
   647  				}
   648  				d.switchToReader(newr)
   649  			}
   650  		}
   651  		return ProcInst{target, data}, nil
   652  
   653  	case '!':
   654  		// <!: Maybe comment, maybe CDATA.
   655  		if b, ok = d.mustgetc(); !ok {
   656  			return nil, d.err
   657  		}
   658  		switch b {
   659  		case '-': // <!-
   660  			// Probably <!-- for a comment.
   661  			if b, ok = d.mustgetc(); !ok {
   662  				return nil, d.err
   663  			}
   664  			if b != '-' {
   665  				d.err = d.syntaxError("invalid sequence <!- not part of <!--")
   666  				return nil, d.err
   667  			}
   668  			// Look for terminator.
   669  			d.buf.Reset()
   670  			var b0, b1 byte
   671  			for {
   672  				if b, ok = d.mustgetc(); !ok {
   673  					return nil, d.err
   674  				}
   675  				d.buf.WriteByte(b)
   676  				if b0 == '-' && b1 == '-' {
   677  					if b != '>' {
   678  						d.err = d.syntaxError(
   679  							`invalid sequence "--" not allowed in comments`)
   680  						return nil, d.err
   681  					}
   682  					break
   683  				}
   684  				b0, b1 = b1, b
   685  			}
   686  			data := d.buf.Bytes()
   687  			data = data[0 : len(data)-3] // chop -->
   688  			return Comment(data), nil
   689  
   690  		case '[': // <![
   691  			// Probably <![CDATA[.
   692  			for i := 0; i < 6; i++ {
   693  				if b, ok = d.mustgetc(); !ok {
   694  					return nil, d.err
   695  				}
   696  				if b != "CDATA["[i] {
   697  					d.err = d.syntaxError("invalid <![ sequence")
   698  					return nil, d.err
   699  				}
   700  			}
   701  			// Have <![CDATA[.  Read text until ]]>.
   702  			data := d.text(-1, true)
   703  			if data == nil {
   704  				return nil, d.err
   705  			}
   706  			return CharData(data), nil
   707  		}
   708  
   709  		// Probably a directive: <!DOCTYPE ...>, <!ENTITY ...>, etc.
   710  		// We don't care, but accumulate for caller. Quoted angle
   711  		// brackets do not count for nesting.
   712  		d.buf.Reset()
   713  		d.buf.WriteByte(b)
   714  		inquote := uint8(0)
   715  		depth := 0
   716  		for {
   717  			if b, ok = d.mustgetc(); !ok {
   718  				return nil, d.err
   719  			}
   720  			if inquote == 0 && b == '>' && depth == 0 {
   721  				break
   722  			}
   723  		HandleB:
   724  			d.buf.WriteByte(b)
   725  			switch {
   726  			case b == inquote:
   727  				inquote = 0
   728  
   729  			case inquote != 0:
   730  				// in quotes, no special action
   731  
   732  			case b == '\'' || b == '"':
   733  				inquote = b
   734  
   735  			case b == '>' && inquote == 0:
   736  				depth--
   737  
   738  			case b == '<' && inquote == 0:
   739  				// Look for <!-- to begin comment.
   740  				s := "!--"
   741  				for i := 0; i < len(s); i++ {
   742  					if b, ok = d.mustgetc(); !ok {
   743  						return nil, d.err
   744  					}
   745  					if b != s[i] {
   746  						for j := 0; j < i; j++ {
   747  							d.buf.WriteByte(s[j])
   748  						}
   749  						depth++
   750  						goto HandleB
   751  					}
   752  				}
   753  
   754  				// Remove < that was written above.
   755  				d.buf.Truncate(d.buf.Len() - 1)
   756  
   757  				// Look for terminator.
   758  				var b0, b1 byte
   759  				for {
   760  					if b, ok = d.mustgetc(); !ok {
   761  						return nil, d.err
   762  					}
   763  					if b0 == '-' && b1 == '-' && b == '>' {
   764  						break
   765  					}
   766  					b0, b1 = b1, b
   767  				}
   768  
   769  				// Replace the comment with a space in the returned Directive
   770  				// body, so that markup parts that were separated by the comment
   771  				// (like a "<" and a "!") don't get joined when re-encoding the
   772  				// Directive, taking new semantic meaning.
   773  				d.buf.WriteByte(' ')
   774  			}
   775  		}
   776  		return Directive(d.buf.Bytes()), nil
   777  	}
   778  
   779  	// Must be an open element like <a href="foo">
   780  	d.ungetc(b)
   781  
   782  	var (
   783  		name  Name
   784  		empty bool
   785  		attr  []Attr
   786  	)
   787  	if name, ok = d.nsname(); !ok {
   788  		if d.err == nil {
   789  			d.err = d.syntaxError("expected element name after <")
   790  		}
   791  		return nil, d.err
   792  	}
   793  
   794  	attr = []Attr{}
   795  	for {
   796  		d.space()
   797  		if b, ok = d.mustgetc(); !ok {
   798  			return nil, d.err
   799  		}
   800  		if b == '/' {
   801  			empty = true
   802  			if b, ok = d.mustgetc(); !ok {
   803  				return nil, d.err
   804  			}
   805  			if b != '>' {
   806  				d.err = d.syntaxError("expected /> in element")
   807  				return nil, d.err
   808  			}
   809  			break
   810  		}
   811  		if b == '>' {
   812  			break
   813  		}
   814  		d.ungetc(b)
   815  
   816  		a := Attr{}
   817  		if a.Name, ok = d.nsname(); !ok {
   818  			if d.err == nil {
   819  				d.err = d.syntaxError("expected attribute name in element")
   820  			}
   821  			return nil, d.err
   822  		}
   823  		d.space()
   824  		if b, ok = d.mustgetc(); !ok {
   825  			return nil, d.err
   826  		}
   827  		if b != '=' {
   828  			if d.Strict {
   829  				d.err = d.syntaxError("attribute name without = in element")
   830  				return nil, d.err
   831  			}
   832  			d.ungetc(b)
   833  			a.Value = a.Name.Local
   834  		} else {
   835  			d.space()
   836  			data := d.attrval()
   837  			if data == nil {
   838  				return nil, d.err
   839  			}
   840  			a.Value = string(data)
   841  		}
   842  		attr = append(attr, a)
   843  	}
   844  	if empty {
   845  		d.needClose = true
   846  		d.toClose = name
   847  	}
   848  	return StartElement{name, attr}, nil
   849  }
   850  
   851  func (d *Decoder) attrval() []byte {
   852  	b, ok := d.mustgetc()
   853  	if !ok {
   854  		return nil
   855  	}
   856  	// Handle quoted attribute values
   857  	if b == '"' || b == '\'' {
   858  		return d.text(int(b), false)
   859  	}
   860  	// Handle unquoted attribute values for strict parsers
   861  	if d.Strict {
   862  		d.err = d.syntaxError("unquoted or missing attribute value in element")
   863  		return nil
   864  	}
   865  	// Handle unquoted attribute values for unstrict parsers
   866  	d.ungetc(b)
   867  	d.buf.Reset()
   868  	for {
   869  		b, ok = d.mustgetc()
   870  		if !ok {
   871  			return nil
   872  		}
   873  		// https://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.2
   874  		if 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z' ||
   875  			'0' <= b && b <= '9' || b == '_' || b == ':' || b == '-' {
   876  			d.buf.WriteByte(b)
   877  		} else {
   878  			d.ungetc(b)
   879  			break
   880  		}
   881  	}
   882  	return d.buf.Bytes()
   883  }
   884  
   885  // Skip spaces if any
   886  func (d *Decoder) space() {
   887  	for {
   888  		b, ok := d.getc()
   889  		if !ok {
   890  			return
   891  		}
   892  		switch b {
   893  		case ' ', '\r', '\n', '\t':
   894  		default:
   895  			d.ungetc(b)
   896  			return
   897  		}
   898  	}
   899  }
   900  
   901  // Read a single byte.
   902  // If there is no byte to read, return ok==false
   903  // and leave the error in d.err.
   904  // Maintain line number.
   905  func (d *Decoder) getc() (b byte, ok bool) {
   906  	if d.err != nil {
   907  		return 0, false
   908  	}
   909  	if d.nextByte >= 0 {
   910  		b = byte(d.nextByte)
   911  		d.nextByte = -1
   912  	} else {
   913  		b, d.err = d.r.ReadByte()
   914  		if d.err != nil {
   915  			return 0, false
   916  		}
   917  		if d.saved != nil {
   918  			d.saved.WriteByte(b)
   919  		}
   920  	}
   921  	if b == '\n' {
   922  		d.line++
   923  		d.linestart = d.offset + 1
   924  	}
   925  	d.offset++
   926  	return b, true
   927  }
   928  
   929  // InputOffset returns the input stream byte offset of the current decoder position.
   930  // The offset gives the location of the end of the most recently returned token
   931  // and the beginning of the next token.
   932  func (d *Decoder) InputOffset() int64 {
   933  	return d.offset
   934  }
   935  
   936  // InputPos returns the line of the current decoder position and the 1 based
   937  // input position of the line. The position gives the location of the end of the
   938  // most recently returned token.
   939  func (d *Decoder) InputPos() (line, column int) {
   940  	return d.line, int(d.offset-d.linestart) + 1
   941  }
   942  
   943  // Return saved offset.
   944  // If we did ungetc (nextByte >= 0), have to back up one.
   945  func (d *Decoder) savedOffset() int {
   946  	n := d.saved.Len()
   947  	if d.nextByte >= 0 {
   948  		n--
   949  	}
   950  	return n
   951  }
   952  
   953  // Must read a single byte.
   954  // If there is no byte to read,
   955  // set d.err to SyntaxError("unexpected EOF")
   956  // and return ok==false
   957  func (d *Decoder) mustgetc() (b byte, ok bool) {
   958  	if b, ok = d.getc(); !ok {
   959  		if d.err == io.EOF {
   960  			d.err = d.syntaxError("unexpected EOF")
   961  		}
   962  	}
   963  	return
   964  }
   965  
   966  // Unread a single byte.
   967  func (d *Decoder) ungetc(b byte) {
   968  	if b == '\n' {
   969  		d.line--
   970  	}
   971  	d.nextByte = int(b)
   972  	d.offset--
   973  }
   974  
   975  var entity = map[string]rune{
   976  	"lt":   '<',
   977  	"gt":   '>',
   978  	"amp":  '&',
   979  	"apos": '\'',
   980  	"quot": '"',
   981  }
   982  
   983  // Read plain text section (XML calls it character data).
   984  // If quote >= 0, we are in a quoted string and need to find the matching quote.
   985  // If cdata == true, we are in a <![CDATA[ section and need to find ]]>.
   986  // On failure return nil and leave the error in d.err.
   987  func (d *Decoder) text(quote int, cdata bool) []byte {
   988  	var b0, b1 byte
   989  	var trunc int
   990  	d.buf.Reset()
   991  Input:
   992  	for {
   993  		b, ok := d.getc()
   994  		if !ok {
   995  			if cdata {
   996  				if d.err == io.EOF {
   997  					d.err = d.syntaxError("unexpected EOF in CDATA section")
   998  				}
   999  				return nil
  1000  			}
  1001  			break Input
  1002  		}
  1003  
  1004  		// <![CDATA[ section ends with ]]>.
  1005  		// It is an error for ]]> to appear in ordinary text.
  1006  		if b0 == ']' && b1 == ']' && b == '>' {
  1007  			if cdata {
  1008  				trunc = 2
  1009  				break Input
  1010  			}
  1011  			d.err = d.syntaxError("unescaped ]]> not in CDATA section")
  1012  			return nil
  1013  		}
  1014  
  1015  		// Stop reading text if we see a <.
  1016  		if b == '<' && !cdata {
  1017  			if quote >= 0 {
  1018  				d.err = d.syntaxError("unescaped < inside quoted string")
  1019  				return nil
  1020  			}
  1021  			d.ungetc('<')
  1022  			break Input
  1023  		}
  1024  		if quote >= 0 && b == byte(quote) {
  1025  			break Input
  1026  		}
  1027  		if b == '&' && !cdata {
  1028  			// Read escaped character expression up to semicolon.
  1029  			// XML in all its glory allows a document to define and use
  1030  			// its own character names with <!ENTITY ...> directives.
  1031  			// Parsers are required to recognize lt, gt, amp, apos, and quot
  1032  			// even if they have not been declared.
  1033  			before := d.buf.Len()
  1034  			d.buf.WriteByte('&')
  1035  			var ok bool
  1036  			var text string
  1037  			var haveText bool
  1038  			if b, ok = d.mustgetc(); !ok {
  1039  				return nil
  1040  			}
  1041  			if b == '#' {
  1042  				d.buf.WriteByte(b)
  1043  				if b, ok = d.mustgetc(); !ok {
  1044  					return nil
  1045  				}
  1046  				base := 10
  1047  				if b == 'x' {
  1048  					base = 16
  1049  					d.buf.WriteByte(b)
  1050  					if b, ok = d.mustgetc(); !ok {
  1051  						return nil
  1052  					}
  1053  				}
  1054  				start := d.buf.Len()
  1055  				for '0' <= b && b <= '9' ||
  1056  					base == 16 && 'a' <= b && b <= 'f' ||
  1057  					base == 16 && 'A' <= b && b <= 'F' {
  1058  					d.buf.WriteByte(b)
  1059  					if b, ok = d.mustgetc(); !ok {
  1060  						return nil
  1061  					}
  1062  				}
  1063  				if b != ';' {
  1064  					d.ungetc(b)
  1065  				} else {
  1066  					s := string(d.buf.Bytes()[start:])
  1067  					d.buf.WriteByte(';')
  1068  					n, err := strconv.ParseUint(s, base, 64)
  1069  					if err == nil && n <= unicode.MaxRune {
  1070  						text = string(rune(n))
  1071  						haveText = true
  1072  					}
  1073  				}
  1074  			} else {
  1075  				d.ungetc(b)
  1076  				if !d.readName() {
  1077  					if d.err != nil {
  1078  						return nil
  1079  					}
  1080  				}
  1081  				if b, ok = d.mustgetc(); !ok {
  1082  					return nil
  1083  				}
  1084  				if b != ';' {
  1085  					d.ungetc(b)
  1086  				} else {
  1087  					name := d.buf.Bytes()[before+1:]
  1088  					d.buf.WriteByte(';')
  1089  					if isName(name) {
  1090  						s := string(name)
  1091  						if r, ok := entity[s]; ok {
  1092  							text = string(r)
  1093  							haveText = true
  1094  						} else if d.Entity != nil {
  1095  							text, haveText = d.Entity[s]
  1096  						}
  1097  					}
  1098  				}
  1099  			}
  1100  
  1101  			if haveText {
  1102  				d.buf.Truncate(before)
  1103  				d.buf.Write([]byte(text))
  1104  				b0, b1 = 0, 0
  1105  				continue Input
  1106  			}
  1107  			if !d.Strict {
  1108  				b0, b1 = 0, 0
  1109  				continue Input
  1110  			}
  1111  			ent := string(d.buf.Bytes()[before:])
  1112  			if ent[len(ent)-1] != ';' {
  1113  				ent += " (no semicolon)"
  1114  			}
  1115  			d.err = d.syntaxError("invalid character entity " + ent)
  1116  			return nil
  1117  		}
  1118  
  1119  		// We must rewrite unescaped \r and \r\n into \n.
  1120  		if b == '\r' {
  1121  			d.buf.WriteByte('\n')
  1122  		} else if b1 == '\r' && b == '\n' {
  1123  			// Skip \r\n--we already wrote \n.
  1124  		} else {
  1125  			d.buf.WriteByte(b)
  1126  		}
  1127  
  1128  		b0, b1 = b1, b
  1129  	}
  1130  	data := d.buf.Bytes()
  1131  	data = data[0 : len(data)-trunc]
  1132  
  1133  	// Inspect each rune for being a disallowed character.
  1134  	buf := data
  1135  	for len(buf) > 0 {
  1136  		r, size := utf8.DecodeRune(buf)
  1137  		if r == utf8.RuneError && size == 1 {
  1138  			d.err = d.syntaxError("invalid UTF-8")
  1139  			return nil
  1140  		}
  1141  		buf = buf[size:]
  1142  		if !isInCharacterRange(r) {
  1143  			d.err = d.syntaxError(fmt.Sprintf("illegal character code %U", r))
  1144  			return nil
  1145  		}
  1146  	}
  1147  
  1148  	return data
  1149  }
  1150  
  1151  // Decide whether the given rune is in the XML Character Range, per
  1152  // the Char production of https://www.xml.com/axml/testaxml.htm,
  1153  // Section 2.2 Characters.
  1154  func isInCharacterRange(r rune) (inrange bool) {
  1155  	return r == 0x09 ||
  1156  		r == 0x0A ||
  1157  		r == 0x0D ||
  1158  		r >= 0x20 && r <= 0xD7FF ||
  1159  		r >= 0xE000 && r <= 0xFFFD ||
  1160  		r >= 0x10000 && r <= 0x10FFFF
  1161  }
  1162  
  1163  // Get name space name: name with a : stuck in the middle.
  1164  // The part before the : is the name space identifier.
  1165  func (d *Decoder) nsname() (name Name, ok bool) {
  1166  	s, ok := d.name()
  1167  	if !ok {
  1168  		return
  1169  	}
  1170  	if strings.Count(s, ":") > 1 {
  1171  		name.Local = s
  1172  	} else if space, local, ok := strings.Cut(s, ":"); !ok || space == "" || local == "" {
  1173  		name.Local = s
  1174  	} else {
  1175  		name.Space = space
  1176  		name.Local = local
  1177  	}
  1178  	return name, true
  1179  }
  1180  
  1181  // Get name: /first(first|second)*/
  1182  // Do not set d.err if the name is missing (unless unexpected EOF is received):
  1183  // let the caller provide better context.
  1184  func (d *Decoder) name() (s string, ok bool) {
  1185  	d.buf.Reset()
  1186  	if !d.readName() {
  1187  		return "", false
  1188  	}
  1189  
  1190  	// Now we check the characters.
  1191  	b := d.buf.Bytes()
  1192  	if !isName(b) {
  1193  		d.err = d.syntaxError("invalid XML name: " + string(b))
  1194  		return "", false
  1195  	}
  1196  	return string(b), true
  1197  }
  1198  
  1199  // Read a name and append its bytes to d.buf.
  1200  // The name is delimited by any single-byte character not valid in names.
  1201  // All multi-byte characters are accepted; the caller must check their validity.
  1202  func (d *Decoder) readName() (ok bool) {
  1203  	var b byte
  1204  	if b, ok = d.mustgetc(); !ok {
  1205  		return
  1206  	}
  1207  	if b < utf8.RuneSelf && !isNameByte(b) {
  1208  		d.ungetc(b)
  1209  		return false
  1210  	}
  1211  	d.buf.WriteByte(b)
  1212  
  1213  	for {
  1214  		if b, ok = d.mustgetc(); !ok {
  1215  			return
  1216  		}
  1217  		if b < utf8.RuneSelf && !isNameByte(b) {
  1218  			d.ungetc(b)
  1219  			break
  1220  		}
  1221  		d.buf.WriteByte(b)
  1222  	}
  1223  	return true
  1224  }
  1225  
  1226  func isNameByte(c byte) bool {
  1227  	return 'A' <= c && c <= 'Z' ||
  1228  		'a' <= c && c <= 'z' ||
  1229  		'0' <= c && c <= '9' ||
  1230  		c == '_' || c == ':' || c == '.' || c == '-'
  1231  }
  1232  
  1233  func isName(s []byte) bool {
  1234  	if len(s) == 0 {
  1235  		return false
  1236  	}
  1237  	c, n := utf8.DecodeRune(s)
  1238  	if c == utf8.RuneError && n == 1 {
  1239  		return false
  1240  	}
  1241  	if !unicode.Is(first, c) {
  1242  		return false
  1243  	}
  1244  	for n < len(s) {
  1245  		s = s[n:]
  1246  		c, n = utf8.DecodeRune(s)
  1247  		if c == utf8.RuneError && n == 1 {
  1248  			return false
  1249  		}
  1250  		if !unicode.Is(first, c) && !unicode.Is(second, c) {
  1251  			return false
  1252  		}
  1253  	}
  1254  	return true
  1255  }
  1256  
  1257  func isNameString(s string) bool {
  1258  	if len(s) == 0 {
  1259  		return false
  1260  	}
  1261  	c, n := utf8.DecodeRuneInString(s)
  1262  	if c == utf8.RuneError && n == 1 {
  1263  		return false
  1264  	}
  1265  	if !unicode.Is(first, c) {
  1266  		return false
  1267  	}
  1268  	for n < len(s) {
  1269  		s = s[n:]
  1270  		c, n = utf8.DecodeRuneInString(s)
  1271  		if c == utf8.RuneError && n == 1 {
  1272  			return false
  1273  		}
  1274  		if !unicode.Is(first, c) && !unicode.Is(second, c) {
  1275  			return false
  1276  		}
  1277  	}
  1278  	return true
  1279  }
  1280  
  1281  // These tables were generated by cut and paste from Appendix B of
  1282  // the XML spec at https://www.xml.com/axml/testaxml.htm
  1283  // and then reformatting. First corresponds to (Letter | '_' | ':')
  1284  // and second corresponds to NameChar.
  1285  
  1286  var first = &unicode.RangeTable{
  1287  	R16: []unicode.Range16{
  1288  		{0x003A, 0x003A, 1},
  1289  		{0x0041, 0x005A, 1},
  1290  		{0x005F, 0x005F, 1},
  1291  		{0x0061, 0x007A, 1},
  1292  		{0x00C0, 0x00D6, 1},
  1293  		{0x00D8, 0x00F6, 1},
  1294  		{0x00F8, 0x00FF, 1},
  1295  		{0x0100, 0x0131, 1},
  1296  		{0x0134, 0x013E, 1},
  1297  		{0x0141, 0x0148, 1},
  1298  		{0x014A, 0x017E, 1},
  1299  		{0x0180, 0x01C3, 1},
  1300  		{0x01CD, 0x01F0, 1},
  1301  		{0x01F4, 0x01F5, 1},
  1302  		{0x01FA, 0x0217, 1},
  1303  		{0x0250, 0x02A8, 1},
  1304  		{0x02BB, 0x02C1, 1},
  1305  		{0x0386, 0x0386, 1},
  1306  		{0x0388, 0x038A, 1},
  1307  		{0x038C, 0x038C, 1},
  1308  		{0x038E, 0x03A1, 1},
  1309  		{0x03A3, 0x03CE, 1},
  1310  		{0x03D0, 0x03D6, 1},
  1311  		{0x03DA, 0x03E0, 2},
  1312  		{0x03E2, 0x03F3, 1},
  1313  		{0x0401, 0x040C, 1},
  1314  		{0x040E, 0x044F, 1},
  1315  		{0x0451, 0x045C, 1},
  1316  		{0x045E, 0x0481, 1},
  1317  		{0x0490, 0x04C4, 1},
  1318  		{0x04C7, 0x04C8, 1},
  1319  		{0x04CB, 0x04CC, 1},
  1320  		{0x04D0, 0x04EB, 1},
  1321  		{0x04EE, 0x04F5, 1},
  1322  		{0x04F8, 0x04F9, 1},
  1323  		{0x0531, 0x0556, 1},
  1324  		{0x0559, 0x0559, 1},
  1325  		{0x0561, 0x0586, 1},
  1326  		{0x05D0, 0x05EA, 1},
  1327  		{0x05F0, 0x05F2, 1},
  1328  		{0x0621, 0x063A, 1},
  1329  		{0x0641, 0x064A, 1},
  1330  		{0x0671, 0x06B7, 1},
  1331  		{0x06BA, 0x06BE, 1},
  1332  		{0x06C0, 0x06CE, 1},
  1333  		{0x06D0, 0x06D3, 1},
  1334  		{0x06D5, 0x06D5, 1},
  1335  		{0x06E5, 0x06E6, 1},
  1336  		{0x0905, 0x0939, 1},
  1337  		{0x093D, 0x093D, 1},
  1338  		{0x0958, 0x0961, 1},
  1339  		{0x0985, 0x098C, 1},
  1340  		{0x098F, 0x0990, 1},
  1341  		{0x0993, 0x09A8, 1},
  1342  		{0x09AA, 0x09B0, 1},
  1343  		{0x09B2, 0x09B2, 1},
  1344  		{0x09B6, 0x09B9, 1},
  1345  		{0x09DC, 0x09DD, 1},
  1346  		{0x09DF, 0x09E1, 1},
  1347  		{0x09F0, 0x09F1, 1},
  1348  		{0x0A05, 0x0A0A, 1},
  1349  		{0x0A0F, 0x0A10, 1},
  1350  		{0x0A13, 0x0A28, 1},
  1351  		{0x0A2A, 0x0A30, 1},
  1352  		{0x0A32, 0x0A33, 1},
  1353  		{0x0A35, 0x0A36, 1},
  1354  		{0x0A38, 0x0A39, 1},
  1355  		{0x0A59, 0x0A5C, 1},
  1356  		{0x0A5E, 0x0A5E, 1},
  1357  		{0x0A72, 0x0A74, 1},
  1358  		{0x0A85, 0x0A8B, 1},
  1359  		{0x0A8D, 0x0A8D, 1},
  1360  		{0x0A8F, 0x0A91, 1},
  1361  		{0x0A93, 0x0AA8, 1},
  1362  		{0x0AAA, 0x0AB0, 1},
  1363  		{0x0AB2, 0x0AB3, 1},
  1364  		{0x0AB5, 0x0AB9, 1},
  1365  		{0x0ABD, 0x0AE0, 0x23},
  1366  		{0x0B05, 0x0B0C, 1},
  1367  		{0x0B0F, 0x0B10, 1},
  1368  		{0x0B13, 0x0B28, 1},
  1369  		{0x0B2A, 0x0B30, 1},
  1370  		{0x0B32, 0x0B33, 1},
  1371  		{0x0B36, 0x0B39, 1},
  1372  		{0x0B3D, 0x0B3D, 1},
  1373  		{0x0B5C, 0x0B5D, 1},
  1374  		{0x0B5F, 0x0B61, 1},
  1375  		{0x0B85, 0x0B8A, 1},
  1376  		{0x0B8E, 0x0B90, 1},
  1377  		{0x0B92, 0x0B95, 1},
  1378  		{0x0B99, 0x0B9A, 1},
  1379  		{0x0B9C, 0x0B9C, 1},
  1380  		{0x0B9E, 0x0B9F, 1},
  1381  		{0x0BA3, 0x0BA4, 1},
  1382  		{0x0BA8, 0x0BAA, 1},
  1383  		{0x0BAE, 0x0BB5, 1},
  1384  		{0x0BB7, 0x0BB9, 1},
  1385  		{0x0C05, 0x0C0C, 1},
  1386  		{0x0C0E, 0x0C10, 1},
  1387  		{0x0C12, 0x0C28, 1},
  1388  		{0x0C2A, 0x0C33, 1},
  1389  		{0x0C35, 0x0C39, 1},
  1390  		{0x0C60, 0x0C61, 1},
  1391  		{0x0C85, 0x0C8C, 1},
  1392  		{0x0C8E, 0x0C90, 1},
  1393  		{0x0C92, 0x0CA8, 1},
  1394  		{0x0CAA, 0x0CB3, 1},
  1395  		{0x0CB5, 0x0CB9, 1},
  1396  		{0x0CDE, 0x0CDE, 1},
  1397  		{0x0CE0, 0x0CE1, 1},
  1398  		{0x0D05, 0x0D0C, 1},
  1399  		{0x0D0E, 0x0D10, 1},
  1400  		{0x0D12, 0x0D28, 1},
  1401  		{0x0D2A, 0x0D39, 1},
  1402  		{0x0D60, 0x0D61, 1},
  1403  		{0x0E01, 0x0E2E, 1},
  1404  		{0x0E30, 0x0E30, 1},
  1405  		{0x0E32, 0x0E33, 1},
  1406  		{0x0E40, 0x0E45, 1},
  1407  		{0x0E81, 0x0E82, 1},
  1408  		{0x0E84, 0x0E84, 1},
  1409  		{0x0E87, 0x0E88, 1},
  1410  		{0x0E8A, 0x0E8D, 3},
  1411  		{0x0E94, 0x0E97, 1},
  1412  		{0x0E99, 0x0E9F, 1},
  1413  		{0x0EA1, 0x0EA3, 1},
  1414  		{0x0EA5, 0x0EA7, 2},
  1415  		{0x0EAA, 0x0EAB, 1},
  1416  		{0x0EAD, 0x0EAE, 1},
  1417  		{0x0EB0, 0x0EB0, 1},
  1418  		{0x0EB2, 0x0EB3, 1},
  1419  		{0x0EBD, 0x0EBD, 1},
  1420  		{0x0EC0, 0x0EC4, 1},
  1421  		{0x0F40, 0x0F47, 1},
  1422  		{0x0F49, 0x0F69, 1},
  1423  		{0x10A0, 0x10C5, 1},
  1424  		{0x10D0, 0x10F6, 1},
  1425  		{0x1100, 0x1100, 1},
  1426  		{0x1102, 0x1103, 1},
  1427  		{0x1105, 0x1107, 1},
  1428  		{0x1109, 0x1109, 1},
  1429  		{0x110B, 0x110C, 1},
  1430  		{0x110E, 0x1112, 1},
  1431  		{0x113C, 0x1140, 2},
  1432  		{0x114C, 0x1150, 2},
  1433  		{0x1154, 0x1155, 1},
  1434  		{0x1159, 0x1159, 1},
  1435  		{0x115F, 0x1161, 1},
  1436  		{0x1163, 0x1169, 2},
  1437  		{0x116D, 0x116E, 1},
  1438  		{0x1172, 0x1173, 1},
  1439  		{0x1175, 0x119E, 0x119E - 0x1175},
  1440  		{0x11A8, 0x11AB, 0x11AB - 0x11A8},
  1441  		{0x11AE, 0x11AF, 1},
  1442  		{0x11B7, 0x11B8, 1},
  1443  		{0x11BA, 0x11BA, 1},
  1444  		{0x11BC, 0x11C2, 1},
  1445  		{0x11EB, 0x11F0, 0x11F0 - 0x11EB},
  1446  		{0x11F9, 0x11F9, 1},
  1447  		{0x1E00, 0x1E9B, 1},
  1448  		{0x1EA0, 0x1EF9, 1},
  1449  		{0x1F00, 0x1F15, 1},
  1450  		{0x1F18, 0x1F1D, 1},
  1451  		{0x1F20, 0x1F45, 1},
  1452  		{0x1F48, 0x1F4D, 1},
  1453  		{0x1F50, 0x1F57, 1},
  1454  		{0x1F59, 0x1F5B, 0x1F5B - 0x1F59},
  1455  		{0x1F5D, 0x1F5D, 1},
  1456  		{0x1F5F, 0x1F7D, 1},
  1457  		{0x1F80, 0x1FB4, 1},
  1458  		{0x1FB6, 0x1FBC, 1},
  1459  		{0x1FBE, 0x1FBE, 1},
  1460  		{0x1FC2, 0x1FC4, 1},
  1461  		{0x1FC6, 0x1FCC, 1},
  1462  		{0x1FD0, 0x1FD3, 1},
  1463  		{0x1FD6, 0x1FDB, 1},
  1464  		{0x1FE0, 0x1FEC, 1},
  1465  		{0x1FF2, 0x1FF4, 1},
  1466  		{0x1FF6, 0x1FFC, 1},
  1467  		{0x2126, 0x2126, 1},
  1468  		{0x212A, 0x212B, 1},
  1469  		{0x212E, 0x212E, 1},
  1470  		{0x2180, 0x2182, 1},
  1471  		{0x3007, 0x3007, 1},
  1472  		{0x3021, 0x3029, 1},
  1473  		{0x3041, 0x3094, 1},
  1474  		{0x30A1, 0x30FA, 1},
  1475  		{0x3105, 0x312C, 1},
  1476  		{0x4E00, 0x9FA5, 1},
  1477  		{0xAC00, 0xD7A3, 1},
  1478  	},
  1479  }
  1480  
  1481  var second = &unicode.RangeTable{
  1482  	R16: []unicode.Range16{
  1483  		{0x002D, 0x002E, 1},
  1484  		{0x0030, 0x0039, 1},
  1485  		{0x00B7, 0x00B7, 1},
  1486  		{0x02D0, 0x02D1, 1},
  1487  		{0x0300, 0x0345, 1},
  1488  		{0x0360, 0x0361, 1},
  1489  		{0x0387, 0x0387, 1},
  1490  		{0x0483, 0x0486, 1},
  1491  		{0x0591, 0x05A1, 1},
  1492  		{0x05A3, 0x05B9, 1},
  1493  		{0x05BB, 0x05BD, 1},
  1494  		{0x05BF, 0x05BF, 1},
  1495  		{0x05C1, 0x05C2, 1},
  1496  		{0x05C4, 0x0640, 0x0640 - 0x05C4},
  1497  		{0x064B, 0x0652, 1},
  1498  		{0x0660, 0x0669, 1},
  1499  		{0x0670, 0x0670, 1},
  1500  		{0x06D6, 0x06DC, 1},
  1501  		{0x06DD, 0x06DF, 1},
  1502  		{0x06E0, 0x06E4, 1},
  1503  		{0x06E7, 0x06E8, 1},
  1504  		{0x06EA, 0x06ED, 1},
  1505  		{0x06F0, 0x06F9, 1},
  1506  		{0x0901, 0x0903, 1},
  1507  		{0x093C, 0x093C, 1},
  1508  		{0x093E, 0x094C, 1},
  1509  		{0x094D, 0x094D, 1},
  1510  		{0x0951, 0x0954, 1},
  1511  		{0x0962, 0x0963, 1},
  1512  		{0x0966, 0x096F, 1},
  1513  		{0x0981, 0x0983, 1},
  1514  		{0x09BC, 0x09BC, 1},
  1515  		{0x09BE, 0x09BF, 1},
  1516  		{0x09C0, 0x09C4, 1},
  1517  		{0x09C7, 0x09C8, 1},
  1518  		{0x09CB, 0x09CD, 1},
  1519  		{0x09D7, 0x09D7, 1},
  1520  		{0x09E2, 0x09E3, 1},
  1521  		{0x09E6, 0x09EF, 1},
  1522  		{0x0A02, 0x0A3C, 0x3A},
  1523  		{0x0A3E, 0x0A3F, 1},
  1524  		{0x0A40, 0x0A42, 1},
  1525  		{0x0A47, 0x0A48, 1},
  1526  		{0x0A4B, 0x0A4D, 1},
  1527  		{0x0A66, 0x0A6F, 1},
  1528  		{0x0A70, 0x0A71, 1},
  1529  		{0x0A81, 0x0A83, 1},
  1530  		{0x0ABC, 0x0ABC, 1},
  1531  		{0x0ABE, 0x0AC5, 1},
  1532  		{0x0AC7, 0x0AC9, 1},
  1533  		{0x0ACB, 0x0ACD, 1},
  1534  		{0x0AE6, 0x0AEF, 1},
  1535  		{0x0B01, 0x0B03, 1},
  1536  		{0x0B3C, 0x0B3C, 1},
  1537  		{0x0B3E, 0x0B43, 1},
  1538  		{0x0B47, 0x0B48, 1},
  1539  		{0x0B4B, 0x0B4D, 1},
  1540  		{0x0B56, 0x0B57, 1},
  1541  		{0x0B66, 0x0B6F, 1},
  1542  		{0x0B82, 0x0B83, 1},
  1543  		{0x0BBE, 0x0BC2, 1},
  1544  		{0x0BC6, 0x0BC8, 1},
  1545  		{0x0BCA, 0x0BCD, 1},
  1546  		{0x0BD7, 0x0BD7, 1},
  1547  		{0x0BE7, 0x0BEF, 1},
  1548  		{0x0C01, 0x0C03, 1},
  1549  		{0x0C3E, 0x0C44, 1},
  1550  		{0x0C46, 0x0C48, 1},
  1551  		{0x0C4A, 0x0C4D, 1},
  1552  		{0x0C55, 0x0C56, 1},
  1553  		{0x0C66, 0x0C6F, 1},
  1554  		{0x0C82, 0x0C83, 1},
  1555  		{0x0CBE, 0x0CC4, 1},
  1556  		{0x0CC6, 0x0CC8, 1},
  1557  		{0x0CCA, 0x0CCD, 1},
  1558  		{0x0CD5, 0x0CD6, 1},
  1559  		{0x0CE6, 0x0CEF, 1},
  1560  		{0x0D02, 0x0D03, 1},
  1561  		{0x0D3E, 0x0D43, 1},
  1562  		{0x0D46, 0x0D48, 1},
  1563  		{0x0D4A, 0x0D4D, 1},
  1564  		{0x0D57, 0x0D57, 1},
  1565  		{0x0D66, 0x0D6F, 1},
  1566  		{0x0E31, 0x0E31, 1},
  1567  		{0x0E34, 0x0E3A, 1},
  1568  		{0x0E46, 0x0E46, 1},
  1569  		{0x0E47, 0x0E4E, 1},
  1570  		{0x0E50, 0x0E59, 1},
  1571  		{0x0EB1, 0x0EB1, 1},
  1572  		{0x0EB4, 0x0EB9, 1},
  1573  		{0x0EBB, 0x0EBC, 1},
  1574  		{0x0EC6, 0x0EC6, 1},
  1575  		{0x0EC8, 0x0ECD, 1},
  1576  		{0x0ED0, 0x0ED9, 1},
  1577  		{0x0F18, 0x0F19, 1},
  1578  		{0x0F20, 0x0F29, 1},
  1579  		{0x0F35, 0x0F39, 2},
  1580  		{0x0F3E, 0x0F3F, 1},
  1581  		{0x0F71, 0x0F84, 1},
  1582  		{0x0F86, 0x0F8B, 1},
  1583  		{0x0F90, 0x0F95, 1},
  1584  		{0x0F97, 0x0F97, 1},
  1585  		{0x0F99, 0x0FAD, 1},
  1586  		{0x0FB1, 0x0FB7, 1},
  1587  		{0x0FB9, 0x0FB9, 1},
  1588  		{0x20D0, 0x20DC, 1},
  1589  		{0x20E1, 0x3005, 0x3005 - 0x20E1},
  1590  		{0x302A, 0x302F, 1},
  1591  		{0x3031, 0x3035, 1},
  1592  		{0x3099, 0x309A, 1},
  1593  		{0x309D, 0x309E, 1},
  1594  		{0x30FC, 0x30FE, 1},
  1595  	},
  1596  }
  1597  
  1598  // HTMLEntity is an entity map containing translations for the
  1599  // standard HTML entity characters.
  1600  //
  1601  // See the Decoder.Strict and Decoder.Entity fields' documentation.
  1602  var HTMLEntity map[string]string = htmlEntity
  1603  
  1604  var htmlEntity = map[string]string{
  1605  	/*
  1606  		hget http://www.w3.org/TR/html4/sgml/entities.html |
  1607  		ssam '
  1608  			,y /\&gt;/ x/\&lt;(.|\n)+/ s/\n/ /g
  1609  			,x v/^\&lt;!ENTITY/d
  1610  			,s/\&lt;!ENTITY ([^ ]+) .*U\+([0-9A-F][0-9A-F][0-9A-F][0-9A-F]) .+/	"\1": "\\u\2",/g
  1611  		'
  1612  	*/
  1613  	"nbsp":     "\u00A0",
  1614  	"iexcl":    "\u00A1",
  1615  	"cent":     "\u00A2",
  1616  	"pound":    "\u00A3",
  1617  	"curren":   "\u00A4",
  1618  	"yen":      "\u00A5",
  1619  	"brvbar":   "\u00A6",
  1620  	"sect":     "\u00A7",
  1621  	"uml":      "\u00A8",
  1622  	"copy":     "\u00A9",
  1623  	"ordf":     "\u00AA",
  1624  	"laquo":    "\u00AB",
  1625  	"not":      "\u00AC",
  1626  	"shy":      "\u00AD",
  1627  	"reg":      "\u00AE",
  1628  	"macr":     "\u00AF",
  1629  	"deg":      "\u00B0",
  1630  	"plusmn":   "\u00B1",
  1631  	"sup2":     "\u00B2",
  1632  	"sup3":     "\u00B3",
  1633  	"acute":    "\u00B4",
  1634  	"micro":    "\u00B5",
  1635  	"para":     "\u00B6",
  1636  	"middot":   "\u00B7",
  1637  	"cedil":    "\u00B8",
  1638  	"sup1":     "\u00B9",
  1639  	"ordm":     "\u00BA",
  1640  	"raquo":    "\u00BB",
  1641  	"frac14":   "\u00BC",
  1642  	"frac12":   "\u00BD",
  1643  	"frac34":   "\u00BE",
  1644  	"iquest":   "\u00BF",
  1645  	"Agrave":   "\u00C0",
  1646  	"Aacute":   "\u00C1",
  1647  	"Acirc":    "\u00C2",
  1648  	"Atilde":   "\u00C3",
  1649  	"Auml":     "\u00C4",
  1650  	"Aring":    "\u00C5",
  1651  	"AElig":    "\u00C6",
  1652  	"Ccedil":   "\u00C7",
  1653  	"Egrave":   "\u00C8",
  1654  	"Eacute":   "\u00C9",
  1655  	"Ecirc":    "\u00CA",
  1656  	"Euml":     "\u00CB",
  1657  	"Igrave":   "\u00CC",
  1658  	"Iacute":   "\u00CD",
  1659  	"Icirc":    "\u00CE",
  1660  	"Iuml":     "\u00CF",
  1661  	"ETH":      "\u00D0",
  1662  	"Ntilde":   "\u00D1",
  1663  	"Ograve":   "\u00D2",
  1664  	"Oacute":   "\u00D3",
  1665  	"Ocirc":    "\u00D4",
  1666  	"Otilde":   "\u00D5",
  1667  	"Ouml":     "\u00D6",
  1668  	"times":    "\u00D7",
  1669  	"Oslash":   "\u00D8",
  1670  	"Ugrave":   "\u00D9",
  1671  	"Uacute":   "\u00DA",
  1672  	"Ucirc":    "\u00DB",
  1673  	"Uuml":     "\u00DC",
  1674  	"Yacute":   "\u00DD",
  1675  	"THORN":    "\u00DE",
  1676  	"szlig":    "\u00DF",
  1677  	"agrave":   "\u00E0",
  1678  	"aacute":   "\u00E1",
  1679  	"acirc":    "\u00E2",
  1680  	"atilde":   "\u00E3",
  1681  	"auml":     "\u00E4",
  1682  	"aring":    "\u00E5",
  1683  	"aelig":    "\u00E6",
  1684  	"ccedil":   "\u00E7",
  1685  	"egrave":   "\u00E8",
  1686  	"eacute":   "\u00E9",
  1687  	"ecirc":    "\u00EA",
  1688  	"euml":     "\u00EB",
  1689  	"igrave":   "\u00EC",
  1690  	"iacute":   "\u00ED",
  1691  	"icirc":    "\u00EE",
  1692  	"iuml":     "\u00EF",
  1693  	"eth":      "\u00F0",
  1694  	"ntilde":   "\u00F1",
  1695  	"ograve":   "\u00F2",
  1696  	"oacute":   "\u00F3",
  1697  	"ocirc":    "\u00F4",
  1698  	"otilde":   "\u00F5",
  1699  	"ouml":     "\u00F6",
  1700  	"divide":   "\u00F7",
  1701  	"oslash":   "\u00F8",
  1702  	"ugrave":   "\u00F9",
  1703  	"uacute":   "\u00FA",
  1704  	"ucirc":    "\u00FB",
  1705  	"uuml":     "\u00FC",
  1706  	"yacute":   "\u00FD",
  1707  	"thorn":    "\u00FE",
  1708  	"yuml":     "\u00FF",
  1709  	"fnof":     "\u0192",
  1710  	"Alpha":    "\u0391",
  1711  	"Beta":     "\u0392",
  1712  	"Gamma":    "\u0393",
  1713  	"Delta":    "\u0394",
  1714  	"Epsilon":  "\u0395",
  1715  	"Zeta":     "\u0396",
  1716  	"Eta":      "\u0397",
  1717  	"Theta":    "\u0398",
  1718  	"Iota":     "\u0399",
  1719  	"Kappa":    "\u039A",
  1720  	"Lambda":   "\u039B",
  1721  	"Mu":       "\u039C",
  1722  	"Nu":       "\u039D",
  1723  	"Xi":       "\u039E",
  1724  	"Omicron":  "\u039F",
  1725  	"Pi":       "\u03A0",
  1726  	"Rho":      "\u03A1",
  1727  	"Sigma":    "\u03A3",
  1728  	"Tau":      "\u03A4",
  1729  	"Upsilon":  "\u03A5",
  1730  	"Phi":      "\u03A6",
  1731  	"Chi":      "\u03A7",
  1732  	"Psi":      "\u03A8",
  1733  	"Omega":    "\u03A9",
  1734  	"alpha":    "\u03B1",
  1735  	"beta":     "\u03B2",
  1736  	"gamma":    "\u03B3",
  1737  	"delta":    "\u03B4",
  1738  	"epsilon":  "\u03B5",
  1739  	"zeta":     "\u03B6",
  1740  	"eta":      "\u03B7",
  1741  	"theta":    "\u03B8",
  1742  	"iota":     "\u03B9",
  1743  	"kappa":    "\u03BA",
  1744  	"lambda":   "\u03BB",
  1745  	"mu":       "\u03BC",
  1746  	"nu":       "\u03BD",
  1747  	"xi":       "\u03BE",
  1748  	"omicron":  "\u03BF",
  1749  	"pi":       "\u03C0",
  1750  	"rho":      "\u03C1",
  1751  	"sigmaf":   "\u03C2",
  1752  	"sigma":    "\u03C3",
  1753  	"tau":      "\u03C4",
  1754  	"upsilon":  "\u03C5",
  1755  	"phi":      "\u03C6",
  1756  	"chi":      "\u03C7",
  1757  	"psi":      "\u03C8",
  1758  	"omega":    "\u03C9",
  1759  	"thetasym": "\u03D1",
  1760  	"upsih":    "\u03D2",
  1761  	"piv":      "\u03D6",
  1762  	"bull":     "\u2022",
  1763  	"hellip":   "\u2026",
  1764  	"prime":    "\u2032",
  1765  	"Prime":    "\u2033",
  1766  	"oline":    "\u203E",
  1767  	"frasl":    "\u2044",
  1768  	"weierp":   "\u2118",
  1769  	"image":    "\u2111",
  1770  	"real":     "\u211C",
  1771  	"trade":    "\u2122",
  1772  	"alefsym":  "\u2135",
  1773  	"larr":     "\u2190",
  1774  	"uarr":     "\u2191",
  1775  	"rarr":     "\u2192",
  1776  	"darr":     "\u2193",
  1777  	"harr":     "\u2194",
  1778  	"crarr":    "\u21B5",
  1779  	"lArr":     "\u21D0",
  1780  	"uArr":     "\u21D1",
  1781  	"rArr":     "\u21D2",
  1782  	"dArr":     "\u21D3",
  1783  	"hArr":     "\u21D4",
  1784  	"forall":   "\u2200",
  1785  	"part":     "\u2202",
  1786  	"exist":    "\u2203",
  1787  	"empty":    "\u2205",
  1788  	"nabla":    "\u2207",
  1789  	"isin":     "\u2208",
  1790  	"notin":    "\u2209",
  1791  	"ni":       "\u220B",
  1792  	"prod":     "\u220F",
  1793  	"sum":      "\u2211",
  1794  	"minus":    "\u2212",
  1795  	"lowast":   "\u2217",
  1796  	"radic":    "\u221A",
  1797  	"prop":     "\u221D",
  1798  	"infin":    "\u221E",
  1799  	"ang":      "\u2220",
  1800  	"and":      "\u2227",
  1801  	"or":       "\u2228",
  1802  	"cap":      "\u2229",
  1803  	"cup":      "\u222A",
  1804  	"int":      "\u222B",
  1805  	"there4":   "\u2234",
  1806  	"sim":      "\u223C",
  1807  	"cong":     "\u2245",
  1808  	"asymp":    "\u2248",
  1809  	"ne":       "\u2260",
  1810  	"equiv":    "\u2261",
  1811  	"le":       "\u2264",
  1812  	"ge":       "\u2265",
  1813  	"sub":      "\u2282",
  1814  	"sup":      "\u2283",
  1815  	"nsub":     "\u2284",
  1816  	"sube":     "\u2286",
  1817  	"supe":     "\u2287",
  1818  	"oplus":    "\u2295",
  1819  	"otimes":   "\u2297",
  1820  	"perp":     "\u22A5",
  1821  	"sdot":     "\u22C5",
  1822  	"lceil":    "\u2308",
  1823  	"rceil":    "\u2309",
  1824  	"lfloor":   "\u230A",
  1825  	"rfloor":   "\u230B",
  1826  	"lang":     "\u2329",
  1827  	"rang":     "\u232A",
  1828  	"loz":      "\u25CA",
  1829  	"spades":   "\u2660",
  1830  	"clubs":    "\u2663",
  1831  	"hearts":   "\u2665",
  1832  	"diams":    "\u2666",
  1833  	"quot":     "\u0022",
  1834  	"amp":      "\u0026",
  1835  	"lt":       "\u003C",
  1836  	"gt":       "\u003E",
  1837  	"OElig":    "\u0152",
  1838  	"oelig":    "\u0153",
  1839  	"Scaron":   "\u0160",
  1840  	"scaron":   "\u0161",
  1841  	"Yuml":     "\u0178",
  1842  	"circ":     "\u02C6",
  1843  	"tilde":    "\u02DC",
  1844  	"ensp":     "\u2002",
  1845  	"emsp":     "\u2003",
  1846  	"thinsp":   "\u2009",
  1847  	"zwnj":     "\u200C",
  1848  	"zwj":      "\u200D",
  1849  	"lrm":      "\u200E",
  1850  	"rlm":      "\u200F",
  1851  	"ndash":    "\u2013",
  1852  	"mdash":    "\u2014",
  1853  	"lsquo":    "\u2018",
  1854  	"rsquo":    "\u2019",
  1855  	"sbquo":    "\u201A",
  1856  	"ldquo":    "\u201C",
  1857  	"rdquo":    "\u201D",
  1858  	"bdquo":    "\u201E",
  1859  	"dagger":   "\u2020",
  1860  	"Dagger":   "\u2021",
  1861  	"permil":   "\u2030",
  1862  	"lsaquo":   "\u2039",
  1863  	"rsaquo":   "\u203A",
  1864  	"euro":     "\u20AC",
  1865  }
  1866  
  1867  // HTMLAutoClose is the set of HTML elements that
  1868  // should be considered to close automatically.
  1869  //
  1870  // See the Decoder.Strict and Decoder.Entity fields' documentation.
  1871  var HTMLAutoClose []string = htmlAutoClose
  1872  
  1873  var htmlAutoClose = []string{
  1874  	/*
  1875  		hget http://www.w3.org/TR/html4/loose.dtd |
  1876  		9 sed -n 's/<!ELEMENT ([^ ]*) +- O EMPTY.+/	"\1",/p' | tr A-Z a-z
  1877  	*/
  1878  	"basefont",
  1879  	"br",
  1880  	"area",
  1881  	"link",
  1882  	"img",
  1883  	"param",
  1884  	"hr",
  1885  	"input",
  1886  	"col",
  1887  	"frame",
  1888  	"isindex",
  1889  	"base",
  1890  	"meta",
  1891  }
  1892  
  1893  var (
  1894  	escQuot = []byte("&#34;") // shorter than "&quot;"
  1895  	escApos = []byte("&#39;") // shorter than "&apos;"
  1896  	escAmp  = []byte("&amp;")
  1897  	escLT   = []byte("&lt;")
  1898  	escGT   = []byte("&gt;")
  1899  	escTab  = []byte("&#x9;")
  1900  	escNL   = []byte("&#xA;")
  1901  	escCR   = []byte("&#xD;")
  1902  	escFFFD = []byte("\uFFFD") // Unicode replacement character
  1903  )
  1904  
  1905  // EscapeText writes to w the properly escaped XML equivalent
  1906  // of the plain text data s.
  1907  func EscapeText(w io.Writer, s []byte) error {
  1908  	return escapeText(w, s, true)
  1909  }
  1910  
  1911  // escapeText writes to w the properly escaped XML equivalent
  1912  // of the plain text data s. If escapeNewline is true, newline
  1913  // characters will be escaped.
  1914  func escapeText(w io.Writer, s []byte, escapeNewline bool) error {
  1915  	var esc []byte
  1916  	last := 0
  1917  	for i := 0; i < len(s); {
  1918  		r, width := utf8.DecodeRune(s[i:])
  1919  		i += width
  1920  		switch r {
  1921  		case '"':
  1922  			esc = escQuot
  1923  		case '\'':
  1924  			esc = escApos
  1925  		case '&':
  1926  			esc = escAmp
  1927  		case '<':
  1928  			esc = escLT
  1929  		case '>':
  1930  			esc = escGT
  1931  		case '\t':
  1932  			esc = escTab
  1933  		case '\n':
  1934  			if !escapeNewline {
  1935  				continue
  1936  			}
  1937  			esc = escNL
  1938  		case '\r':
  1939  			esc = escCR
  1940  		default:
  1941  			if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
  1942  				esc = escFFFD
  1943  				break
  1944  			}
  1945  			continue
  1946  		}
  1947  		if _, err := w.Write(s[last : i-width]); err != nil {
  1948  			return err
  1949  		}
  1950  		if _, err := w.Write(esc); err != nil {
  1951  			return err
  1952  		}
  1953  		last = i
  1954  	}
  1955  	_, err := w.Write(s[last:])
  1956  	return err
  1957  }
  1958  
  1959  // EscapeString writes to p the properly escaped XML equivalent
  1960  // of the plain text data s.
  1961  func (p *printer) EscapeString(s string) {
  1962  	var esc []byte
  1963  	last := 0
  1964  	for i := 0; i < len(s); {
  1965  		r, width := utf8.DecodeRuneInString(s[i:])
  1966  		i += width
  1967  		switch r {
  1968  		case '"':
  1969  			esc = escQuot
  1970  		case '\'':
  1971  			esc = escApos
  1972  		case '&':
  1973  			esc = escAmp
  1974  		case '<':
  1975  			esc = escLT
  1976  		case '>':
  1977  			esc = escGT
  1978  		case '\t':
  1979  			esc = escTab
  1980  		case '\n':
  1981  			esc = escNL
  1982  		case '\r':
  1983  			esc = escCR
  1984  		default:
  1985  			if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
  1986  				esc = escFFFD
  1987  				break
  1988  			}
  1989  			continue
  1990  		}
  1991  		p.WriteString(s[last : i-width])
  1992  		p.Write(esc)
  1993  		last = i
  1994  	}
  1995  	p.WriteString(s[last:])
  1996  }
  1997  
  1998  // Escape is like EscapeText but omits the error return value.
  1999  // It is provided for backwards compatibility with Go 1.0.
  2000  // Code targeting Go 1.1 or later should use EscapeText.
  2001  func Escape(w io.Writer, s []byte) {
  2002  	EscapeText(w, s)
  2003  }
  2004  
  2005  var (
  2006  	cdataStart  = []byte("<![CDATA[")
  2007  	cdataEnd    = []byte("]]>")
  2008  	cdataEscape = []byte("]]]]><![CDATA[>")
  2009  )
  2010  
  2011  // emitCDATA writes to w the CDATA-wrapped plain text data s.
  2012  // It escapes CDATA directives nested in s.
  2013  func emitCDATA(w io.Writer, s []byte) error {
  2014  	if len(s) == 0 {
  2015  		return nil
  2016  	}
  2017  	if _, err := w.Write(cdataStart); err != nil {
  2018  		return err
  2019  	}
  2020  
  2021  	for {
  2022  		before, after, ok := bytes.Cut(s, cdataEnd)
  2023  		if !ok {
  2024  			break
  2025  		}
  2026  		// Found a nested CDATA directive end.
  2027  		if _, err := w.Write(before); err != nil {
  2028  			return err
  2029  		}
  2030  		if _, err := w.Write(cdataEscape); err != nil {
  2031  			return err
  2032  		}
  2033  		s = after
  2034  	}
  2035  
  2036  	if _, err := w.Write(s); err != nil {
  2037  		return err
  2038  	}
  2039  
  2040  	_, err := w.Write(cdataEnd)
  2041  	return err
  2042  }
  2043  
  2044  // procInst parses the `param="..."` or `param='...'`
  2045  // value out of the provided string, returning "" if not found.
  2046  func procInst(param, s string) string {
  2047  	// TODO: this parsing is somewhat lame and not exact.
  2048  	// It works for all actual cases, though.
  2049  	param = param + "="
  2050  	_, v, _ := strings.Cut(s, param)
  2051  	if v == "" {
  2052  		return ""
  2053  	}
  2054  	if v[0] != '\'' && v[0] != '"' {
  2055  		return ""
  2056  	}
  2057  	unquote, _, ok := strings.Cut(v[1:], v[:1])
  2058  	if !ok {
  2059  		return ""
  2060  	}
  2061  	return unquote
  2062  }
  2063  

View as plain text