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