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