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