github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/encoding/xml/xml.go (about)

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