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>
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)
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.
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.
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
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>
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
51 ;; There can be only top level node, but with any number of children below.
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") ...)
67 ;; Some macros are provided to ease the parsing of this list.
68 ;; Whitespace is preserved. Fixme: There should be a tree-walker that
73 ;; Note that {buffer-substring,match-string}-no-properties were
74 ;; formerly used in several places, but that removes composition info.
76 ;;*******************************************************************
78 ;;** Macros to parse the list
80 ;;*******************************************************************
82 (defsubst xml-node-name
(node)
83 "Return the tag associated with NODE.
84 The tag is a lower-case symbol."
87 (defsubst xml-node-attributes
(node)
88 "Return the list of attributes of 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."
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."
101 (dolist (child (xml-node-children node
))
103 (if (equal (xml-node-name child
) child-name
)
104 (push child 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
))))
117 ;;*******************************************************************
119 ;;** Creating the list
121 ;;*******************************************************************
124 (defun xml-parse-file (file &optional parse-dtd
)
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."
130 (if (get-file-buffer file
)
132 (set-buffer (get-file-buffer file
))
134 (let (auto-mode-alist) ; no need for xml-mode
137 (let ((xml (xml-parse-region (point-min)
143 (kill-buffer (current-buffer)))
146 ;; Note that this is setup so that we can do whitespace-skipping with
147 ;; `(skip-syntax-forward " ")', inter alia. Previously this was slow
148 ;; compared with `re-search-forward', but that has been fixed. Also
149 ;; note that the standard syntax table contains other characters with
150 ;; whitespace syntax, like NBSP, but they are invalid in contexts in
151 ;; which we might skip whitespace -- specifically, they're not
152 ;; NameChars [XML 4].
154 (defvar xml-syntax-table
155 (let ((table (make-syntax-table)))
156 ;; Get space syntax correct per XML [3].
158 (modify-syntax-entry c
"." table
)) ; all are space in standard table
159 (dolist (c '(?
\t ?
\n ?
\r)) ; these should be space
160 (modify-syntax-entry c
" " table
))
161 ;; For skipping attributes.
162 (modify-syntax-entry ?
\" "\"" table
)
163 (modify-syntax-entry ?
' "\"" table
)
164 ;; Non-alnum name chars should be symbol constituents (`-' and `_'
165 ;; are OK by default).
166 (modify-syntax-entry ?.
"_" table
)
167 (modify-syntax-entry ?
: "_" table
)
169 (dolist (c '(#x00B7
#x02D0
#x02D1
#x0387
#x0640
#x0E46
#x0EC6
#x3005
170 #x3031
#x3032
#x3033
#x3034
#x3035
#x309D
#x309E
#x30FC
172 (modify-syntax-entry (decode-char 'ucs c
) "w" table
))
173 ;; Fixme: rest of [4]
175 "Syntax table used by `xml-parse-region'.")
178 ;; Note that [:alpha:] matches all multibyte chars with word syntax.
180 (defconst xml-name-regexp
"[[:alpha:]_:][[:alnum:]._:-]*"))
182 ;; Fixme: This needs re-writing to deal with the XML grammar properly, i.e.
183 ;; document ::= prolog element Misc*
184 ;; prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
187 (defun xml-parse-region (beg end
&optional buffer parse-dtd
)
188 "Parse the region from BEG to END in BUFFER.
189 If BUFFER is nil, it defaults to the current buffer.
190 Returns the XML list for the region, or raises an error if the region
191 is not a well-formed XML file.
192 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped,
193 and returned as the first element of the list."
195 (narrow-to-region beg end
)
196 ;; Use fixed syntax table to ensure regexp char classes and syntax
198 (with-syntax-table (standard-syntax-table)
199 (let ((case-fold-search nil
) ; XML is case-sensitive.
204 (goto-char (point-min))
206 (if (search-forward "<" nil t
)
210 ;; translation of rule [1] of XML specifications
211 (error "XML files can have only one toplevel tag")
212 (setq result
(xml-parse-tag parse-dtd
))
215 ((listp (car result
))
216 (setq dtd
(car result
))
217 (if (cdr result
) ; possible leading comment
218 (add-to-list 'xml
(cdr result
))))
220 (add-to-list 'xml result
)))))
221 (goto-char (point-max))))
223 (cons dtd
(nreverse xml
))
227 (defun xml-parse-tag (&optional parse-dtd
)
228 "Parse the tag at point.
229 If PARSE-DTD is non-nil, the DTD of the document, if any, is parsed and
230 returned as the first element in the list.
232 - a list : the matching node
233 - nil : the point is not looking at a tag.
234 - a pair : the first element is the DTD, the second is the node."
236 ;; Processing instructions (like the <?xml version="1.0"?> tag at the
237 ;; beginning of a document).
239 (search-forward "?>")
240 (skip-syntax-forward " ")
241 (xml-parse-tag parse-dtd
))
242 ;; Character data (CDATA) sections, in which no tag should be interpreted
243 ((looking-at "<!\\[CDATA\\[")
244 (let ((pos (match-end 0)))
245 (unless (search-forward "]]>" nil t
)
246 (error "CDATA section does not end anywhere in the document"))
247 (buffer-substring pos
(match-beginning 0))))
248 ;; DTD for the document
249 ((looking-at "<!DOCTYPE")
252 (setq dtd
(xml-parse-dtd))
254 (skip-syntax-forward " ")
256 (cons dtd
(xml-parse-tag))
260 (search-forward "-->")
266 ((looking-at "<\\([^/>[:space:]]+\\)")
267 (goto-char (match-end 1))
268 (let* ((node-name (match-string 1))
269 ;; Parse the attribute list.
270 (children (list (xml-parse-attlist) (intern node-name
)))
273 ;; is this an empty element ?
274 (if (looking-at "/>")
279 ;; is this a valid start tag ?
280 (if (eq (char-after) ?
>)
283 ;; Now check that we have the right end-tag. Note that this
284 ;; one might contain spaces after the tag name
285 (let ((end (concat "</" node-name
"\\s-*>")))
286 (while (not (looking-at end
))
289 (error "XML: Invalid end tag (expecting %s) at pos %d"
292 (let ((tag (xml-parse-tag)))
294 (push tag children
))))
299 (let ((string (buffer-substring pos
(point)))
302 ;; Clean up the string. As per XML
303 ;; specifications, the XML processor should
304 ;; always pass the whole string to the
305 ;; application. But \r's should be replaced:
306 ;; http://www.w3.org/TR/2000/REC-xml-20001006#sec-line-ends
307 (while (string-match "\r\n?" string pos
)
308 (setq string
(replace-match "\n" t t string
))
309 (setq pos
(1+ (match-beginning 0))))
311 (setq string
(xml-substitute-special string
))
313 (if (stringp (car children
))
314 ;; The two strings were separated by a comment.
315 (cons (concat (car children
) string
)
317 (cons string children
))))))))
319 (goto-char (match-end 0))
321 ;; This was an invalid start tag
322 (error "XML: Invalid attribute list")))))
323 (t ;; This is not a tag.
324 (error "XML: Invalid character"))))
326 (defun xml-parse-attlist ()
327 "Return the attribute-list after point.
328 Leave point at the first non-blank character after the tag."
331 (skip-syntax-forward " ")
332 (while (looking-at (eval-when-compile
333 (concat "\\(" xml-name-regexp
"\\)\\s-*=\\s-*")))
334 (setq name
(intern (match-string 1)))
335 (goto-char (match-end 0))
337 ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
339 ;; Do we have a string between quotes (or double-quotes),
340 ;; or a simple word ?
341 (if (looking-at "\"\\([^\"]*\\)\"")
342 (setq start-pos
(match-beginning 0))
343 (if (looking-at "'\\([^']*\\)'")
344 (setq start-pos
(match-beginning 0))
345 (error "XML: Attribute values must be given between quotes")))
347 ;; Each attribute must be unique within a given element
348 (if (assoc name attlist
)
349 (error "XML: each attribute must be unique within an element"))
351 ;; Multiple whitespace characters should be replaced with a single one
353 (let ((string (match-string 1))
355 (replace-regexp-in-string "\\s-\\{2,\\}" " " string
)
356 (push (cons name
(xml-substitute-special string
)) attlist
))
358 (goto-char start-pos
)
359 (forward-sexp) ; we have string syntax
361 (skip-syntax-forward " "))
364 ;;*******************************************************************
366 ;;** The DTD (document type declaration)
367 ;;** The following functions know how to skip or parse the DTD of
370 ;;*******************************************************************
372 ;; Fixme: This fails at least if the DTD contains conditional sections.
374 (defun xml-skip-dtd ()
375 "Skip the DTD at point.
376 This follows the rule [28] in the XML specifications."
377 (forward-char (length "<!DOCTYPE"))
378 (if (looking-at "\\s-*>")
379 (error "XML: invalid DTD (excepting name of the document)"))
383 (skip-syntax-forward " ")
384 (if (looking-at "\\[")
385 (re-search-forward "]\\s-*>")
386 (search-forward ">")))
387 (error (error "XML: No end to the DTD"))))
389 (defun xml-parse-dtd ()
390 "Parse the DTD at point."
391 (forward-char (eval-when-compile (length "<!DOCTYPE")))
392 (skip-syntax-forward " ")
394 (error "XML: invalid DTD (excepting name of the document)"))
396 ;; Get the name of the document
397 (looking-at xml-name-regexp
)
398 (let ((dtd (list (match-string 0) 'dtd
))
399 type element end-pos
)
400 (goto-char (match-end 0))
402 (skip-syntax-forward " ")
404 (cond ((looking-at "PUBLIC\\s-+")
405 (goto-char (match-end 0))
406 (unless (or (re-search-forward
407 "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
410 "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
412 (error "XML: missing public id"))
413 (let ((pubid (match-string 1)))
414 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t
)
415 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t
))
416 (error "XML: missing system id"))
417 (push (list pubid
(match-string 1) 'public
) dtd
)))
418 ((looking-at "SYSTEM\\s-+")
419 (goto-char (match-end 0))
420 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t
)
421 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t
))
422 (error "XML: missing system id"))
423 (push (list (match-string 1) 'system
) dtd
)))
424 (skip-syntax-forward " ")
425 (if (eq ?
> (char-after))
427 (skip-syntax-forward " ")
428 (if (not (eq (char-after) ?\
[))
429 (error "XML: bad DTD")
431 ;; Parse the rest of the DTD
432 ;; Fixme: Deal with ENTITY, ATTLIST, NOTATION, PIs.
433 (while (not (looking-at "\\s-*\\]"))
434 (skip-syntax-forward " ")
437 ;; Translation of rule [45] of XML specifications
439 "<!ELEMENT\\s-+\\([[:alnum:].%;]+\\)\\s-+\\([^>]+\\)>")
441 (setq element
(intern (match-string 1))
442 type
(match-string-no-properties 2))
443 (setq end-pos
(match-end 0))
445 ;; Translation of rule [46] of XML specifications
447 ((string-match "^EMPTY[ \t\n\r]*$" type
) ;; empty declaration
449 ((string-match "^ANY[ \t\n\r]*$" type
) ;; any type of contents
451 ((string-match "^(\\(.*\\))[ \t\n\r]*$" type
) ;; children ([47])
452 (setq type
(xml-parse-elem-type (match-string 1 type
))))
453 ((string-match "^%[^;]+;[ \t\n\r]*$" type
) ;; substitution
456 (error "XML: Invalid element type in the DTD")))
458 ;; rule [45]: the element declaration must be unique
459 (if (assoc element dtd
)
460 (error "XML: element declarations must be unique in a DTD (<%s>)"
461 (symbol-name element
)))
463 ;; Store the element in the DTD
464 (push (list element type
) dtd
)
467 (search-forward "-->"))
470 (error "XML: Invalid DTD item")))
472 ;; Skip the end of the DTD
473 (search-forward ">"))))
477 (defun xml-parse-elem-type (string)
478 "Convert element type STRING into a Lisp structure."
481 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string
)
483 (setq elem
(match-string 1 string
)
484 modifier
(match-string 2 string
))
485 (if (string-match "|" elem
)
486 (setq elem
(cons 'choice
487 (mapcar 'xml-parse-elem-type
488 (split-string elem
"|"))))
489 (if (string-match "," elem
)
490 (setq elem
(cons 'seq
491 (mapcar 'xml-parse-elem-type
492 (split-string elem
",")))))))
493 (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string
)
494 (setq elem
(match-string 1 string
)
495 modifier
(match-string 2 string
))))
497 (if (and (stringp elem
) (string= elem
"#PCDATA"))
501 ((string= modifier
"+")
503 ((string= modifier
"*")
505 ((string= modifier
"?")
510 ;;*******************************************************************
512 ;;** Substituting special XML sequences
514 ;;*******************************************************************
517 (defvar str
)) ; dynamic from replace-regexp-in-string
519 ;; Fixme: Take declared entities from the DTD when they're available.
520 (defun xml-substitute-entity (match)
521 "Subroutine of xml-substitute-special."
523 (let ((match1 (match-string 1 str
)))
524 (cond ((string= match1
"lt") "<")
525 ((string= match1
"gt") ">")
526 ((string= match1
"apos") "'")
527 ((string= match1
"quot") "\"")
528 ((string= match1
"amp") "&")
529 ((and (string-match "#\\([0-9]+\\)" match1
)
530 (let ((c (decode-char
532 (string-to-number (match-string 1 match1
)))))
533 (if c
(string c
))))) ; else unrepresentable
534 ((and (string-match "#x\\([[:xdigit:]]+\\)" match1
)
535 (let ((c (decode-char
537 (string-to-number (match-string 1 match1
) 16))))
539 ;; Default to asis. Arguably, unrepresentable code points
540 ;; might be best replaced with U+FFFD.
543 (defun xml-substitute-special (string)
544 "Return STRING, after subsituting entity references."
545 ;; This originally made repeated passes through the string from the
546 ;; beginning, which isn't correct, since then either "&amp;" or
547 ;; "&amp;" won't DTRT.
548 (replace-regexp-in-string "&\\([^;]+\\);"
549 #'xml-substitute-entity string t t
))
551 ;;*******************************************************************
553 ;;** Printing a tree.
554 ;;** This function is intended mainly for debugging purposes.
556 ;;*******************************************************************
558 (defun xml-debug-print (xml)
560 (xml-debug-print-internal node
"")))
562 (defun xml-debug-print-internal (xml indent-string
)
563 "Outputs the XML tree in the current buffer.
564 The first line is indented with INDENT-STRING."
567 (insert indent-string ?
< (symbol-name (xml-node-name tree
)))
569 ;; output the attribute list
570 (setq attlist
(xml-node-attributes tree
))
572 (insert ?\
(symbol-name (caar attlist
)) "=\"" (cdar attlist
) ?
\")
573 (setq attlist
(cdr attlist
)))
577 (setq tree
(xml-node-children tree
))
579 ;; output the children
584 (xml-debug-print-internal node
(concat indent-string
" ")))
585 ((stringp node
) (insert node
))
587 (error "Invalid XML tree"))))
589 (insert ?
\n indent-string
590 ?
< ?
/ (symbol-name (xml-node-name xml
)) ?
>)))