* lisp/xml.el: Handle entity and character reference expansion correctly.
[emacs.git] / lisp / xml.el
bloba3e279b41bd0a7fc40ca6dae07f2095e89390db6
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>
7 ;; Keywords: xml, data
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/>.
24 ;;; Commentary:
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.
30 ;;; FILE FORMAT
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
36 ;; parsing stopped.
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>
44 ;; </node1>
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
47 ;; below the nodes.
49 ;; There can be only top level node, but with any number of children below.
51 ;;; LIST FORMAT
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") ...)
62 ;; | nil
63 ;; string ::= "..."
65 ;; Some macros are provided to ease the parsing of this list.
66 ;; Whitespace is preserved. Fixme: There should be a tree-walker that
67 ;; can remove it.
69 ;; TODO:
70 ;; * xml:base, xml:space support
71 ;; * more complete DOCTYPE parsing
72 ;; * pi support
74 ;;; Code:
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
94 '(("lt" . "&#60;")
95 ("gt" . ">")
96 ("apos" . "'")
97 ("quot" . "\"")
98 ("amp" . "&#38;"))
99 "Alist mapping XML entities to their replacement text.")
101 (defvar xml-parameter-entity-alist nil
102 "Alist of defined XML parametric entities.")
104 (defvar xml-sub-parser nil
105 "Non-nil when the XML parser is parsing an XML fragment.")
107 (defvar xml-validating-parser nil
108 "Set to non-nil to get validity checking.")
110 (defsubst xml-node-name (node)
111 "Return the tag associated with NODE.
112 Without namespace-aware parsing, the tag is a symbol.
114 With namespace-aware parsing, the tag is a cons of a string
115 representing the uri of the namespace with the local name of the
116 tag. For example,
118 <foo>
120 would be represented by
122 '(\"\" . \"foo\")."
124 (car node))
126 (defsubst xml-node-attributes (node)
127 "Return the list of attributes of NODE.
128 The list can be nil."
129 (nth 1 node))
131 (defsubst xml-node-children (node)
132 "Return the list of children of NODE.
133 This is a list of nodes, and it can be nil."
134 (cddr node))
136 (defun xml-get-children (node child-name)
137 "Return the children of NODE whose tag is CHILD-NAME.
138 CHILD-NAME should match the value returned by `xml-node-name'."
139 (let ((match ()))
140 (dolist (child (xml-node-children node))
141 (if (and (listp child)
142 (equal (xml-node-name child) child-name))
143 (push child match)))
144 (nreverse match)))
146 (defun xml-get-attribute-or-nil (node attribute)
147 "Get from NODE the value of ATTRIBUTE.
148 Return nil if the attribute was not found.
150 See also `xml-get-attribute'."
151 (cdr (assoc attribute (xml-node-attributes node))))
153 (defsubst xml-get-attribute (node attribute)
154 "Get from NODE the value of ATTRIBUTE.
155 An empty string is returned if the attribute was not found.
157 See also `xml-get-attribute-or-nil'."
158 (or (xml-get-attribute-or-nil node attribute) ""))
160 ;;; Creating the list
162 ;;;###autoload
163 (defun xml-parse-file (file &optional parse-dtd parse-ns)
164 "Parse the well-formed XML file FILE.
165 Return the top node with all its children.
166 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped.
167 If PARSE-NS is non-nil, then QNAMES are expanded."
168 (with-temp-buffer
169 (insert-file-contents file)
170 (xml--parse-buffer parse-dtd parse-ns)))
172 (eval-and-compile
173 (let* ((start-chars (concat "[:alpha:]:_"))
174 (name-chars (concat "-[:digit:]." start-chars))
175 ;;[3] S ::= (#x20 | #x9 | #xD | #xA)+
176 (whitespace "[ \t\n\r]"))
177 ;; [4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6]
178 ;; | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF]
179 ;; | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF]
180 ;; | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD]
181 ;; | [#x10000-#xEFFFF]
182 (defconst xml-name-start-char-re (concat "[" start-chars "]"))
183 ;; [4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7
184 ;; | [#x0300-#x036F] | [#x203F-#x2040]
185 (defconst xml-name-char-re (concat "[" name-chars "]"))
186 ;; [5] Name ::= NameStartChar (NameChar)*
187 (defconst xml-name-re (concat xml-name-start-char-re xml-name-char-re "*"))
188 ;; [6] Names ::= Name (#x20 Name)*
189 (defconst xml-names-re (concat xml-name-re "\\(?: " xml-name-re "\\)*"))
190 ;; [7] Nmtoken ::= (NameChar)+
191 (defconst xml-nmtoken-re (concat xml-name-char-re "+"))
192 ;; [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*
193 (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]+;\\)")
196 ;; [68] EntityRef ::= '&' Name ';'
197 (defconst xml-entity-ref (concat "&" xml-name-re ";"))
198 ;; [69] PEReference ::= '%' Name ';'
199 (defconst xml-pe-reference-re (concat "%" xml-name-re ";"))
200 ;; [67] Reference ::= EntityRef | CharRef
201 (defconst xml-reference-re (concat "\\(?:" xml-entity-ref "\\|" xml-char-ref-re "\\)"))
202 ;; [10] AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'"
203 (defconst xml-att-value-re (concat "\\(?:\"\\(?:[^&\"]\\|" xml-reference-re "\\)*\"\\|"
204 "'\\(?:[^&']\\|" xml-reference-re "\\)*'\\)"))
205 ;; [56] TokenizedType ::= 'ID' [VC: ID] [VC: One ID / Element Type] [VC: ID Attribute Default]
206 ;; | 'IDREF' [VC: IDREF]
207 ;; | 'IDREFS' [VC: IDREF]
208 ;; | 'ENTITY' [VC: Entity Name]
209 ;; | 'ENTITIES' [VC: Entity Name]
210 ;; | 'NMTOKEN' [VC: Name Token]
211 ;; | 'NMTOKENS' [VC: Name Token]
212 (defconst xml-tokenized-type-re (concat "\\(?:ID\\|IDREF\\|IDREFS\\|ENTITY\\|"
213 "ENTITIES\\|NMTOKEN\\|NMTOKENS\\)"))
214 ;; [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
215 (defconst xml-notation-type-re
216 (concat "\\(?:NOTATION" whitespace "(" whitespace "*" xml-name-re
217 "\\(?:" whitespace "*|" whitespace "*" xml-name-re "\\)*"
218 whitespace "*)\\)"))
219 ;; [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
220 ;; [VC: Enumeration] [VC: No Duplicate Tokens]
221 (defconst xml-enumeration-re (concat "\\(?:(" whitespace "*" xml-nmtoken-re
222 "\\(?:" whitespace "*|" whitespace "*"
223 xml-nmtoken-re "\\)*"
224 whitespace ")\\)"))
225 ;; [57] EnumeratedType ::= NotationType | Enumeration
226 (defconst xml-enumerated-type-re (concat "\\(?:" xml-notation-type-re
227 "\\|" xml-enumeration-re "\\)"))
228 ;; [54] AttType ::= StringType | TokenizedType | EnumeratedType
229 ;; [55] StringType ::= 'CDATA'
230 (defconst xml-att-type-re (concat "\\(?:CDATA\\|" xml-tokenized-type-re
231 "\\|" xml-notation-type-re
232 "\\|" xml-enumerated-type-re "\\)"))
233 ;; [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
234 (defconst xml-default-decl-re (concat "\\(?:#REQUIRED\\|#IMPLIED\\|\\(?:#FIXED"
235 whitespace "\\)*" xml-att-value-re "\\)"))
236 ;; [53] AttDef ::= S Name S AttType S DefaultDecl
237 (defconst xml-att-def-re (concat "\\(?:" whitespace "*" xml-name-re
238 whitespace "*" xml-att-type-re
239 whitespace "*" xml-default-decl-re "\\)"))
240 ;; [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
241 ;; | "'" ([^%&'] | PEReference | Reference)* "'"
242 (defconst xml-entity-value-re (concat "\\(?:\"\\(?:[^%&\"]\\|" xml-pe-reference-re
243 "\\|" xml-reference-re
244 "\\)*\"\\|'\\(?:[^%&']\\|"
245 xml-pe-reference-re "\\|"
246 xml-reference-re "\\)*'\\)"))))
248 ;; [75] ExternalID ::= 'SYSTEM' S SystemLiteral
249 ;; | 'PUBLIC' S PubidLiteral S SystemLiteral
250 ;; [76] NDataDecl ::= S 'NDATA' S
251 ;; [73] EntityDef ::= EntityValue| (ExternalID NDataDecl?)
252 ;; [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
253 ;; [74] PEDef ::= EntityValue | ExternalID
254 ;; [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
255 ;; [70] EntityDecl ::= GEDecl | PEDecl
257 ;; Note that this is setup so that we can do whitespace-skipping with
258 ;; `(skip-syntax-forward " ")', inter alia. Previously this was slow
259 ;; compared with `re-search-forward', but that has been fixed. Also
260 ;; note that the standard syntax table contains other characters with
261 ;; whitespace syntax, like NBSP, but they are invalid in contexts in
262 ;; which we might skip whitespace -- specifically, they're not
263 ;; NameChars [XML 4].
265 (defvar xml-syntax-table
266 (let ((table (make-syntax-table)))
267 ;; Get space syntax correct per XML [3].
268 (dotimes (c 31)
269 (modify-syntax-entry c "." table)) ; all are space in standard table
270 (dolist (c '(?\t ?\n ?\r)) ; these should be space
271 (modify-syntax-entry c " " table))
272 ;; For skipping attributes.
273 (modify-syntax-entry ?\" "\"" table)
274 (modify-syntax-entry ?' "\"" table)
275 ;; Non-alnum name chars should be symbol constituents (`-' and `_'
276 ;; are OK by default).
277 (modify-syntax-entry ?. "_" table)
278 (modify-syntax-entry ?: "_" table)
279 ;; XML [89]
280 (unless (featurep 'xemacs)
281 (dolist (c '(#x00B7 #x02D0 #x02D1 #x0387 #x0640 #x0E46 #x0EC6 #x3005
282 #x3031 #x3032 #x3033 #x3034 #x3035 #x309D #x309E #x30FC
283 #x30FD #x30FE))
284 (modify-syntax-entry (decode-char 'ucs c) "w" table)))
285 ;; Fixme: rest of [4]
286 table)
287 "Syntax table used by `xml-parse-region'.")
289 ;; XML [5]
290 ;; Note that [:alpha:] matches all multibyte chars with word syntax.
291 (eval-and-compile
292 (defconst xml-name-regexp "[[:alpha:]_:][[:alnum:]._:-]*"))
294 ;; Fixme: This needs re-writing to deal with the XML grammar properly, i.e.
295 ;; document ::= prolog element Misc*
296 ;; prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
298 ;;;###autoload
299 (defun xml-parse-region (&optional beg end buffer parse-dtd parse-ns)
300 "Parse the region from BEG to END in BUFFER.
301 If BEG is nil, it defaults to `point-min'.
302 If END is nil, it defaults to `point-max'.
303 If BUFFER is nil, it defaults to the current buffer.
304 Returns the XML list for the region, or raises an error if the region
305 is not well-formed XML.
306 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped,
307 and returned as the first element of the list.
308 If PARSE-NS is non-nil, then QNAMES are expanded."
309 ;; Use fixed syntax table to ensure regexp char classes and syntax
310 ;; specs DTRT.
311 (unless buffer
312 (setq buffer (current-buffer)))
313 (with-temp-buffer
314 (insert-buffer-substring-no-properties buffer beg end)
315 (xml--parse-buffer parse-dtd parse-ns)))
317 (defun xml--parse-buffer (parse-dtd parse-ns)
318 (with-syntax-table (standard-syntax-table)
319 (let ((case-fold-search nil) ; XML is case-sensitive.
320 ;; Prevent entity definitions from changing the defaults
321 (xml-entity-alist xml-entity-alist)
322 (xml-parameter-entity-alist xml-parameter-entity-alist)
323 xml result dtd)
324 (goto-char (point-min))
325 (while (not (eobp))
326 (if (search-forward "<" nil t)
327 (progn
328 (forward-char -1)
329 (setq result (xml-parse-tag-1 parse-dtd parse-ns))
330 (cond
331 ((null result)
332 ;; Not looking at an xml start tag.
333 (unless (eobp)
334 (forward-char 1)))
335 ((and xml (not xml-sub-parser))
336 ;; Translation of rule [1] of XML specifications
337 (error "XML: (Not Well-Formed) Only one root tag allowed"))
338 ((and (listp (car result))
339 parse-dtd)
340 (setq dtd (car result))
341 (if (cdr result) ; possible leading comment
342 (add-to-list 'xml (cdr result))))
344 (add-to-list 'xml result))))
345 (goto-char (point-max))))
346 (if parse-dtd
347 (cons dtd (nreverse xml))
348 (nreverse xml)))))
350 (defun xml-maybe-do-ns (name default xml-ns)
351 "Perform any namespace expansion.
352 NAME is the name to perform the expansion on.
353 DEFAULT is the default namespace. XML-NS is a cons of namespace
354 names to uris. When namespace-aware parsing is off, then XML-NS
355 is nil.
357 During namespace-aware parsing, any name without a namespace is
358 put into the namespace identified by DEFAULT. nil is used to
359 specify that the name shouldn't be given a namespace."
360 (if (consp xml-ns)
361 (let* ((nsp (string-match ":" name))
362 (lname (if nsp (substring name (match-end 0)) name))
363 (prefix (if nsp (substring name 0 (match-beginning 0)) default))
364 (special (and (string-equal lname "xmlns") (not prefix)))
365 ;; Setting default to nil will insure that there is not
366 ;; matching cons in xml-ns. In which case we
367 (ns (or (cdr (assoc (if special "xmlns" prefix)
368 xml-ns))
369 "")))
370 (cons ns (if special "" lname)))
371 (intern name)))
373 (defun xml-parse-fragment (&optional parse-dtd parse-ns)
374 "Parse xml-like fragments."
375 (let ((xml-sub-parser t)
376 ;; Prevent entity definitions from changing the defaults
377 (xml-entity-alist xml-entity-alist)
378 (xml-parameter-entity-alist xml-parameter-entity-alist)
379 children)
380 (while (not (eobp))
381 (let ((bit (xml-parse-tag-1 parse-dtd parse-ns)))
382 (if children
383 (setq children (append (list bit) children))
384 (if (stringp bit)
385 (setq children (list bit))
386 (setq children bit)))))
387 (reverse children)))
389 (defun xml-parse-tag (&optional parse-dtd parse-ns)
390 "Parse the tag at point.
391 If PARSE-DTD is non-nil, the DTD of the document, if any, is parsed and
392 returned as the first element in the list.
393 If PARSE-NS is non-nil, expand QNAMES; if the value of PARSE-NS
394 is a list, use it as an alist mapping namespaces to URIs.
396 Return one of:
397 - a list : the matching node
398 - nil : the point is not looking at a tag.
399 - a pair : the first element is the DTD, the second is the node."
400 (let ((buf (current-buffer))
401 (pos (point)))
402 (with-temp-buffer
403 (insert-buffer-substring-no-properties buf pos)
404 (goto-char (point-min))
405 (xml-parse-tag-1 parse-dtd parse-ns))))
407 (defun xml-parse-tag-1 (&optional parse-dtd parse-ns)
408 "Like `xml-parse-tag', but possibly modify the buffer while working."
409 (let ((xml-validating-parser (or parse-dtd xml-validating-parser))
410 (xml-ns (cond ((consp parse-ns) parse-ns)
411 (parse-ns xml-default-ns))))
412 (cond
413 ;; Processing instructions, like <?xml version="1.0"?>.
414 ((looking-at "<\\?")
415 (search-forward "?>")
416 (skip-syntax-forward " ")
417 (xml-parse-tag-1 parse-dtd xml-ns))
418 ;; Character data (CDATA) sections, in which no tag should be interpreted
419 ((looking-at "<!\\[CDATA\\[")
420 (let ((pos (match-end 0)))
421 (unless (search-forward "]]>" nil t)
422 (error "XML: (Not Well Formed) CDATA section does not end anywhere in the document"))
423 (concat
424 (buffer-substring-no-properties pos (match-beginning 0))
425 (xml-parse-string))))
426 ;; DTD for the document
427 ((looking-at "<!DOCTYPE[ \t\n\r]")
428 (let ((dtd (xml-parse-dtd parse-ns)))
429 (skip-syntax-forward " ")
430 (if xml-validating-parser
431 (cons dtd (xml-parse-tag-1 nil xml-ns))
432 (xml-parse-tag-1 nil xml-ns))))
433 ;; skip comments
434 ((looking-at "<!--")
435 (search-forward "-->")
436 ;; FIXME: This loses the skipped-over spaces.
437 (skip-syntax-forward " ")
438 (unless (eobp)
439 (let ((xml-sub-parser t))
440 (xml-parse-tag-1 parse-dtd xml-ns))))
441 ;; end tag
442 ((looking-at "</")
443 '())
444 ;; opening tag
445 ((looking-at (eval-when-compile (concat "<\\(" xml-name-re "\\)")))
446 (goto-char (match-end 1))
447 ;; Parse this node
448 (let* ((node-name (match-string-no-properties 1))
449 ;; Parse the attribute list.
450 (attrs (xml-parse-attlist xml-ns))
451 children)
452 ;; add the xmlns:* attrs to our cache
453 (when (consp xml-ns)
454 (dolist (attr attrs)
455 (when (and (consp (car attr))
456 (equal "http://www.w3.org/2000/xmlns/"
457 (caar attr)))
458 (push (cons (cdar attr) (cdr attr))
459 xml-ns))))
460 (setq children (list attrs (xml-maybe-do-ns node-name "" xml-ns)))
461 (cond
462 ;; is this an empty element ?
463 ((looking-at "/>")
464 (forward-char 2)
465 (nreverse children))
466 ;; is this a valid start tag ?
467 ((eq (char-after) ?>)
468 (forward-char 1)
469 ;; Now check that we have the right end-tag.
470 (let ((end (concat "</" node-name "\\s-*>")))
471 (while (not (looking-at end))
472 (cond
473 ((eobp)
474 (error "XML: (Not Well-Formed) End of buffer while reading element `%s'"
475 node-name))
476 ((looking-at "</")
477 (forward-char 2)
478 (error "XML: (Not Well-Formed) Invalid end tag `%s' (expecting `%s')"
479 (let ((pos (point)))
480 (buffer-substring pos (if (re-search-forward "\\s-*>" nil t)
481 (match-beginning 0)
482 (point-max))))
483 node-name))
484 ;; Read a sub-element and push it onto CHILDREN.
485 ((= (char-after) ?<)
486 (let ((tag (xml-parse-tag-1 nil xml-ns)))
487 (when tag
488 (push tag children))))
489 ;; Read some character data.
491 (let ((expansion (xml-parse-string)))
492 (push (if (stringp (car children))
493 ;; If two strings were separated by a
494 ;; comment, concat them.
495 (concat (pop children) expansion)
496 expansion)
497 children)))))
498 ;; Move point past the end-tag.
499 (goto-char (match-end 0))
500 (nreverse children)))
501 ;; Otherwise this was an invalid start tag (expected ">" not found.)
503 (error "XML: (Well-Formed) Couldn't parse tag: %s"
504 (buffer-substring-no-properties (- (point) 10) (+ (point) 1)))))))
506 ;; (Not one of PI, CDATA, Comment, End tag, or Start tag)
508 (unless xml-sub-parser ; Usually, we error out.
509 (error "XML: (Well-Formed) Invalid character"))
510 ;; However, if we're parsing incrementally, then we need to deal
511 ;; with stray CDATA.
512 (xml-parse-string)))))
514 (defun xml-parse-string ()
515 "Parse character data at point, and return it as a string.
516 Leave point at the start of the next thing to parse. This
517 function can modify the buffer by expanding entity and character
518 references."
519 (let ((start (point))
520 ref val)
521 (while (and (not (eobp))
522 (not (looking-at "<")))
523 ;; Find the next < or & character.
524 (skip-chars-forward "^<&")
525 (when (eq (char-after) ?&)
526 ;; If we find an entity or character reference, expand it.
527 (unless (looking-at (eval-when-compile
528 (concat "&\\(?:#\\([0-9]+\\)\\|#x\\([0-9a-fA-F]+\\)\\|\\("
529 xml-name-re "\\)\\);")))
530 (error "XML: (Not Well-Formed) Invalid entity reference"))
531 ;; For a character reference, the next entity or character
532 ;; reference must be after the replacement. [4.6] "Numerical
533 ;; character references are expanded immediately when
534 ;; recognized and MUST be treated as character data."
535 (cond ((setq ref (match-string 1))
536 ;; Decimal character reference
537 (setq val (save-match-data
538 (decode-char 'ucs (string-to-number ref))))
539 (and (null val)
540 xml-validating-parser
541 (error "XML: (Validity) Invalid character `%s'" ref))
542 (replace-match (or (string val) xml-undefined-entity) t t))
543 ;; Hexadecimal character reference
544 ((setq ref (match-string 2))
545 (setq val (save-match-data
546 (decode-char 'ucs (string-to-number ref 16))))
547 (and (null val)
548 xml-validating-parser
549 (error "XML: (Validity) Invalid character `x%s'" ref))
550 (replace-match (or (string val) xml-undefined-entity) t t))
551 ;; For an entity reference, search again from the start
552 ;; of the replaced text, since the replacement can
553 ;; contain entity or character references, or markup.
554 ((setq ref (match-string 3))
555 (setq val (assoc ref xml-entity-alist))
556 (and (null val)
557 xml-validating-parser
558 (error "XML: (Validity) Undefined entity `%s'" ref))
559 (replace-match (cdr val) t t)
560 (goto-char (match-beginning 0))))))
561 ;; [2.11] Clean up line breaks.
562 (let ((end-marker (point-marker)))
563 (goto-char start)
564 (while (re-search-forward "\r\n?" end-marker t)
565 (replace-match "\n" t t))
566 (goto-char end-marker)
567 (buffer-substring start (point)))))
569 (defun xml-parse-attlist (&optional xml-ns)
570 "Return the attribute-list after point.
571 Leave point at the first non-blank character after the tag."
572 (let ((attlist ())
573 end-pos name)
574 (skip-syntax-forward " ")
575 (while (looking-at (eval-when-compile
576 (concat "\\(" xml-name-regexp "\\)\\s-*=\\s-*")))
577 (setq end-pos (match-end 0))
578 (setq name (xml-maybe-do-ns (match-string-no-properties 1) nil xml-ns))
579 (goto-char end-pos)
581 ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
583 ;; Do we have a string between quotes (or double-quotes),
584 ;; or a simple word ?
585 (if (looking-at "\"\\([^\"]*\\)\"")
586 (setq end-pos (match-end 0))
587 (if (looking-at "'\\([^']*\\)'")
588 (setq end-pos (match-end 0))
589 (error "XML: (Not Well-Formed) Attribute values must be given between quotes")))
591 ;; Each attribute must be unique within a given element
592 (if (assoc name attlist)
593 (error "XML: (Not Well-Formed) Each attribute must be unique within an element"))
595 ;; Multiple whitespace characters should be replaced with a single one
596 ;; in the attributes
597 (let ((string (match-string-no-properties 1)))
598 (replace-regexp-in-string "\\s-\\{2,\\}" " " string)
599 (let ((expansion (xml-substitute-special string)))
600 (unless (stringp expansion)
601 ; We say this is the constraint. It is actually that neither
602 ; external entities nor "<" can be in an attribute value.
603 (error "XML: (Not Well-Formed) Entities in attributes cannot expand into elements"))
604 (push (cons name expansion) attlist)))
606 (goto-char end-pos)
607 (skip-syntax-forward " "))
608 (nreverse attlist)))
610 ;;; DTD (document type declaration)
612 ;; The following functions know how to skip or parse the DTD of a
613 ;; document. FIXME: it fails at least if the DTD contains conditional
614 ;; sections.
616 (defun xml-skip-dtd ()
617 "Skip the DTD at point.
618 This follows the rule [28] in the XML specifications."
619 (let ((xml-validating-parser nil))
620 (xml-parse-dtd)))
622 (defun xml-parse-dtd (&optional parse-ns)
623 "Parse the DTD at point."
624 (forward-char (eval-when-compile (length "<!DOCTYPE")))
625 (skip-syntax-forward " ")
626 (if (and (looking-at ">")
627 xml-validating-parser)
628 (error "XML: (Validity) Invalid DTD (expecting name of the document)"))
630 ;; Get the name of the document
631 (looking-at xml-name-regexp)
632 (let ((dtd (list (match-string-no-properties 0) 'dtd))
633 (xml-parameter-entity-alist xml-parameter-entity-alist)
634 (parameter-entity-re (eval-when-compile
635 (concat "%\\(" xml-name-re "\\);")))
636 next-parameter-entity)
637 (goto-char (match-end 0))
638 (skip-syntax-forward " ")
640 ;; External subset (XML [75])
641 (cond ((looking-at "PUBLIC\\s-+")
642 (goto-char (match-end 0))
643 (unless (or (re-search-forward
644 "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
645 nil t)
646 (re-search-forward
647 "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
648 nil t))
649 (error "XML: Missing Public ID"))
650 (let ((pubid (match-string-no-properties 1)))
651 (skip-syntax-forward " ")
652 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
653 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
654 (error "XML: Missing System ID"))
655 (push (list pubid (match-string-no-properties 1) 'public) dtd)))
656 ((looking-at "SYSTEM\\s-+")
657 (goto-char (match-end 0))
658 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
659 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
660 (error "XML: Missing System ID"))
661 (push (list (match-string-no-properties 1) 'system) dtd)))
662 (skip-syntax-forward " ")
664 (if (eq (char-after) ?>)
666 ;; No internal subset
667 (forward-char)
669 ;; Internal subset (XML [28b])
670 (unless (eq (char-after) ?\[)
671 (error "XML: Bad DTD"))
672 (forward-char)
674 ;; [2.8]: "markup declarations may be made up in whole or in
675 ;; part of the replacement text of parameter entities."
677 ;; Since parameter entities are valid only within the DTD, we
678 ;; first search for the position of the next possible parameter
679 ;; entity. Then, search for the next DTD element; if it ends
680 ;; before the next parameter entity, expand the parameter entity
681 ;; and try again.
682 (setq next-parameter-entity
683 (save-excursion
684 (if (re-search-forward parameter-entity-re nil t)
685 (match-beginning 0))))
687 ;; Parse the rest of the DTD
688 ;; Fixme: Deal with NOTATION, PIs.
689 (while (not (looking-at "\\s-*\\]"))
690 (skip-syntax-forward " ")
691 (cond
692 ;; Element declaration [45]:
693 ((and (looking-at (eval-when-compile
694 (concat "<!ELEMENT\\s-+\\(" xml-name-re
695 "\\)\\s-+\\([^>]+\\)>")))
696 (or (null next-parameter-entity)
697 (<= (match-end 0) next-parameter-entity)))
698 (let ((element (match-string-no-properties 1))
699 (type (match-string-no-properties 2))
700 (end-pos (match-end 0)))
701 ;; Translation of rule [46] of XML specifications
702 (cond
703 ((string-match "\\`EMPTY\\s-*\\'" type) ; empty declaration
704 (setq type 'empty))
705 ((string-match "\\`ANY\\s-*$" type) ; any type of contents
706 (setq type 'any))
707 ((string-match "\\`(\\(.*\\))\\s-*\\'" type) ; children ([47])
708 (setq type (xml-parse-elem-type
709 (match-string-no-properties 1 type))))
710 ((string-match "^%[^;]+;[ \t\n\r]*\\'" type) ; substitution
711 nil)
712 (xml-validating-parser
713 (error "XML: (Validity) Invalid element type in the DTD")))
715 ;; rule [45]: the element declaration must be unique
716 (and (assoc element dtd)
717 xml-validating-parser
718 (error "XML: (Validity) DTD element declarations must be unique (<%s>)"
719 element))
721 ;; Store the element in the DTD
722 (push (list element type) dtd)
723 (goto-char end-pos)))
725 ;; Attribute-list declaration [52] (currently unsupported):
726 ((and (looking-at (eval-when-compile
727 (concat "<!ATTLIST[ \t\n\r]*\\(" xml-name-re
728 "\\)[ \t\n\r]*\\(" xml-att-def-re
729 "\\)*[ \t\n\r]*>")))
730 (or (null next-parameter-entity)
731 (<= (match-end 0) next-parameter-entity)))
732 (goto-char (match-end 0)))
734 ;; Comments (skip to end, ignoring parameter entity):
735 ((looking-at "<!--")
736 (search-forward "-->")
737 (and next-parameter-entity
738 (> (point) next-parameter-entity)
739 (setq next-parameter-entity
740 (save-excursion
741 (if (re-search-forward parameter-entity-re nil t)
742 (match-beginning 0))))))
744 ;; Internal entity declarations:
745 ((and (looking-at (eval-when-compile
746 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
747 xml-name-re "\\)[ \t\n\r]*\\("
748 xml-entity-value-re "\\)[ \t\n\r]*>")))
749 (or (null next-parameter-entity)
750 (<= (match-end 0) next-parameter-entity)))
751 (let* ((name (prog1 (match-string-no-properties 2)
752 (goto-char (match-end 0))))
753 (alist (if (match-string 1)
754 'xml-parameter-entity-alist
755 'xml-entity-alist))
756 ;; Retrieve the deplacement text:
757 (value (xml--entity-replacement-text
758 ;; Entity value, sans quotation marks:
759 (substring (match-string-no-properties 3) 1 -1))))
760 ;; If the same entity is declared more than once, the
761 ;; first declaration is binding.
762 (unless (assoc name (symbol-value alist))
763 (set alist (cons (cons name value) (symbol-value alist))))))
765 ;; External entity declarations (currently unsupported):
766 ((and (or (looking-at (eval-when-compile
767 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
768 xml-name-re "\\)[ \t\n\r]+SYSTEM[ \t\n\r]+"
769 "\\(\"[^\"]*\"\\|'[^']*'\\)[ \t\n\r]*>")))
770 (looking-at (eval-when-compile
771 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
772 xml-name-re "\\)[ \t\n\r]+PUBLIC[ \t\n\r]+"
773 "\"[- \r\na-zA-Z0-9'()+,./:=?;!*#@$_%]*\""
774 "\\|'[- \r\na-zA-Z0-9()+,./:=?;!*#@$_%]*'"
775 "[ \t\n\r]+\\(\"[^\"]*\"\\|'[^']*'\\)"
776 "[ \t\n\r]*>"))))
777 (or (null next-parameter-entity)
778 (<= (match-end 0) next-parameter-entity)))
779 (goto-char (match-end 0)))
781 ;; If a parameter entity is in the way, expand it.
782 (next-parameter-entity
783 (save-excursion
784 (goto-char next-parameter-entity)
785 (unless (looking-at parameter-entity-re)
786 (error "XML: Internal error"))
787 (let* ((entity (match-string 1))
788 (beg (point-marker))
789 (elt (assoc entity xml-parameter-entity-alist)))
790 (if elt
791 (progn
792 (replace-match (cdr elt) t t)
793 ;; The replacement can itself be a parameter entity.
794 (goto-char next-parameter-entity))
795 (goto-char (match-end 0))))
796 (setq next-parameter-entity
797 (if (re-search-forward parameter-entity-re nil t)
798 (match-beginning 0)))))
800 ;; Anything else:
801 (xml-validating-parser
802 (error "XML: (Validity) Invalid DTD item"))))
804 (if (looking-at "\\s-*]>")
805 (goto-char (match-end 0))))
806 (nreverse dtd)))
808 (defun xml--entity-replacement-text (string)
809 "Return the replacement text for the entity value STRING.
810 The replacement text is obtained by replacing character
811 references and parameter-entity references."
812 (let ((ref-re (eval-when-compile
813 (concat "\\(?:&#\\([0-9]+\\)\\|&#x\\([0-9a-fA-F]+\\)\\|%\\("
814 xml-name-re "\\)\\);")))
815 children)
816 (while (string-match ref-re string)
817 (push (substring string 0 (match-beginning 0)) children)
818 (let ((remainder (substring string (match-end 0)))
819 ref val)
820 (cond ((setq ref (match-string 1 string))
821 ;; Decimal character reference
822 (setq val (decode-char 'ucs (string-to-number ref)))
823 (if val (push (string val) children)))
824 ;; Hexadecimal character reference
825 ((setq ref (match-string 2 string))
826 (setq val (decode-char 'ucs (string-to-number ref 16)))
827 (if val (push (string val) children)))
828 ;; Parameter entity reference
829 ((setq ref (match-string 3 string))
830 (setq val (assoc ref xml-parameter-entity-alist))
831 (and (null val)
832 xml-validating-parser
833 (error "XML: (Validity) Undefined parameter entity `%s'" ref))
834 (push (or (cdr val) xml-undefined-entity) children)))
835 (setq string remainder)))
836 (mapconcat 'identity (nreverse (cons string children)) "")))
838 (defun xml-parse-elem-type (string)
839 "Convert element type STRING into a Lisp structure."
841 (let (elem modifier)
842 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
843 (progn
844 (setq elem (match-string-no-properties 1 string)
845 modifier (match-string-no-properties 2 string))
846 (if (string-match "|" elem)
847 (setq elem (cons 'choice
848 (mapcar 'xml-parse-elem-type
849 (split-string elem "|"))))
850 (if (string-match "," elem)
851 (setq elem (cons 'seq
852 (mapcar 'xml-parse-elem-type
853 (split-string elem ",")))))))
854 (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string)
855 (setq elem (match-string-no-properties 1 string)
856 modifier (match-string-no-properties 2 string))))
858 (if (and (stringp elem) (string= elem "#PCDATA"))
859 (setq elem 'pcdata))
861 (cond
862 ((string= modifier "+")
863 (list '+ elem))
864 ((string= modifier "*")
865 (list '* elem))
866 ((string= modifier "?")
867 (list '\? elem))
869 elem))))
871 ;;; Substituting special XML sequences
873 (defun xml-substitute-special (string)
874 "Return STRING, after substituting entity and character references.
875 STRING is assumed to occur in an XML attribute value."
876 (let ((ref-re (eval-when-compile
877 (concat "&\\(?:#\\(x\\)?\\([0-9]+\\)\\|\\("
878 xml-name-re "\\)\\);")))
879 children)
880 (while (string-match ref-re string)
881 (push (substring string 0 (match-beginning 0)) children)
882 (let* ((remainder (substring string (match-end 0)))
883 (ref (match-string 2 string)))
884 (if ref
885 ;; [4.6] Character references are included as
886 ;; character data.
887 (let ((val (decode-char 'ucs (string-to-number
888 ref (if (match-string 1 string) 16)))))
889 (push (cond (val (string val))
890 (xml-validating-parser
891 (error "XML: (Validity) Undefined character `x%s'" ref))
892 (t xml-undefined-entity))
893 children)
894 (setq string remainder))
895 ;; [4.4.5] Entity references are "included in literal".
896 ;; Note that we don't need do anything special to treat
897 ;; quotes as normal data characters.
898 (setq ref (match-string 3 string))
899 (let ((val (or (cdr (assoc ref xml-entity-alist))
900 (if xml-validating-parser
901 (error "XML: (Validity) Undefined entity `%s'" ref)
902 xml-undefined-entity))))
903 (setq string (concat val remainder))))))
904 (mapconcat 'identity (nreverse (cons string children)) "")))
906 (defun xml-substitute-numeric-entities (string)
907 "Substitute SGML numeric entities by their respective utf characters.
908 This function replaces numeric entities in the input STRING and
909 returns the modified string. For example \"&#42;\" gets replaced
910 by \"*\"."
911 (if (and string (stringp string))
912 (let ((start 0))
913 (while (string-match "&#\\([0-9]+\\);" string start)
914 (condition-case nil
915 (setq string (replace-match
916 (string (read (substring string
917 (match-beginning 1)
918 (match-end 1))))
919 nil nil string))
920 (error nil))
921 (setq start (1+ (match-beginning 0))))
922 string)
923 nil))
925 ;;; Printing a parse tree (mainly for debugging).
927 (defun xml-debug-print (xml &optional indent-string)
928 "Outputs the XML in the current buffer.
929 XML can be a tree or a list of nodes.
930 The first line is indented with the optional INDENT-STRING."
931 (setq indent-string (or indent-string ""))
932 (dolist (node xml)
933 (xml-debug-print-internal node indent-string)))
935 (defalias 'xml-print 'xml-debug-print)
937 (defun xml-escape-string (string)
938 "Return STRING with entity substitutions made from `xml-entity-alist'."
939 (mapconcat (lambda (byte)
940 (let ((char (char-to-string byte)))
941 (if (rassoc char xml-entity-alist)
942 (concat "&" (car (rassoc char xml-entity-alist)) ";")
943 char)))
944 string ""))
946 (defun xml-debug-print-internal (xml indent-string)
947 "Outputs the XML tree in the current buffer.
948 The first line is indented with INDENT-STRING."
949 (let ((tree xml)
950 attlist)
951 (insert indent-string ?< (symbol-name (xml-node-name tree)))
953 ;; output the attribute list
954 (setq attlist (xml-node-attributes tree))
955 (while attlist
956 (insert ?\ (symbol-name (caar attlist)) "=\""
957 (xml-escape-string (cdar attlist)) ?\")
958 (setq attlist (cdr attlist)))
960 (setq tree (xml-node-children tree))
962 (if (null tree)
963 (insert ?/ ?>)
964 (insert ?>)
966 ;; output the children
967 (dolist (node tree)
968 (cond
969 ((listp node)
970 (insert ?\n)
971 (xml-debug-print-internal node (concat indent-string " ")))
972 ((stringp node)
973 (insert (xml-escape-string node)))
975 (error "Invalid XML tree"))))
977 (when (not (and (null (cdr tree))
978 (stringp (car tree))))
979 (insert ?\n indent-string))
980 (insert ?< ?/ (symbol-name (xml-node-name xml)) ?>))))
982 (provide 'xml)
984 ;;; xml.el ends here