1 ;;; xml.el --- XML parser
3 ;; Copyright (C) 2000-2012 Free Software Foundation, Inc.
5 ;; Author: Emmanuel Briot <briot@gnat.com>
6 ;; Maintainer: Mark A. Hershberger <mah@everybody.org>
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; This file contains a somewhat incomplete non-validating XML parser. It
27 ;; parses a file, and returns a list that can be used internally by
28 ;; any other Lisp libraries.
32 ;; The document type declaration may either be ignored or (optionally)
33 ;; parsed, but currently the parsing will only accept element
34 ;; declarations. The XML file is assumed to be well-formed. In case
35 ;; of error, the parsing stops and the XML file is shown where the
38 ;; It also knows how to ignore comments and processing instructions.
40 ;; The XML file should have the following format:
41 ;; <node1 attr1="name1" attr2="name2" ...>value
42 ;; <node2 attr3="name3" attr4="name4">value2</node2>
43 ;; <node3 attr5="name5" attr6="name6">value3</node3>
45 ;; Of course, the name of the nodes and attributes can be anything. There can
46 ;; be any number of attributes (or none), as well as any number of children
49 ;; There can be only top level node, but with any number of children below.
53 ;; The functions `xml-parse-file', `xml-parse-region' and
54 ;; `xml-parse-tag' return a list with the following format:
56 ;; xml-list ::= (node node ...)
57 ;; node ::= (qname attribute-list . child_node_list)
58 ;; child_node_list ::= child_node child_node ...
59 ;; child_node ::= node | string
60 ;; qname ::= (:namespace-uri . "name") | "name"
61 ;; attribute_list ::= ((qname . "value") (qname . "value") ...)
65 ;; Some macros are provided to ease the parsing of this list.
66 ;; Whitespace is preserved. Fixme: There should be a tree-walker that
70 ;; * xml:base, xml:space support
71 ;; * more complete DOCTYPE parsing
76 ;; Note that buffer-substring and match-string were formerly used in
77 ;; several places, because the -no-properties variants remove
78 ;; composition info. However, after some discussion on emacs-devel,
79 ;; the consensus was that the speed of the -no-properties variants was
80 ;; a worthwhile tradeoff especially since we're usually parsing files
81 ;; instead of hand-crafted XML.
83 ;;; Macros to parse the list
85 (defconst xml-undefined-entity
"?"
86 "What to substitute for undefined entities")
88 (defconst xml-default-ns
'(("" .
"")
89 ("xml" .
"http://www.w3.org/XML/1998/namespace")
90 ("xmlns" .
"http://www.w3.org/2000/xmlns/"))
91 "Alist mapping default XML namespaces to their URIs.")
93 (defvar xml-entity-alist
99 "Alist mapping XML entities to their replacement text.")
101 (defvar xml-entity-expansion-limit
20000
102 "The maximum size of entity reference expansions.
103 If the size of the buffer increases by this many characters while
104 expanding entity references in a segment of character data, the
105 XML parser signals an error. Setting this to nil removes the
106 limit (making the parser vulnerable to XML bombs).")
108 (defvar xml-parameter-entity-alist nil
109 "Alist of defined XML parametric entities.")
111 (defvar xml-sub-parser nil
112 "Non-nil when the XML parser is parsing an XML fragment.")
114 (defvar xml-validating-parser nil
115 "Set to non-nil to get validity checking.")
117 (defsubst xml-node-name
(node)
118 "Return the tag associated with NODE.
119 Without namespace-aware parsing, the tag is a symbol.
121 With namespace-aware parsing, the tag is a cons of a string
122 representing the uri of the namespace with the local name of the
127 would be represented by
133 (defsubst xml-node-attributes
(node)
134 "Return the list of attributes of NODE.
135 The list can be nil."
138 (defsubst xml-node-children
(node)
139 "Return the list of children of NODE.
140 This is a list of nodes, and it can be nil."
143 (defun xml-get-children (node child-name
)
144 "Return the children of NODE whose tag is CHILD-NAME.
145 CHILD-NAME should match the value returned by `xml-node-name'."
147 (dolist (child (xml-node-children node
))
148 (if (and (listp child
)
149 (equal (xml-node-name child
) child-name
))
153 (defun xml-get-attribute-or-nil (node attribute
)
154 "Get from NODE the value of ATTRIBUTE.
155 Return nil if the attribute was not found.
157 See also `xml-get-attribute'."
158 (cdr (assoc attribute
(xml-node-attributes node
))))
160 (defsubst xml-get-attribute
(node attribute
)
161 "Get from NODE the value of ATTRIBUTE.
162 An empty string is returned if the attribute was not found.
164 See also `xml-get-attribute-or-nil'."
165 (or (xml-get-attribute-or-nil node attribute
) ""))
167 ;;; Regular expressions for XML components
169 ;; The following regexps are used as subexpressions in regexps that
170 ;; are `eval-when-compile'd for efficiency, so they must be defined at
175 ;; See the definition of word syntax in `xml-syntax-table'.
176 (defconst xml-name-start-char-re
(concat "[[:word:]:_]"))
178 ;; [4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7
179 ;; | [#x0300-#x036F] | [#x203F-#x2040]
180 (defconst xml-name-char-re
(concat "[-0-9.[:word:]:_·̀-ͯ‿-⁀]"))
182 ;; [5] Name ::= NameStartChar (NameChar)*
183 (defconst xml-name-re
(concat xml-name-start-char-re xml-name-char-re
"*"))
185 ;; [6] Names ::= Name (#x20 Name)*
186 (defconst xml-names-re
(concat xml-name-re
"\\(?: " xml-name-re
"\\)*"))
188 ;; [7] Nmtoken ::= (NameChar)+
189 (defconst xml-nmtoken-re
(concat xml-name-char-re
"+"))
191 ;; [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*
192 (defconst xml-nmtokens-re
(concat xml-nmtoken-re
"\\(?: " xml-name-re
"\\)*"))
194 ;; [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
195 (defconst xml-char-ref-re
"\\(?:&#[0-9]+;\\|&#x[0-9a-fA-F]+;\\)")
197 ;; [68] EntityRef ::= '&' Name ';'
198 (defconst xml-entity-ref
(concat "&" xml-name-re
";"))
200 (defconst xml-entity-or-char-ref-re
(concat "&\\(?:#\\(x\\)?\\([0-9]+\\)\\|\\("
201 xml-name-re
"\\)\\);"))
203 ;; [69] PEReference ::= '%' Name ';'
204 (defconst xml-pe-reference-re
(concat "%\\(" xml-name-re
"\\);"))
206 ;; [67] Reference ::= EntityRef | CharRef
207 (defconst xml-reference-re
(concat "\\(?:" xml-entity-ref
"\\|" xml-char-ref-re
"\\)"))
209 ;; [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
210 ;; | "'" ([^<&'] | Reference)* "'"
211 (defconst xml-att-value-re
(concat "\\(?:\"\\(?:[^&\"]\\|"
212 xml-reference-re
"\\)*\"\\|"
213 "'\\(?:[^&']\\|" xml-reference-re
216 ;; [56] TokenizedType ::= 'ID'
217 ;; [VC: ID] [VC: One ID / Element Type] [VC: ID Attribute Default]
218 ;; | 'IDREF' [VC: IDREF]
219 ;; | 'IDREFS' [VC: IDREF]
220 ;; | 'ENTITY' [VC: Entity Name]
221 ;; | 'ENTITIES' [VC: Entity Name]
222 ;; | 'NMTOKEN' [VC: Name Token]
223 ;; | 'NMTOKENS' [VC: Name Token]
224 (defconst xml-tokenized-type-re
(concat "\\(?:ID\\|IDREF\\|IDREFS\\|ENTITY\\|"
225 "ENTITIES\\|NMTOKEN\\|NMTOKENS\\)"))
227 ;; [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
228 (defconst xml-notation-type-re
229 (concat "\\(?:NOTATION\\s-+(\\s-*" xml-name-re
230 "\\(?:\\s-*|\\s-*" xml-name-re
"\\)*\\s-*)\\)"))
232 ;; [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
233 ;; [VC: Enumeration] [VC: No Duplicate Tokens]
234 (defconst xml-enumeration-re
(concat "\\(?:(\\s-*" xml-nmtoken-re
235 "\\(?:\\s-*|\\s-*" xml-nmtoken-re
238 ;; [57] EnumeratedType ::= NotationType | Enumeration
239 (defconst xml-enumerated-type-re
(concat "\\(?:" xml-notation-type-re
240 "\\|" xml-enumeration-re
"\\)"))
242 ;; [54] AttType ::= StringType | TokenizedType | EnumeratedType
243 ;; [55] StringType ::= 'CDATA'
244 (defconst xml-att-type-re
(concat "\\(?:CDATA\\|" xml-tokenized-type-re
245 "\\|" xml-notation-type-re
246 "\\|" xml-enumerated-type-re
"\\)"))
248 ;; [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
249 (defconst xml-default-decl-re
(concat "\\(?:#REQUIRED\\|#IMPLIED\\|"
250 "\\(?:#FIXED\\s-+\\)*"
251 xml-att-value-re
"\\)"))
253 ;; [53] AttDef ::= S Name S AttType S DefaultDecl
254 (defconst xml-att-def-re
(concat "\\(?:\\s-*" xml-name-re
255 "\\s-*" xml-att-type-re
256 "\\s-*" xml-default-decl-re
"\\)"))
258 ;; [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
259 ;; | "'" ([^%&'] | PEReference | Reference)* "'"
260 (defconst xml-entity-value-re
(concat "\\(?:\"\\(?:[^%&\"]\\|"
262 "\\|" xml-reference-re
263 "\\)*\"\\|'\\(?:[^%&']\\|"
264 xml-pe-reference-re
"\\|"
265 xml-reference-re
"\\)*'\\)"))
266 ) ; End of `eval-when-compile'
269 ;; [75] ExternalID ::= 'SYSTEM' S SystemLiteral
270 ;; | 'PUBLIC' S PubidLiteral S SystemLiteral
271 ;; [76] NDataDecl ::= S 'NDATA' S
272 ;; [73] EntityDef ::= EntityValue| (ExternalID NDataDecl?)
273 ;; [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
274 ;; [74] PEDef ::= EntityValue | ExternalID
275 ;; [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
276 ;; [70] EntityDecl ::= GEDecl | PEDecl
278 ;; Note that this is setup so that we can do whitespace-skipping with
279 ;; `(skip-syntax-forward " ")', inter alia. Previously this was slow
280 ;; compared with `re-search-forward', but that has been fixed.
282 (defvar xml-syntax-table
283 ;; By default, characters have symbol syntax.
284 (let ((table (make-char-table 'syntax-table
'(3))))
285 ;; The XML space chars [3], and nothing else, have space syntax.
286 (dolist (c '(?\s ?
\t ?
\r ?
\n))
287 (modify-syntax-entry c
" " table
))
288 ;; The characters in NameStartChar [4], aside from ':' and '_',
289 ;; have word syntax. This is used by `xml-name-start-char-re'.
290 (modify-syntax-entry '(?A . ?Z
) "w" table
)
291 (modify-syntax-entry '(?a . ?z
) "w" table
)
292 (modify-syntax-entry '(#xC0 .
#xD6
) "w" table
)
293 (modify-syntax-entry '(#xD8 .
#XF6
) "w" table
)
294 (modify-syntax-entry '(#xF8 .
#X2FF
) "w" table
)
295 (modify-syntax-entry '(#x370 .
#X37D
) "w" table
)
296 (modify-syntax-entry '(#x37F .
#x1FFF
) "w" table
)
297 (modify-syntax-entry '(#x200C .
#x200D
) "w" table
)
298 (modify-syntax-entry '(#x2070 .
#x218F
) "w" table
)
299 (modify-syntax-entry '(#x2C00 .
#x2FEF
) "w" table
)
300 (modify-syntax-entry '(#x3001 .
#xD7FF
) "w" table
)
301 (modify-syntax-entry '(#xF900 .
#xFDCF
) "w" table
)
302 (modify-syntax-entry '(#xFDF0 .
#xFFFD
) "w" table
)
303 (modify-syntax-entry '(#x10000 .
#xEFFFF
) "w" table
)
305 "Syntax table used by the XML parser.
306 In this syntax table, the XML space characters [ \\t\\r\\n], and
307 only those characters, have whitespace syntax.")
312 (defun xml-parse-file (file &optional parse-dtd parse-ns
)
313 "Parse the well-formed XML file FILE.
314 Return the top node with all its children.
315 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped.
316 If PARSE-NS is non-nil, then QNAMES are expanded."
318 (insert-file-contents file
)
319 (xml--parse-buffer parse-dtd parse-ns
)))
322 (defun xml-parse-region (&optional beg end buffer parse-dtd parse-ns
)
323 "Parse the region from BEG to END in BUFFER.
324 Return the XML parse tree, or raise an error if the region does
325 not contain well-formed XML.
327 If BEG is nil, it defaults to `point-min'.
328 If END is nil, it defaults to `point-max'.
329 If BUFFER is nil, it defaults to the current buffer.
330 If PARSE-DTD is non-nil, parse the DTD and return it as the first
332 If PARSE-NS is non-nil, expand QNAMES."
333 ;; Use fixed syntax table to ensure regexp char classes and syntax
336 (setq buffer
(current-buffer)))
338 (insert-buffer-substring-no-properties buffer beg end
)
339 (xml--parse-buffer parse-dtd parse-ns
)))
343 ;; Fixme: This needs re-writing to deal with the XML grammar properly, i.e.
344 ;; document ::= prolog element Misc*
345 ;; prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
347 (defun xml--parse-buffer (parse-dtd parse-ns
)
348 (with-syntax-table xml-syntax-table
349 (let ((case-fold-search nil
) ; XML is case-sensitive.
350 ;; Prevent entity definitions from changing the defaults
351 (xml-entity-alist xml-entity-alist
)
352 (xml-parameter-entity-alist xml-parameter-entity-alist
)
354 (goto-char (point-min))
356 (if (search-forward "<" nil t
)
359 (setq result
(xml-parse-tag-1 parse-dtd parse-ns
))
362 ;; Not looking at an xml start tag.
365 ((and xml
(not xml-sub-parser
))
366 ;; Translation of rule [1] of XML specifications
367 (error "XML: (Not Well-Formed) Only one root tag allowed"))
368 ((and (listp (car result
))
370 (setq dtd
(car result
))
371 (if (cdr result
) ; possible leading comment
372 (add-to-list 'xml
(cdr result
))))
374 (add-to-list 'xml result
))))
375 (goto-char (point-max))))
377 (cons dtd
(nreverse xml
))
380 (defun xml-maybe-do-ns (name default xml-ns
)
381 "Perform any namespace expansion.
382 NAME is the name to perform the expansion on.
383 DEFAULT is the default namespace. XML-NS is a cons of namespace
384 names to uris. When namespace-aware parsing is off, then XML-NS
387 During namespace-aware parsing, any name without a namespace is
388 put into the namespace identified by DEFAULT. nil is used to
389 specify that the name shouldn't be given a namespace."
391 (let* ((nsp (string-match ":" name
))
392 (lname (if nsp
(substring name
(match-end 0)) name
))
393 (prefix (if nsp
(substring name
0 (match-beginning 0)) default
))
394 (special (and (string-equal lname
"xmlns") (not prefix
)))
395 ;; Setting default to nil will insure that there is not
396 ;; matching cons in xml-ns. In which case we
397 (ns (or (cdr (assoc (if special
"xmlns" prefix
)
400 (cons ns
(if special
"" lname
)))
403 (defun xml-parse-tag (&optional parse-dtd parse-ns
)
404 "Parse the tag at point.
405 If PARSE-DTD is non-nil, the DTD of the document, if any, is parsed and
406 returned as the first element in the list.
407 If PARSE-NS is non-nil, expand QNAMES; if the value of PARSE-NS
408 is a list, use it as an alist mapping namespaces to URIs.
411 - a list : the matching node
412 - nil : the point is not looking at a tag.
413 - a pair : the first element is the DTD, the second is the node."
414 (let* ((case-fold-search nil
)
415 ;; Prevent entity definitions from changing the defaults
416 (xml-entity-alist xml-entity-alist
)
417 (xml-parameter-entity-alist xml-parameter-entity-alist
)
418 (buf (current-buffer))
421 (with-syntax-table xml-syntax-table
422 (insert-buffer-substring-no-properties buf pos
)
423 (goto-char (point-min))
424 (xml-parse-tag-1 parse-dtd parse-ns
)))))
426 (defun xml-parse-tag-1 (&optional parse-dtd parse-ns
)
427 "Like `xml-parse-tag', but possibly modify the buffer while working."
428 (let ((xml-validating-parser (or parse-dtd xml-validating-parser
))
429 (xml-ns (cond ((consp parse-ns
) parse-ns
)
430 (parse-ns xml-default-ns
))))
432 ;; Processing instructions, like <?xml version="1.0"?>.
434 (search-forward "?>")
435 (skip-syntax-forward " ")
436 (xml-parse-tag-1 parse-dtd xml-ns
))
437 ;; Character data (CDATA) sections, in which no tag should be interpreted
438 ((looking-at "<!\\[CDATA\\[")
439 (let ((pos (match-end 0)))
440 (unless (search-forward "]]>" nil t
)
441 (error "XML: (Not Well Formed) CDATA section does not end anywhere in the document"))
443 (buffer-substring-no-properties pos
(match-beginning 0))
444 (xml-parse-string))))
445 ;; DTD for the document
446 ((looking-at "<!DOCTYPE[ \t\n\r]")
447 (let ((dtd (xml-parse-dtd parse-ns
)))
448 (skip-syntax-forward " ")
449 (if xml-validating-parser
450 (cons dtd
(xml-parse-tag-1 nil xml-ns
))
451 (xml-parse-tag-1 nil xml-ns
))))
454 (search-forward "-->")
455 ;; FIXME: This loses the skipped-over spaces.
456 (skip-syntax-forward " ")
458 (let ((xml-sub-parser t
))
459 (xml-parse-tag-1 parse-dtd xml-ns
))))
464 ((looking-at (eval-when-compile (concat "<\\(" xml-name-re
"\\)")))
465 (goto-char (match-end 1))
467 (let* ((node-name (match-string-no-properties 1))
468 ;; Parse the attribute list.
469 (attrs (xml-parse-attlist xml-ns
))
471 ;; add the xmlns:* attrs to our cache
474 (when (and (consp (car attr
))
475 (equal "http://www.w3.org/2000/xmlns/"
477 (push (cons (cdar attr
) (cdr attr
))
479 (setq children
(list attrs
(xml-maybe-do-ns node-name
"" xml-ns
)))
481 ;; is this an empty element ?
485 ;; is this a valid start tag ?
486 ((eq (char-after) ?
>)
488 ;; Now check that we have the right end-tag.
489 (let ((end (concat "</" node-name
"\\s-*>")))
490 (while (not (looking-at end
))
493 (error "XML: (Not Well-Formed) End of document while reading element `%s'"
497 (error "XML: (Not Well-Formed) Invalid end tag `%s' (expecting `%s')"
499 (buffer-substring pos
(if (re-search-forward "\\s-*>" nil t
)
503 ;; Read a sub-element and push it onto CHILDREN.
505 (let ((tag (xml-parse-tag-1 nil xml-ns
)))
507 (push tag children
))))
508 ;; Read some character data.
510 (let ((expansion (xml-parse-string)))
511 (push (if (stringp (car children
))
512 ;; If two strings were separated by a
513 ;; comment, concat them.
514 (concat (pop children
) expansion
)
517 ;; Move point past the end-tag.
518 (goto-char (match-end 0))
519 (nreverse children
)))
520 ;; Otherwise this was an invalid start tag (expected ">" not found.)
522 (error "XML: (Well-Formed) Couldn't parse tag: %s"
523 (buffer-substring-no-properties (- (point) 10) (+ (point) 1)))))))
525 ;; (Not one of PI, CDATA, Comment, End tag, or Start tag)
527 (unless xml-sub-parser
; Usually, we error out.
528 (error "XML: (Well-Formed) Invalid character"))
529 ;; However, if we're parsing incrementally, then we need to deal
531 (xml-parse-string)))))
533 (defun xml-parse-string ()
534 "Parse character data at point, and return it as a string.
535 Leave point at the start of the next thing to parse. This
536 function can modify the buffer by expanding entity and character
538 (let ((start (point))
539 ;; Keep track of the size of the rest of the buffer:
540 (old-remaining-size (- (buffer-size) (point)))
542 (while (and (not (eobp))
543 (not (looking-at "<")))
544 ;; Find the next < or & character.
545 (skip-chars-forward "^<&")
546 (when (eq (char-after) ?
&)
547 ;; If we find an entity or character reference, expand it.
548 (unless (looking-at xml-entity-or-char-ref-re
)
549 (error "XML: (Not Well-Formed) Invalid entity reference"))
550 ;; For a character reference, the next entity or character
551 ;; reference must be after the replacement. [4.6] "Numerical
552 ;; character references are expanded immediately when
553 ;; recognized and MUST be treated as character data."
554 (if (setq ref
(match-string 2))
555 (progn ; Numeric char reference
556 (setq val
(save-match-data
557 (decode-char 'ucs
(string-to-number
558 ref
(if (match-string 1) 16)))))
560 xml-validating-parser
561 (error "XML: (Validity) Invalid character reference `%s'"
563 (replace-match (or (string val
) xml-undefined-entity
) t t
))
564 ;; For an entity reference, search again from the start of
565 ;; the replaced text, since the replacement can contain
566 ;; entity or character references, or markup.
567 (setq ref
(match-string 3)
568 val
(assoc ref xml-entity-alist
))
570 xml-validating-parser
571 (error "XML: (Validity) Undefined entity `%s'" ref
))
572 (replace-match (cdr val
) t t
)
573 (goto-char (match-beginning 0)))
574 ;; Check for XML bombs.
575 (and xml-entity-expansion-limit
576 (> (- (buffer-size) (point))
577 (+ old-remaining-size xml-entity-expansion-limit
))
578 (error "XML: Entity reference expansion \
579 surpassed `xml-entity-expansion-limit'"))))
580 ;; [2.11] Clean up line breaks.
581 (let ((end-marker (point-marker)))
583 (while (re-search-forward "\r\n?" end-marker t
)
584 (replace-match "\n" t t
))
585 (goto-char end-marker
)
586 (buffer-substring start
(point)))))
588 (defun xml-parse-attlist (&optional xml-ns
)
589 "Return the attribute-list after point.
590 Leave point at the first non-blank character after the tag."
593 (skip-syntax-forward " ")
594 (while (looking-at (eval-when-compile
595 (concat "\\(" xml-name-re
"\\)\\s-*=\\s-*")))
596 (setq end-pos
(match-end 0))
597 (setq name
(xml-maybe-do-ns (match-string-no-properties 1) nil xml-ns
))
600 ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
602 ;; Do we have a string between quotes (or double-quotes),
603 ;; or a simple word ?
604 (if (looking-at "\"\\([^\"]*\\)\"")
605 (setq end-pos
(match-end 0))
606 (if (looking-at "'\\([^']*\\)'")
607 (setq end-pos
(match-end 0))
608 (error "XML: (Not Well-Formed) Attribute values must be given between quotes")))
610 ;; Each attribute must be unique within a given element
611 (if (assoc name attlist
)
612 (error "XML: (Not Well-Formed) Each attribute must be unique within an element"))
614 ;; Multiple whitespace characters should be replaced with a single one
616 (let ((string (match-string-no-properties 1)))
617 (replace-regexp-in-string "\\s-\\{2,\\}" " " string
)
618 (let ((expansion (xml-substitute-special string
)))
619 (unless (stringp expansion
)
620 ;; We say this is the constraint. It is actually that
621 ;; neither external entities nor "<" can be in an
623 (error "XML: (Not Well-Formed) Entities in attributes cannot expand into elements"))
624 (push (cons name expansion
) attlist
)))
627 (skip-syntax-forward " "))
630 ;;; DTD (document type declaration)
632 ;; The following functions know how to skip or parse the DTD of a
633 ;; document. FIXME: it fails at least if the DTD contains conditional
636 (defun xml-skip-dtd ()
637 "Skip the DTD at point.
638 This follows the rule [28] in the XML specifications."
639 (let ((xml-validating-parser nil
))
642 (defun xml-parse-dtd (&optional parse-ns
)
643 "Parse the DTD at point."
644 (forward-char (eval-when-compile (length "<!DOCTYPE")))
645 (skip-syntax-forward " ")
646 (if (and (looking-at ">")
647 xml-validating-parser
)
648 (error "XML: (Validity) Invalid DTD (expecting name of the document)"))
650 ;; Get the name of the document
651 (looking-at xml-name-re
)
652 (let ((dtd (list (match-string-no-properties 0) 'dtd
))
653 (xml-parameter-entity-alist xml-parameter-entity-alist
)
654 next-parameter-entity
)
655 (goto-char (match-end 0))
656 (skip-syntax-forward " ")
658 ;; External subset (XML [75])
659 (cond ((looking-at "PUBLIC\\s-+")
660 (goto-char (match-end 0))
661 (unless (or (re-search-forward
662 "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
665 "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
667 (error "XML: Missing Public ID"))
668 (let ((pubid (match-string-no-properties 1)))
669 (skip-syntax-forward " ")
670 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t
)
671 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t
))
672 (error "XML: Missing System ID"))
673 (push (list pubid
(match-string-no-properties 1) 'public
) dtd
)))
674 ((looking-at "SYSTEM\\s-+")
675 (goto-char (match-end 0))
676 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t
)
677 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t
))
678 (error "XML: Missing System ID"))
679 (push (list (match-string-no-properties 1) 'system
) dtd
)))
680 (skip-syntax-forward " ")
682 (if (eq (char-after) ?
>)
684 ;; No internal subset
687 ;; Internal subset (XML [28b])
688 (unless (eq (char-after) ?\
[)
689 (error "XML: Bad DTD"))
692 ;; [2.8]: "markup declarations may be made up in whole or in
693 ;; part of the replacement text of parameter entities."
695 ;; Since parameter entities are valid only within the DTD, we
696 ;; first search for the position of the next possible parameter
697 ;; entity. Then, search for the next DTD element; if it ends
698 ;; before the next parameter entity, expand the parameter entity
700 (setq next-parameter-entity
702 (if (re-search-forward xml-pe-reference-re nil t
)
703 (match-beginning 0))))
705 ;; Parse the rest of the DTD
706 ;; Fixme: Deal with NOTATION, PIs.
707 (while (not (looking-at "\\s-*\\]"))
708 (skip-syntax-forward " ")
711 (error "XML: (Well-Formed) End of document while reading DTD"))
712 ;; Element declaration [45]:
713 ((and (looking-at (eval-when-compile
714 (concat "<!ELEMENT\\s-+\\(" xml-name-re
715 "\\)\\s-+\\([^>]+\\)>")))
716 (or (null next-parameter-entity
)
717 (<= (match-end 0) next-parameter-entity
)))
718 (let ((element (match-string-no-properties 1))
719 (type (match-string-no-properties 2))
720 (end-pos (match-end 0)))
721 ;; Translation of rule [46] of XML specifications
723 ((string-match "\\`EMPTY\\s-*\\'" type
) ; empty declaration
725 ((string-match "\\`ANY\\s-*$" type
) ; any type of contents
727 ((string-match "\\`(\\(.*\\))\\s-*\\'" type
) ; children ([47])
728 (setq type
(xml-parse-elem-type
729 (match-string-no-properties 1 type
))))
730 ((string-match "^%[^;]+;[ \t\n\r]*\\'" type
) ; substitution
732 (xml-validating-parser
733 (error "XML: (Validity) Invalid element type in the DTD")))
735 ;; rule [45]: the element declaration must be unique
736 (and (assoc element dtd
)
737 xml-validating-parser
738 (error "XML: (Validity) DTD element declarations must be unique (<%s>)"
741 ;; Store the element in the DTD
742 (push (list element type
) dtd
)
743 (goto-char end-pos
)))
745 ;; Attribute-list declaration [52] (currently unsupported):
746 ((and (looking-at (eval-when-compile
747 (concat "<!ATTLIST[ \t\n\r]*\\(" xml-name-re
748 "\\)[ \t\n\r]*\\(" xml-att-def-re
750 (or (null next-parameter-entity
)
751 (<= (match-end 0) next-parameter-entity
)))
752 (goto-char (match-end 0)))
754 ;; Comments (skip to end, ignoring parameter entity):
756 (search-forward "-->")
757 (and next-parameter-entity
758 (> (point) next-parameter-entity
)
759 (setq next-parameter-entity
761 (if (re-search-forward xml-pe-reference-re nil t
)
762 (match-beginning 0))))))
764 ;; Internal entity declarations:
765 ((and (looking-at (eval-when-compile
766 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
767 xml-name-re
"\\)[ \t\n\r]*\\("
768 xml-entity-value-re
"\\)[ \t\n\r]*>")))
769 (or (null next-parameter-entity
)
770 (<= (match-end 0) next-parameter-entity
)))
771 (let* ((name (prog1 (match-string-no-properties 2)
772 (goto-char (match-end 0))))
773 (alist (if (match-string 1)
774 'xml-parameter-entity-alist
776 ;; Retrieve the deplacement text:
777 (value (xml--entity-replacement-text
778 ;; Entity value, sans quotation marks:
779 (substring (match-string-no-properties 3) 1 -
1))))
780 ;; If the same entity is declared more than once, the
781 ;; first declaration is binding.
782 (unless (assoc name
(symbol-value alist
))
783 (set alist
(cons (cons name value
) (symbol-value alist
))))))
785 ;; External entity declarations (currently unsupported):
786 ((and (or (looking-at (eval-when-compile
787 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
788 xml-name-re
"\\)[ \t\n\r]+SYSTEM[ \t\n\r]+"
789 "\\(\"[^\"]*\"\\|'[^']*'\\)[ \t\n\r]*>")))
790 (looking-at (eval-when-compile
791 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
792 xml-name-re
"\\)[ \t\n\r]+PUBLIC[ \t\n\r]+"
793 "\"[- \r\na-zA-Z0-9'()+,./:=?;!*#@$_%]*\""
794 "\\|'[- \r\na-zA-Z0-9()+,./:=?;!*#@$_%]*'"
795 "[ \t\n\r]+\\(\"[^\"]*\"\\|'[^']*'\\)"
797 (or (null next-parameter-entity
)
798 (<= (match-end 0) next-parameter-entity
)))
799 (goto-char (match-end 0)))
801 ;; If a parameter entity is in the way, expand it.
802 (next-parameter-entity
804 (goto-char next-parameter-entity
)
805 (unless (looking-at xml-pe-reference-re
)
806 (error "XML: Internal error"))
807 (let* ((entity (match-string 1))
809 (elt (assoc entity xml-parameter-entity-alist
)))
812 (replace-match (cdr elt
) t t
)
813 ;; The replacement can itself be a parameter entity.
814 (goto-char next-parameter-entity
))
815 (goto-char (match-end 0))))
816 (setq next-parameter-entity
817 (if (re-search-forward xml-pe-reference-re nil t
)
818 (match-beginning 0)))))
820 ;; Anything else is garbage (ignored if not validating).
821 (xml-validating-parser
822 (error "XML: (Validity) Invalid DTD item"))
824 (skip-chars-forward "^]"))))
826 (if (looking-at "\\s-*]>")
827 (goto-char (match-end 0))))
830 (defun xml--entity-replacement-text (string)
831 "Return the replacement text for the entity value STRING.
832 The replacement text is obtained by replacing character
833 references and parameter-entity references."
834 (let ((ref-re (eval-when-compile
835 (concat "\\(?:&#\\([0-9]+\\)\\|&#x\\([0-9a-fA-F]+\\)\\|%\\("
836 xml-name-re
"\\)\\);")))
838 (while (string-match ref-re string
)
839 (push (substring string
0 (match-beginning 0)) children
)
840 (let ((remainder (substring string
(match-end 0)))
842 (cond ((setq ref
(match-string 1 string
))
843 ;; Decimal character reference
844 (setq val
(decode-char 'ucs
(string-to-number ref
)))
845 (if val
(push (string val
) children
)))
846 ;; Hexadecimal character reference
847 ((setq ref
(match-string 2 string
))
848 (setq val
(decode-char 'ucs
(string-to-number ref
16)))
849 (if val
(push (string val
) children
)))
850 ;; Parameter entity reference
851 ((setq ref
(match-string 3 string
))
852 (setq val
(assoc ref xml-parameter-entity-alist
))
854 xml-validating-parser
855 (error "XML: (Validity) Undefined parameter entity `%s'" ref
))
856 (push (or (cdr val
) xml-undefined-entity
) children
)))
857 (setq string remainder
)))
858 (mapconcat 'identity
(nreverse (cons string children
)) "")))
860 (defun xml-parse-elem-type (string)
861 "Convert element type STRING into a Lisp structure."
864 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string
)
866 (setq elem
(match-string-no-properties 1 string
)
867 modifier
(match-string-no-properties 2 string
))
868 (if (string-match "|" elem
)
869 (setq elem
(cons 'choice
870 (mapcar 'xml-parse-elem-type
871 (split-string elem
"|"))))
872 (if (string-match "," elem
)
873 (setq elem
(cons 'seq
874 (mapcar 'xml-parse-elem-type
875 (split-string elem
",")))))))
876 (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string
)
877 (setq elem
(match-string-no-properties 1 string
)
878 modifier
(match-string-no-properties 2 string
))))
880 (if (and (stringp elem
) (string= elem
"#PCDATA"))
884 ((string= modifier
"+")
886 ((string= modifier
"*")
888 ((string= modifier
"?")
893 ;;; Substituting special XML sequences
895 (defun xml-substitute-special (string)
896 "Return STRING, after substituting entity and character references.
897 STRING is assumed to occur in an XML attribute value."
898 (let ((strlen (length string
))
900 (while (string-match xml-entity-or-char-ref-re string
)
901 (push (substring string
0 (match-beginning 0)) children
)
902 (let* ((remainder (substring string
(match-end 0)))
903 (is-hex (match-string 1 string
)) ; Is it a hex numeric reference?
904 (ref (match-string 2 string
))) ; Numeric part of reference
906 ;; [4.6] Character references are included as
908 (let ((val (decode-char 'ucs
(string-to-number ref
(if is-hex
16)))))
909 (push (cond (val (string val
))
910 (xml-validating-parser
911 (error "XML: (Validity) Undefined character `x%s'" ref
))
912 (t xml-undefined-entity
))
914 (setq string remainder
915 strlen
(length string
)))
916 ;; [4.4.5] Entity references are "included in literal".
917 ;; Note that we don't need do anything special to treat
918 ;; quotes as normal data characters.
919 (setq ref
(match-string 3 string
)) ; entity name
920 (let ((val (or (cdr (assoc ref xml-entity-alist
))
921 (if xml-validating-parser
922 (error "XML: (Validity) Undefined entity `%s'" ref
)
923 xml-undefined-entity
))))
924 (setq string
(concat val remainder
)))
925 (and xml-entity-expansion-limit
926 (> (length string
) (+ strlen xml-entity-expansion-limit
))
927 (error "XML: Passed `xml-entity-expansion-limit' while expanding `&%s;'"
929 (mapconcat 'identity
(nreverse (cons string children
)) "")))
931 (defun xml-substitute-numeric-entities (string)
932 "Substitute SGML numeric entities by their respective utf characters.
933 This function replaces numeric entities in the input STRING and
934 returns the modified string. For example \"*\" gets replaced
936 (if (and string
(stringp string
))
938 (while (string-match "&#\\([0-9]+\\);" string start
)
940 (setq string
(replace-match
941 (string (read (substring string
946 (setq start
(1+ (match-beginning 0))))
950 ;;; Printing a parse tree (mainly for debugging).
952 (defun xml-debug-print (xml &optional indent-string
)
953 "Outputs the XML in the current buffer.
954 XML can be a tree or a list of nodes.
955 The first line is indented with the optional INDENT-STRING."
956 (setq indent-string
(or indent-string
""))
958 (xml-debug-print-internal node indent-string
)))
960 (defalias 'xml-print
'xml-debug-print
)
962 (defun xml-escape-string (string)
963 "Return STRING with entity substitutions made from `xml-entity-alist'."
964 (mapconcat (lambda (byte)
965 (let ((char (char-to-string byte
)))
966 (if (rassoc char xml-entity-alist
)
967 (concat "&" (car (rassoc char xml-entity-alist
)) ";")
971 (defun xml-debug-print-internal (xml indent-string
)
972 "Outputs the XML tree in the current buffer.
973 The first line is indented with INDENT-STRING."
976 (insert indent-string ?
< (symbol-name (xml-node-name tree
)))
978 ;; output the attribute list
979 (setq attlist
(xml-node-attributes tree
))
981 (insert ?\
(symbol-name (caar attlist
)) "=\""
982 (xml-escape-string (cdar attlist
)) ?
\")
983 (setq attlist
(cdr attlist
)))
985 (setq tree
(xml-node-children tree
))
991 ;; output the children
996 (xml-debug-print-internal node
(concat indent-string
" ")))
998 (insert (xml-escape-string node
)))
1000 (error "Invalid XML tree"))))
1002 (when (not (and (null (cdr tree
))
1003 (stringp (car tree
))))
1004 (insert ?
\n indent-string
))
1005 (insert ?
< ?
/ (symbol-name (xml-node-name xml
)) ?
>))))
1009 ;;; xml.el ends here