(elint-check-defcustom-form): Don't use `evenp' so we don't implicitly
[emacs.git] / lisp / xml.el
blob27363f7ee2dafbdccbb6213f06f4e738e877eddf
1 ;;; xml.el --- XML parser
3 ;; Copyright (C) 2000, 2001, 2003 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 2, or (at your option)
14 ;; 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; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
26 ;;; Commentary:
28 ;; This file contains a somewhat incomplete non-validating XML parser. It
29 ;; parses a file, and returns a list that can be used internally by
30 ;; any other lisp libraries.
32 ;;; FILE FORMAT
34 ;; The document type declaration may either be ignored or (optionally)
35 ;; parsed, but currently the parsing will only accept element
36 ;; declarations. The XML file is assumed to be well-formed. In case
37 ;; of error, the parsing stops and the XML file is shown where the
38 ;; parsing stopped.
40 ;; It also knows how to ignore comments and processing instructions.
42 ;; The XML file should have the following format:
43 ;; <node1 attr1="name1" attr2="name2" ...>value
44 ;; <node2 attr3="name3" attr4="name4">value2</node2>
45 ;; <node3 attr5="name5" attr6="name6">value3</node3>
46 ;; </node1>
47 ;; Of course, the name of the nodes and attributes can be anything. There can
48 ;; be any number of attributes (or none), as well as any number of children
49 ;; below the nodes.
51 ;; There can be only top level node, but with any number of children below.
53 ;;; LIST FORMAT
55 ;; The functions `xml-parse-file' and `xml-parse-tag' return a list with
56 ;; the following format:
58 ;; xml-list ::= (node node ...)
59 ;; node ::= (tag_name attribute-list . child_node_list)
60 ;; child_node_list ::= child_node child_node ...
61 ;; child_node ::= node | string
62 ;; tag_name ::= string
63 ;; attribute_list ::= (("attribute" . "value") ("attribute" . "value") ...)
64 ;; | nil
65 ;; string ::= "..."
67 ;; Some macros are provided to ease the parsing of this list.
68 ;; Whitespace is preserved. Fixme: There should be a tree-walker that
69 ;; can remove it.
71 ;;; Code:
73 ;; Note that {buffer-substring,match-string}-no-properties were
74 ;; formerly used in several places, but that removes composition info.
76 ;;*******************************************************************
77 ;;**
78 ;;** Macros to parse the list
79 ;;**
80 ;;*******************************************************************
82 (defsubst xml-node-name (node)
83 "Return the tag associated with NODE.
84 The tag is a lower-case symbol."
85 (car node))
87 (defsubst xml-node-attributes (node)
88 "Return the list of attributes of NODE.
89 The list can be nil."
90 (nth 1 node))
92 (defsubst xml-node-children (node)
93 "Return the list of children of NODE.
94 This is a list of nodes, and it can be nil."
95 (cddr node))
97 (defun xml-get-children (node child-name)
98 "Return the children of NODE whose tag is CHILD-NAME.
99 CHILD-NAME should be a lower case symbol."
100 (let ((match ()))
101 (dolist (child (xml-node-children node))
102 (if child
103 (if (equal (xml-node-name child) child-name)
104 (push child match))))
105 (nreverse match)))
107 (defun xml-get-attribute (node attribute)
108 "Get from NODE the value of ATTRIBUTE.
109 An empty string is returned if the attribute was not found."
110 (if (xml-node-attributes node)
111 (let ((value (assoc attribute (xml-node-attributes node))))
112 (if value
113 (cdr value)
114 ""))
115 ""))
117 ;;*******************************************************************
118 ;;**
119 ;;** Creating the list
120 ;;**
121 ;;*******************************************************************
123 ;;;###autoload
124 (defun xml-parse-file (file &optional parse-dtd parse-ns)
125 "Parse the well-formed XML file FILE.
126 If FILE is already visited, use its buffer and don't kill it.
127 Returns the top node with all its children.
128 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped.
129 If PARSE-NS is non-nil, then QNAMES are expanded."
130 (let ((keep))
131 (if (get-file-buffer file)
132 (progn
133 (set-buffer (get-file-buffer file))
134 (setq keep (point)))
135 (let (auto-mode-alist) ; no need for xml-mode
136 (find-file file)))
138 (let ((xml (xml-parse-region (point-min)
139 (point-max)
140 (current-buffer)
141 parse-dtd parse-ns)))
142 (if keep
143 (goto-char keep)
144 (kill-buffer (current-buffer)))
145 xml)))
147 ;; Note that this is setup so that we can do whitespace-skipping with
148 ;; `(skip-syntax-forward " ")', inter alia. Previously this was slow
149 ;; compared with `re-search-forward', but that has been fixed. Also
150 ;; note that the standard syntax table contains other characters with
151 ;; whitespace syntax, like NBSP, but they are invalid in contexts in
152 ;; which we might skip whitespace -- specifically, they're not
153 ;; NameChars [XML 4].
155 (defvar xml-syntax-table
156 (let ((table (make-syntax-table)))
157 ;; Get space syntax correct per XML [3].
158 (dotimes (c 31)
159 (modify-syntax-entry c "." table)) ; all are space in standard table
160 (dolist (c '(?\t ?\n ?\r)) ; these should be space
161 (modify-syntax-entry c " " table))
162 ;; For skipping attributes.
163 (modify-syntax-entry ?\" "\"" table)
164 (modify-syntax-entry ?' "\"" table)
165 ;; Non-alnum name chars should be symbol constituents (`-' and `_'
166 ;; are OK by default).
167 (modify-syntax-entry ?. "_" table)
168 (modify-syntax-entry ?: "_" table)
169 ;; XML [89]
170 (dolist (c '(#x00B7 #x02D0 #x02D1 #x0387 #x0640 #x0E46 #x0EC6 #x3005
171 #x3031 #x3032 #x3033 #x3034 #x3035 #x309D #x309E #x30FC
172 #x30FD #x30FE))
173 (modify-syntax-entry (decode-char 'ucs c) "w" table))
174 ;; Fixme: rest of [4]
175 table)
176 "Syntax table used by `xml-parse-region'.")
178 ;; XML [5]
179 ;; Note that [:alpha:] matches all multibyte chars with word syntax.
180 (eval-and-compile
181 (defconst xml-name-regexp "[[:alpha:]_:][[:alnum:]._:-]*"))
183 ;; Fixme: This needs re-writing to deal with the XML grammar properly, i.e.
184 ;; document ::= prolog element Misc*
185 ;; prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
187 ;;;###autoload
188 (defun xml-parse-region (beg end &optional buffer parse-dtd parse-ns)
189 "Parse the region from BEG to END in BUFFER.
190 If BUFFER is nil, it defaults to the current buffer.
191 Returns the XML list for the region, or raises an error if the region
192 is not well-formed XML.
193 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped,
194 and returned as the first element of the list.
195 If PARSE-NS is non-nil, then QNAMES are expanded."
196 (save-restriction
197 (narrow-to-region beg end)
198 ;; Use fixed syntax table to ensure regexp char classes and syntax
199 ;; specs DTRT.
200 (with-syntax-table (standard-syntax-table)
201 (let ((case-fold-search nil) ; XML is case-sensitive.
202 xml result dtd)
203 (save-excursion
204 (if buffer
205 (set-buffer buffer))
206 (goto-char (point-min))
207 (while (not (eobp))
208 (if (search-forward "<" nil t)
209 (progn
210 (forward-char -1)
211 (if xml
212 ;; translation of rule [1] of XML specifications
213 (error "XML files can have only one toplevel tag")
214 (setq result (xml-parse-tag parse-dtd parse-ns))
215 (cond
216 ((null result))
217 ((listp (car result))
218 (setq dtd (car result))
219 (if (cdr result) ; possible leading comment
220 (add-to-list 'xml (cdr result))))
222 (add-to-list 'xml result)))))
223 (goto-char (point-max))))
224 (if parse-dtd
225 (cons dtd (nreverse xml))
226 (nreverse xml)))))))
229 (defun xml-parse-tag (&optional parse-dtd parse-ns)
230 "Parse the tag at point.
231 If PARSE-DTD is non-nil, the DTD of the document, if any, is parsed and
232 returned as the first element in the list.
233 If PARSE-NS is non-nil, then QNAMES are expanded.
234 Returns one of:
235 - a list : the matching node
236 - nil : the point is not looking at a tag.
237 - a pair : the first element is the DTD, the second is the node."
238 (let ((xml-ns (if (consp parse-ns)
239 parse-ns
240 (if parse-ns
241 (list
242 ;; Default no namespace
243 (cons "" "")
244 ;; We need to seed the xmlns namespace
245 (cons "xmlns" "http://www.w3.org/2000/xmlns/"))))))
246 (cond
247 ;; Processing instructions (like the <?xml version="1.0"?> tag at the
248 ;; beginning of a document).
249 ((looking-at "<\\?")
250 (search-forward "?>")
251 (skip-syntax-forward " ")
252 (xml-parse-tag parse-dtd xml-ns))
253 ;; Character data (CDATA) sections, in which no tag should be interpreted
254 ((looking-at "<!\\[CDATA\\[")
255 (let ((pos (match-end 0)))
256 (unless (search-forward "]]>" nil t)
257 (error "CDATA section does not end anywhere in the document"))
258 (buffer-substring pos (match-beginning 0))))
259 ;; DTD for the document
260 ((looking-at "<!DOCTYPE")
261 (let (dtd)
262 (if parse-dtd
263 (setq dtd (xml-parse-dtd))
264 (xml-skip-dtd))
265 (skip-syntax-forward " ")
266 (if dtd
267 (cons dtd (xml-parse-tag nil xml-ns))
268 (xml-parse-tag nil xml-ns))))
269 ;; skip comments
270 ((looking-at "<!--")
271 (search-forward "-->")
272 nil)
273 ;; end tag
274 ((looking-at "</")
275 '())
276 ;; opening tag
277 ((looking-at "<\\([^/>[:space:]]+\\)")
278 (goto-char (match-end 1))
279 (let* ((node-name (match-string 1))
280 ;; Parse the attribute list.
281 (children (list (xml-parse-attlist) (intern node-name)))
282 pos)
284 ;; add the xmlns:* attrs to our cache
285 (when (consp xml-ns)
286 (mapcar
287 (lambda (attr)
288 (let* ((splitup (split-string (symbol-name (car attr)) ":"))
289 (prefix (nth 0 splitup))
290 (lname (nth 1 splitup)))
291 (when (string= "xmlns" prefix)
292 (setq xml-ns (append (list (cons (if lname
293 lname
295 (cdr attr)))
296 xml-ns)))))
297 (car children))
299 ;; expand element names
300 (let* ((splitup (split-string (symbol-name (cadr children)) ":"))
301 (lname (or (nth 1 splitup)
302 (nth 0 splitup)))
303 (prefix (if (nth 1 splitup)
304 (nth 0 splitup)
305 "")))
306 (setcdr children (list
307 (intern (concat "{"
308 (cdr (assoc-string prefix xml-ns))
309 "}" lname)))))
311 ;; expand attribute names
312 (mapcar
313 (lambda (attr)
314 (let* ((splitup (split-string (symbol-name (car attr)) ":"))
315 (lname (or (nth 1 splitup)
316 (nth 0 splitup)))
317 (prefix (if (nth 1 splitup)
318 (nth 0 splitup)
319 (caar xml-ns))))
321 (setcar attr (intern (concat "{"
322 (cdr (assoc-string prefix xml-ns))
323 "}" lname)))))
324 (car children)))
326 ;; is this an empty element ?
327 (if (looking-at "/>")
328 (progn
329 (forward-char 2)
330 (nreverse children))
332 ;; is this a valid start tag ?
333 (if (eq (char-after) ?>)
334 (progn
335 (forward-char 1)
336 ;; Now check that we have the right end-tag. Note that this
337 ;; one might contain spaces after the tag name
338 (let ((end (concat "</" node-name "\\s-*>")))
339 (while (not (looking-at end))
340 (cond
341 ((looking-at "</")
342 (error "XML: Invalid end tag (expecting %s) at pos %d"
343 node-name (point)))
344 ((= (char-after) ?<)
345 (let ((tag (xml-parse-tag nil xml-ns)))
346 (when tag
347 (push tag children))))
349 (setq pos (point))
350 (search-forward "<")
351 (forward-char -1)
352 (let ((string (buffer-substring pos (point)))
353 (pos 0))
355 ;; Clean up the string. As per XML
356 ;; specifications, the XML processor should
357 ;; always pass the whole string to the
358 ;; application. But \r's should be replaced:
359 ;; http://www.w3.org/TR/2000/REC-xml-20001006#sec-line-ends
360 (while (string-match "\r\n?" string pos)
361 (setq string (replace-match "\n" t t string))
362 (setq pos (1+ (match-beginning 0))))
364 (setq string (xml-substitute-special string))
365 (setq children
366 (if (stringp (car children))
367 ;; The two strings were separated by a comment.
368 (cons (concat (car children) string)
369 (cdr children))
370 (cons string children))))))))
372 (goto-char (match-end 0))
373 (nreverse children))
374 ;; This was an invalid start tag
375 (error "XML: Invalid attribute list")))))
376 (t ;; This is not a tag.
377 (error "XML: Invalid character")))))
379 (defun xml-parse-attlist ()
380 "Return the attribute-list after point.Leave point at the first non-blank character after the tag."
381 (let ((attlist ())
382 start-pos name)
383 (skip-syntax-forward " ")
384 (while (looking-at (eval-when-compile
385 (concat "\\(" xml-name-regexp "\\)\\s-*=\\s-*")))
386 (setq name (intern (match-string 1)))
387 (goto-char (match-end 0))
389 ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
391 ;; Do we have a string between quotes (or double-quotes),
392 ;; or a simple word ?
393 (if (looking-at "\"\\([^\"]*\\)\"")
394 (setq start-pos (match-beginning 0))
395 (if (looking-at "'\\([^']*\\)'")
396 (setq start-pos (match-beginning 0))
397 (error "XML: Attribute values must be given between quotes")))
399 ;; Each attribute must be unique within a given element
400 (if (assoc name attlist)
401 (error "XML: each attribute must be unique within an element"))
403 ;; Multiple whitespace characters should be replaced with a single one
404 ;; in the attributes
405 (let ((string (match-string 1))
406 (pos 0))
407 (replace-regexp-in-string "\\s-\\{2,\\}" " " string)
408 (push (cons name (xml-substitute-special string)) attlist))
410 (goto-char start-pos)
411 (forward-sexp) ; we have string syntax
413 (skip-syntax-forward " "))
414 (nreverse attlist)))
416 ;;*******************************************************************
417 ;;**
418 ;;** The DTD (document type declaration)
419 ;;** The following functions know how to skip or parse the DTD of
420 ;;** a document
421 ;;**
422 ;;*******************************************************************
424 ;; Fixme: This fails at least if the DTD contains conditional sections.
426 (defun xml-skip-dtd ()
427 "Skip the DTD at point.
428 This follows the rule [28] in the XML specifications."
429 (forward-char (length "<!DOCTYPE"))
430 (if (looking-at "\\s-*>")
431 (error "XML: invalid DTD (excepting name of the document)"))
432 (condition-case nil
433 (progn
434 (forward-sexp)
435 (skip-syntax-forward " ")
436 (if (looking-at "\\[")
437 (re-search-forward "]\\s-*>")
438 (search-forward ">")))
439 (error (error "XML: No end to the DTD"))))
441 (defun xml-parse-dtd ()
442 "Parse the DTD at point."
443 (forward-char (eval-when-compile (length "<!DOCTYPE")))
444 (skip-syntax-forward " ")
445 (if (looking-at ">")
446 (error "XML: invalid DTD (excepting name of the document)"))
448 ;; Get the name of the document
449 (looking-at xml-name-regexp)
450 (let ((dtd (list (match-string 0) 'dtd))
451 type element end-pos)
452 (goto-char (match-end 0))
454 (skip-syntax-forward " ")
455 ;; XML [75]
456 (cond ((looking-at "PUBLIC\\s-+")
457 (goto-char (match-end 0))
458 (unless (or (re-search-forward
459 "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
460 nil t)
461 (re-search-forward
462 "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
463 nil t))
464 (error "XML: missing public id"))
465 (let ((pubid (match-string 1)))
466 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
467 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
468 (error "XML: missing system id"))
469 (push (list pubid (match-string 1) 'public) dtd)))
470 ((looking-at "SYSTEM\\s-+")
471 (goto-char (match-end 0))
472 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
473 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
474 (error "XML: missing system id"))
475 (push (list (match-string 1) 'system) dtd)))
476 (skip-syntax-forward " ")
477 (if (eq ?> (char-after))
478 (forward-char)
479 (skip-syntax-forward " ")
480 (if (not (eq (char-after) ?\[))
481 (error "XML: bad DTD")
482 (forward-char)
483 ;; Parse the rest of the DTD
484 ;; Fixme: Deal with ENTITY, ATTLIST, NOTATION, PIs.
485 (while (not (looking-at "\\s-*\\]"))
486 (skip-syntax-forward " ")
487 (cond
489 ;; Translation of rule [45] of XML specifications
490 ((looking-at
491 "<!ELEMENT\\s-+\\([[:alnum:].%;]+\\)\\s-+\\([^>]+\\)>")
493 (setq element (intern (match-string 1))
494 type (match-string-no-properties 2))
495 (setq end-pos (match-end 0))
497 ;; Translation of rule [46] of XML specifications
498 (cond
499 ((string-match "^EMPTY[ \t\n\r]*$" type) ;; empty declaration
500 (setq type 'empty))
501 ((string-match "^ANY[ \t\n\r]*$" type) ;; any type of contents
502 (setq type 'any))
503 ((string-match "^(\\(.*\\))[ \t\n\r]*$" type) ;; children ([47])
504 (setq type (xml-parse-elem-type (match-string 1 type))))
505 ((string-match "^%[^;]+;[ \t\n\r]*$" type) ;; substitution
506 nil)
508 (error "XML: Invalid element type in the DTD")))
510 ;; rule [45]: the element declaration must be unique
511 (if (assoc element dtd)
512 (error "XML: element declarations must be unique in a DTD (<%s>)"
513 (symbol-name element)))
515 ;; Store the element in the DTD
516 (push (list element type) dtd)
517 (goto-char end-pos))
518 ((looking-at "<!--")
519 (search-forward "-->"))
522 (error "XML: Invalid DTD item")))
524 ;; Skip the end of the DTD
525 (search-forward ">"))))
526 (nreverse dtd)))
529 (defun xml-parse-elem-type (string)
530 "Convert element type STRING into a Lisp structure."
532 (let (elem modifier)
533 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
534 (progn
535 (setq elem (match-string 1 string)
536 modifier (match-string 2 string))
537 (if (string-match "|" elem)
538 (setq elem (cons 'choice
539 (mapcar 'xml-parse-elem-type
540 (split-string elem "|"))))
541 (if (string-match "," elem)
542 (setq elem (cons 'seq
543 (mapcar 'xml-parse-elem-type
544 (split-string elem ",")))))))
545 (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string)
546 (setq elem (match-string 1 string)
547 modifier (match-string 2 string))))
549 (if (and (stringp elem) (string= elem "#PCDATA"))
550 (setq elem 'pcdata))
552 (cond
553 ((string= modifier "+")
554 (list '+ elem))
555 ((string= modifier "*")
556 (list '* elem))
557 ((string= modifier "?")
558 (list '\? elem))
560 elem))))
562 ;;*******************************************************************
563 ;;**
564 ;;** Substituting special XML sequences
565 ;;**
566 ;;*******************************************************************
568 (eval-when-compile
569 (defvar str)) ; dynamic from replace-regexp-in-string
571 ;; Fixme: Take declared entities from the DTD when they're available.
572 (defun xml-substitute-entity (match)
573 "Subroutine of xml-substitute-special."
574 (save-match-data
575 (let ((match1 (match-string 1 str)))
576 (cond ((string= match1 "lt") "<")
577 ((string= match1 "gt") ">")
578 ((string= match1 "apos") "'")
579 ((string= match1 "quot") "\"")
580 ((string= match1 "amp") "&")
581 ((and (string-match "#\\([0-9]+\\)" match1)
582 (let ((c (decode-char
583 'ucs
584 (string-to-number (match-string 1 match1)))))
585 (if c (string c))))) ; else unrepresentable
586 ((and (string-match "#x\\([[:xdigit:]]+\\)" match1)
587 (let ((c (decode-char
588 'ucs
589 (string-to-number (match-string 1 match1) 16))))
590 (if c (string c)))))
591 ;; Default to asis. Arguably, unrepresentable code points
592 ;; might be best replaced with U+FFFD.
593 (t match)))))
595 (defun xml-substitute-special (string)
596 "Return STRING, after subsituting entity references."
597 ;; This originally made repeated passes through the string from the
598 ;; beginning, which isn't correct, since then either "&amp;amp;" or
599 ;; "&#38;amp;" won't DTRT.
600 (replace-regexp-in-string "&\\([^;]+\\);"
601 #'xml-substitute-entity string t t))
603 ;;*******************************************************************
604 ;;**
605 ;;** Printing a tree.
606 ;;** This function is intended mainly for debugging purposes.
607 ;;**
608 ;;*******************************************************************
610 (defun xml-debug-print (xml)
611 (dolist (node xml)
612 (xml-debug-print-internal node "")))
614 (defun xml-debug-print-internal (xml indent-string)
615 "Outputs the XML tree in the current buffer.
616 The first line is indented with INDENT-STRING."
617 (let ((tree xml)
618 attlist)
619 (insert indent-string ?< (symbol-name (xml-node-name tree)))
621 ;; output the attribute list
622 (setq attlist (xml-node-attributes tree))
623 (while attlist
624 (insert ?\ (symbol-name (caar attlist)) "=\"" (cdar attlist) ?\")
625 (setq attlist (cdr attlist)))
627 (insert ?>)
629 (setq tree (xml-node-children tree))
631 ;; output the children
632 (dolist (node tree)
633 (cond
634 ((listp node)
635 (insert ?\n)
636 (xml-debug-print-internal node (concat indent-string " ")))
637 ((stringp node) (insert node))
639 (error "Invalid XML tree"))))
641 (insert ?\n indent-string
642 ?< ?/ (symbol-name (xml-node-name xml)) ?>)))
644 (provide 'xml)
646 ;;; arch-tag: 5864b283-5a68-4b59-a20d-36a72b353b9b
647 ;;; xml.el ends here