* xml.el (xml-parse-dtd): Use proper regexps for ELEMENT declarations.
[bpt/emacs.git] / lisp / xml.el
1 ;;; xml.el --- XML parser
2
3 ;; Copyright (C) 2000-2012 Free Software Foundation, Inc.
4
5 ;; Author: Emmanuel Briot <briot@gnat.com>
6 ;; Maintainer: Mark A. Hershberger <mah@everybody.org>
7 ;; Keywords: xml, data
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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/>.
23
24 ;;; Commentary:
25
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.
29
30 ;;; FILE FORMAT
31
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.
37 ;;
38 ;; It also knows how to ignore comments and processing instructions.
39 ;;
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.
48 ;;
49 ;; There can be only top level node, but with any number of children below.
50
51 ;;; LIST FORMAT
52
53 ;; The functions `xml-parse-file', `xml-parse-region' and
54 ;; `xml-parse-tag' return a list with the following format:
55 ;;
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 ::= "..."
64 ;;
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.
68
69 ;; TODO:
70 ;; * xml:base, xml:space support
71 ;; * more complete DOCTYPE parsing
72 ;; * pi support
73
74 ;;; Code:
75
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.
82
83 ;;*******************************************************************
84 ;;**
85 ;;** Macros to parse the list
86 ;;**
87 ;;*******************************************************************
88
89 (defconst xml-undefined-entity "?"
90 "What to substitute for undefined entities")
91
92 (defvar xml-entity-alist
93 '(("lt" . "<")
94 ("gt" . ">")
95 ("apos" . "'")
96 ("quot" . "\"")
97 ("amp" . "&"))
98 "Alist of defined XML entities.")
99
100 (defvar xml-parameter-entity-alist nil
101 "Alist of defined XML parametric entities.")
102
103 (defvar xml-sub-parser nil
104 "Non-nil when the XML parser is parsing an XML fragment.")
105
106 (defvar xml-validating-parser nil
107 "Set to non-nil to get validity checking.")
108
109 (defsubst xml-node-name (node)
110 "Return the tag associated with NODE.
111 Without namespace-aware parsing, the tag is a symbol.
112
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,
116
117 <foo>
118
119 would be represented by
120
121 '(\"\" . \"foo\")."
122
123 (car node))
124
125 (defsubst xml-node-attributes (node)
126 "Return the list of attributes of NODE.
127 The list can be nil."
128 (nth 1 node))
129
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))
134
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)))
144
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.
148
149 See also `xml-get-attribute'."
150 (cdr (assoc attribute (xml-node-attributes node))))
151
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.
155
156 See also `xml-get-attribute-or-nil'."
157 (or (xml-get-attribute-or-nil node attribute) ""))
158
159 ;;*******************************************************************
160 ;;**
161 ;;** Creating the list
162 ;;**
163 ;;*******************************************************************
164
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)))
174
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 "\\)*'\\)"))))
250
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
259
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].
267
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'.")
291
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:]._:-]*"))
296
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*)?
300
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)))
317
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))))
344 (t
345 (add-to-list 'xml result))))
346 (goto-char (point-max))))
347 (if parse-dtd
348 (cons dtd (nreverse xml))
349 (nreverse xml)))))
350
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.
357
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)))
373
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)))
390
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))
446
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
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))))
461
462 (setq children (list attrs (xml-maybe-do-ns node-name "" xml-ns)))
463
464 ;; is this an empty element ?
465 (if (looking-at "/>")
466 (progn
467 (forward-char 2)
468 (nreverse children))
469
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))))
486 (t
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))))))))
496
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"))
505
506 ;; However, if we're parsing incrementally, then we need to deal
507 ;; with stray CDATA.
508 (xml-parse-string)))))
509
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))))
523
524 (xml-substitute-special string)))
525
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)
537
538 ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
539
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")))
547
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"))
551
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)))
562
563 (goto-char end-pos)
564 (skip-syntax-forward " "))
565 (nreverse attlist)))
566
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 ;;*******************************************************************
574
575 ;; Fixme: This fails at least if the DTD contains conditional sections.
576
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)))
582
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)"))
590
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 " ")
600
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 " ")
624
625 (if (eq (char-after) ?>)
626
627 ;; No internal subset
628 (forward-char)
629
630 ;; Internal subset (XML [28b])
631 (unless (eq (char-after) ?\[)
632 (error "XML: Bad DTD"))
633 (forward-char)
634
635 ;; [2.8]: "markup declarations may be made up in whole or in
636 ;; part of the replacement text of parameter entities."
637
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))))
647
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 (eval-when-compile
655 (concat "<!ELEMENT\\s-+\\(" xml-name-re
656 "\\)\\s-+\\([^>]+\\)>")))
657 (or (null next-parameter-entity)
658 (<= (match-end 0) next-parameter-entity)))
659 (let ((element (match-string-no-properties 1))
660 (type (match-string-no-properties 2))
661 (end-pos (match-end 0)))
662 ;; Translation of rule [46] of XML specifications
663 (cond
664 ((string-match "\\`EMPTY\\s-*\\'" type) ; empty declaration
665 (setq type 'empty))
666 ((string-match "\\`ANY\\s-*$" type) ; any type of contents
667 (setq type 'any))
668 ((string-match "\\`(\\(.*\\))\\s-*\\'" type) ; children ([47])
669 (setq type (xml-parse-elem-type
670 (match-string-no-properties 1 type))))
671 ((string-match "^%[^;]+;[ \t\n\r]*\\'" type) ; substitution
672 nil)
673 (xml-validating-parser
674 (error "XML: (Validity) Invalid element type in the DTD")))
675
676 ;; rule [45]: the element declaration must be unique
677 (and (assoc element dtd)
678 xml-validating-parser
679 (error "XML: (Validity) DTD element declarations must be unique (<%s>)"
680 element))
681
682 ;; Store the element in the DTD
683 (push (list element type) dtd)
684 (goto-char end-pos)))
685
686 ;; Attribute-list declaration [52] (currently unsupported):
687 ((and (looking-at (eval-when-compile
688 (concat "<!ATTLIST[ \t\n\r]*\\(" xml-name-re
689 "\\)[ \t\n\r]*\\(" xml-att-def-re
690 "\\)*[ \t\n\r]*>")))
691 (or (null next-parameter-entity)
692 (<= (match-end 0) next-parameter-entity)))
693 (goto-char (match-end 0)))
694
695 ;; Comments (skip to end, ignoring parameter entity):
696 ((looking-at "<!--")
697 (search-forward "-->")
698 (and next-parameter-entity
699 (> (point) next-parameter-entity)
700 (setq next-parameter-entity
701 (save-excursion
702 (if (re-search-forward parameter-entity-re nil t)
703 (match-beginning 0))))))
704
705 ;; Internal entity declarations:
706 ((and (looking-at (eval-when-compile
707 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
708 xml-name-re "\\)[ \t\n\r]*\\("
709 xml-entity-value-re "\\)[ \t\n\r]*>")))
710 (or (null next-parameter-entity)
711 (<= (match-end 0) next-parameter-entity)))
712 (let* ((name (prog1 (match-string-no-properties 2)
713 (goto-char (match-end 0))))
714 (alist (if (match-string 1)
715 'xml-parameter-entity-alist
716 'xml-entity-alist))
717 ;; Retrieve the deplacement text:
718 (value (xml--entity-replacement-text
719 ;; Entity value, sans quotation marks:
720 (substring (match-string-no-properties 3) 1 -1))))
721 ;; If the same entity is declared more than once, the
722 ;; first declaration is binding.
723 (unless (assoc name (symbol-value alist))
724 (set alist (cons (cons name value) (symbol-value alist))))))
725
726 ;; External entity declarations (currently unsupported):
727 ((and (or (looking-at (eval-when-compile
728 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
729 xml-name-re "\\)[ \t\n\r]+SYSTEM[ \t\n\r]+"
730 "\\(\"[^\"]*\"\\|'[^']*'\\)[ \t\n\r]*>")))
731 (looking-at (eval-when-compile
732 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
733 xml-name-re "\\)[ \t\n\r]+PUBLIC[ \t\n\r]+"
734 "\"[- \r\na-zA-Z0-9'()+,./:=?;!*#@$_%]*\""
735 "\\|'[- \r\na-zA-Z0-9()+,./:=?;!*#@$_%]*'"
736 "[ \t\n\r]+\\(\"[^\"]*\"\\|'[^']*'\\)"
737 "[ \t\n\r]*>"))))
738 (or (null next-parameter-entity)
739 (<= (match-end 0) next-parameter-entity)))
740 (goto-char (match-end 0)))
741
742 ;; If a parameter entity is in the way, expand it.
743 (next-parameter-entity
744 (save-excursion
745 (goto-char next-parameter-entity)
746 (unless (looking-at parameter-entity-re)
747 (error "XML: Internal error"))
748 (let* ((entity (match-string 1))
749 (beg (point-marker))
750 (elt (assoc entity xml-parameter-entity-alist)))
751 (if elt
752 (progn
753 (replace-match (cdr elt) t t)
754 ;; The replacement can itself be a parameter entity.
755 (goto-char next-parameter-entity))
756 (goto-char (match-end 0))))
757 (setq next-parameter-entity
758 (if (re-search-forward parameter-entity-re nil t)
759 (match-beginning 0)))))
760
761 ;; Anything else:
762 (xml-validating-parser
763 (error "XML: (Validity) Invalid DTD item"))))
764
765 (if (looking-at "\\s-*]>")
766 (goto-char (match-end 0))))
767 (nreverse dtd)))
768
769 (defun xml--entity-replacement-text (string)
770 "Return the replacement text for the entity value STRING.
771 The replacement text is obtained by replacing character
772 references and parameter-entity references."
773 (let ((ref-re (eval-when-compile
774 (concat "\\(?:&#\\([0-9]+\\)\\|&#x\\([0-9a-fA-F]+\\)\\|%\\("
775 xml-name-re "\\)\\);")))
776 children)
777 (while (string-match ref-re string)
778 (push (substring string 0 (match-beginning 0)) children)
779 (let ((remainder (substring string (match-end 0)))
780 ref val)
781 (cond ((setq ref (match-string 1 string))
782 ;; Decimal character reference
783 (setq val (decode-char 'ucs (string-to-number ref)))
784 (if val (push (string val) children)))
785 ;; Hexadecimal character reference
786 ((setq ref (match-string 2 string))
787 (setq val (decode-char 'ucs (string-to-number ref 16)))
788 (if val (push (string val) children)))
789 ;; Parameter entity reference
790 ((setq ref (match-string 3 string))
791 (setq val (assoc ref xml-parameter-entity-alist))
792 (if val
793 (push (cdr val) children)
794 (push (concat "%" ref ";") children))))
795 (setq string remainder)))
796 (mapconcat 'identity (nreverse (cons string children)) "")))
797
798 (defun xml-parse-elem-type (string)
799 "Convert element type STRING into a Lisp structure."
800
801 (let (elem modifier)
802 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
803 (progn
804 (setq elem (match-string-no-properties 1 string)
805 modifier (match-string-no-properties 2 string))
806 (if (string-match "|" elem)
807 (setq elem (cons 'choice
808 (mapcar 'xml-parse-elem-type
809 (split-string elem "|"))))
810 (if (string-match "," elem)
811 (setq elem (cons 'seq
812 (mapcar 'xml-parse-elem-type
813 (split-string elem ",")))))))
814 (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string)
815 (setq elem (match-string-no-properties 1 string)
816 modifier (match-string-no-properties 2 string))))
817
818 (if (and (stringp elem) (string= elem "#PCDATA"))
819 (setq elem 'pcdata))
820
821 (cond
822 ((string= modifier "+")
823 (list '+ elem))
824 ((string= modifier "*")
825 (list '* elem))
826 ((string= modifier "?")
827 (list '\? elem))
828 (t
829 elem))))
830
831 ;;*******************************************************************
832 ;;**
833 ;;** Substituting special XML sequences
834 ;;**
835 ;;*******************************************************************
836
837 (defun xml-substitute-special (string)
838 "Return STRING, after substituting entity references."
839 ;; This originally made repeated passes through the string from the
840 ;; beginning, which isn't correct, since then either "&amp;amp;" or
841 ;; "&#38;amp;" won't DTRT.
842
843 (let ((point 0)
844 children end-point)
845 (while (string-match "&\\([^;]*\\);" string point)
846 (setq end-point (match-end 0))
847 (let* ((this-part (match-string-no-properties 1 string))
848 (prev-part (substring string point (match-beginning 0)))
849 (entity (assoc this-part xml-entity-alist))
850 (expansion
851 (cond ((string-match "#\\([0-9]+\\)" this-part)
852 (let ((c (decode-char
853 'ucs
854 (string-to-number (match-string-no-properties 1 this-part)))))
855 (if c (string c))))
856 ((string-match "#x\\([[:xdigit:]]+\\)" this-part)
857 (let ((c (decode-char
858 'ucs
859 (string-to-number (match-string-no-properties 1 this-part) 16))))
860 (if c (string c))))
861 (entity
862 (cdr entity))
863 ((eq (length this-part) 0)
864 (error "XML: (Not Well-Formed) No entity given"))
865 (t
866 (if xml-validating-parser
867 (error "XML: (Validity) Undefined entity `%s'"
868 this-part)
869 xml-undefined-entity)))))
870
871 (cond ((null children)
872 ;; FIXME: If we have an entity that expands into XML, this won't work.
873 (setq children
874 (concat prev-part expansion)))
875 ((stringp children)
876 (if (stringp expansion)
877 (setq children (concat children prev-part expansion))
878 (setq children (list expansion (concat prev-part children)))))
879 ((and (stringp expansion)
880 (stringp (car children)))
881 (setcar children (concat prev-part expansion (car children))))
882 ((stringp expansion)
883 (setq children (append (concat prev-part expansion)
884 children)))
885 ((stringp (car children))
886 (setcar children (concat (car children) prev-part))
887 (setq children (append expansion children)))
888 (t
889 (setq children (list expansion
890 prev-part
891 children))))
892 (setq point end-point)))
893 (cond ((stringp children)
894 (concat children (substring string point)))
895 ((stringp (car (last children)))
896 (concat (car (last children)) (substring string point)))
897 ((null children)
898 string)
899 (t
900 (concat (mapconcat 'identity
901 (nreverse children)
902 "")
903 (substring string point))))))
904
905 (defun xml-substitute-numeric-entities (string)
906 "Substitute SGML numeric entities by their respective utf characters.
907 This function replaces numeric entities in the input STRING and
908 returns the modified string. For example \"&#42;\" gets replaced
909 by \"*\"."
910 (if (and string (stringp string))
911 (let ((start 0))
912 (while (string-match "&#\\([0-9]+\\);" string start)
913 (condition-case nil
914 (setq string (replace-match
915 (string (read (substring string
916 (match-beginning 1)
917 (match-end 1))))
918 nil nil string))
919 (error nil))
920 (setq start (1+ (match-beginning 0))))
921 string)
922 nil))
923
924 ;;*******************************************************************
925 ;;**
926 ;;** Printing a tree.
927 ;;** This function is intended mainly for debugging purposes.
928 ;;**
929 ;;*******************************************************************
930
931 (defun xml-debug-print (xml &optional indent-string)
932 "Outputs the XML in the current buffer.
933 XML can be a tree or a list of nodes.
934 The first line is indented with the optional INDENT-STRING."
935 (setq indent-string (or indent-string ""))
936 (dolist (node xml)
937 (xml-debug-print-internal node indent-string)))
938
939 (defalias 'xml-print 'xml-debug-print)
940
941 (defun xml-escape-string (string)
942 "Return STRING with entity substitutions made from `xml-entity-alist'."
943 (mapconcat (lambda (byte)
944 (let ((char (char-to-string byte)))
945 (if (rassoc char xml-entity-alist)
946 (concat "&" (car (rassoc char xml-entity-alist)) ";")
947 char)))
948 string ""))
949
950 (defun xml-debug-print-internal (xml indent-string)
951 "Outputs the XML tree in the current buffer.
952 The first line is indented with INDENT-STRING."
953 (let ((tree xml)
954 attlist)
955 (insert indent-string ?< (symbol-name (xml-node-name tree)))
956
957 ;; output the attribute list
958 (setq attlist (xml-node-attributes tree))
959 (while attlist
960 (insert ?\ (symbol-name (caar attlist)) "=\""
961 (xml-escape-string (cdar attlist)) ?\")
962 (setq attlist (cdr attlist)))
963
964 (setq tree (xml-node-children tree))
965
966 (if (null tree)
967 (insert ?/ ?>)
968 (insert ?>)
969
970 ;; output the children
971 (dolist (node tree)
972 (cond
973 ((listp node)
974 (insert ?\n)
975 (xml-debug-print-internal node (concat indent-string " ")))
976 ((stringp node)
977 (insert (xml-escape-string node)))
978 (t
979 (error "Invalid XML tree"))))
980
981 (when (not (and (null (cdr tree))
982 (stringp (car tree))))
983 (insert ?\n indent-string))
984 (insert ?< ?/ (symbol-name (xml-node-name xml)) ?>))))
985
986 (provide 'xml)
987
988 ;;; xml.el ends here