Make (many) trivial substitutions for renamed and
[emacs/old-mirror.git] / lisp / xml.el
blob01d1afa3b051dc5b05f31e7fc65076ced2325b93
1 ;;; xml.el --- XML parser
3 ;; Copyright (C) 2000, 2001, 2003 Free Software Foundation, Inc.
5 ;; Author: Emmanuel Briot <briot@gnat.com>
6 ;; Maintainer: FSF
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)
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 (let ((keep))
130 (if (get-file-buffer file)
131 (progn
132 (set-buffer (get-file-buffer file))
133 (setq keep (point)))
134 (let (auto-mode-alist) ; no need for xml-mode
135 (find-file file)))
137 (let ((xml (xml-parse-region (point-min)
138 (point-max)
139 (current-buffer)
140 parse-dtd)))
141 (if keep
142 (goto-char keep)
143 (kill-buffer (current-buffer)))
144 xml)))
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].
157 (dotimes (c 31)
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)
168 ;; XML [89]
169 (dolist (c '(#x00B7 #x02D0 #x02D1 #x0387 #x0640 #x0E46 #x0EC6 #x3005
170 #x3031 #x3032 #x3033 #x3034 #x3035 #x309D #x309E #x30FC
171 #x30FD #x30FE))
172 (modify-syntax-entry (decode-char 'ucs c) "w" table))
173 ;; Fixme: rest of [4]
174 table)
175 "Syntax table used by `xml-parse-region'.")
177 ;; XML [5]
178 ;; Note that [:alpha:] matches all multibyte chars with word syntax.
179 (eval-and-compile
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*)?
186 ;;;###autoload
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."
194 (save-restriction
195 (narrow-to-region beg end)
196 ;; Use fixed syntax table to ensure regexp char classes and syntax
197 ;; specs DTRT.
198 (with-syntax-table (standard-syntax-table)
199 (let ((case-fold-search nil) ; XML is case-sensitive.
200 xml result dtd)
201 (save-excursion
202 (if buffer
203 (set-buffer buffer))
204 (goto-char (point-min))
205 (while (not (eobp))
206 (if (search-forward "<" nil t)
207 (progn
208 (forward-char -1)
209 (if xml
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))
213 (cond
214 ((null result))
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))))
222 (if parse-dtd
223 (cons dtd (nreverse xml))
224 (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.
231 Returns one of:
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."
235 (cond
236 ;; Processing instructions (like the <?xml version="1.0"?> tag at the
237 ;; beginning of a document).
238 ((looking-at "<\\?")
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")
250 (let (dtd)
251 (if parse-dtd
252 (setq dtd (xml-parse-dtd))
253 (xml-skip-dtd))
254 (skip-syntax-forward " ")
255 (if dtd
256 (cons dtd (xml-parse-tag))
257 (xml-parse-tag))))
258 ;; skip comments
259 ((looking-at "<!--")
260 (search-forward "-->")
261 nil)
262 ;; end tag
263 ((looking-at "</")
264 '())
265 ;; opening tag
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)))
271 pos)
273 ;; is this an empty element ?
274 (if (looking-at "/>")
275 (progn
276 (forward-char 2)
277 ;; Fixme: Inconsistent with the nil content returned from
278 ;; `<tag></tag>'.
279 (nreverse (cons '("") children)))
281 ;; is this a valid start tag ?
282 (if (eq (char-after) ?>)
283 (progn
284 (forward-char 1)
285 ;; Now check that we have the right end-tag. Note that this
286 ;; one might contain spaces after the tag name
287 (let ((end (concat "</" node-name "\\s-*>")))
288 (while (not (looking-at end))
289 (cond
290 ((looking-at "</")
291 (error "XML: Invalid end tag (expecting %s) at pos %d"
292 node-name (point)))
293 ((= (char-after) ?<)
294 (let ((tag (xml-parse-tag)))
295 (when tag
296 (push tag children))))
298 (setq pos (point))
299 (search-forward "<")
300 (forward-char -1)
301 (let ((string (buffer-substring pos (point)))
302 (pos 0))
304 ;; Clean up the string. As per XML
305 ;; specifications, the XML processor should
306 ;; always pass the whole string to the
307 ;; application. But \r's should be replaced:
308 ;; http://www.w3.org/TR/2000/REC-xml-20001006#sec-line-ends
309 (while (string-match "\r\n?" string pos)
310 (setq string (replace-match "\n" t t string))
311 (setq pos (1+ (match-beginning 0))))
313 (setq string (xml-substitute-special string))
314 (setq children
315 (if (stringp (car children))
316 ;; The two strings were separated by a comment.
317 (cons (concat (car children) string)
318 (cdr children))
319 (cons string children))))))))
321 (goto-char (match-end 0))
322 (nreverse children))
323 ;; This was an invalid start tag
324 (error "XML: Invalid attribute list")))))
325 (t ;; This is not a tag.
326 (error "XML: Invalid character"))))
328 (defun xml-parse-attlist ()
329 "Return the attribute-list after point.
330 Leave point at the first non-blank character after the tag."
331 (let ((attlist ())
332 start-pos name)
333 (skip-syntax-forward " ")
334 (while (looking-at (eval-when-compile
335 (concat "\\(" xml-name-regexp "\\)\\s-*=\\s-*")))
336 (setq name (intern (match-string 1)))
337 (goto-char (match-end 0))
339 ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
341 ;; Do we have a string between quotes (or double-quotes),
342 ;; or a simple word ?
343 (if (looking-at "\"\\([^\"]*\\)\"")
344 (setq start-pos (match-beginning 0))
345 (if (looking-at "'\\([^']*\\)'")
346 (setq start-pos (match-beginning 0))
347 (error "XML: Attribute values must be given between quotes")))
349 ;; Each attribute must be unique within a given element
350 (if (assoc name attlist)
351 (error "XML: each attribute must be unique within an element"))
353 ;; Multiple whitespace characters should be replaced with a single one
354 ;; in the attributes
355 (let ((string (match-string 1))
356 (pos 0))
357 (replace-regexp-in-string "\\s-\\{2,\\}" " " string)
358 (push (cons name (xml-substitute-special string)) attlist))
360 (goto-char start-pos)
361 (forward-sexp) ; we have string syntax
363 (skip-syntax-forward " "))
364 (nreverse attlist)))
366 ;;*******************************************************************
367 ;;**
368 ;;** The DTD (document type declaration)
369 ;;** The following functions know how to skip or parse the DTD of
370 ;;** a document
371 ;;**
372 ;;*******************************************************************
374 ;; Fixme: This fails at least if the DTD contains conditional sections.
376 (defun xml-skip-dtd ()
377 "Skip the DTD at point.
378 This follows the rule [28] in the XML specifications."
379 (forward-char (length "<!DOCTYPE"))
380 (if (looking-at "\\s-*>")
381 (error "XML: invalid DTD (excepting name of the document)"))
382 (condition-case nil
383 (progn
384 (forward-sexp)
385 (skip-syntax-forward " ")
386 (if (looking-at "\\[")
387 (re-search-forward "]\\s-*>")
388 (search-forward ">")))
389 (error (error "XML: No end to the DTD"))))
391 (defun xml-parse-dtd ()
392 "Parse the DTD at point."
393 (forward-char (eval-when-compile (length "<!DOCTYPE")))
394 (skip-syntax-forward " ")
395 (if (looking-at ">")
396 (error "XML: invalid DTD (excepting name of the document)"))
398 ;; Get the name of the document
399 (looking-at xml-name-regexp)
400 (let ((dtd (list (match-string 0) 'dtd))
401 type element end-pos)
402 (goto-char (match-end 0))
404 (skip-syntax-forward " ")
405 ;; XML [75]
406 (cond ((looking-at "PUBLIC\\s-+")
407 (goto-char (match-end 0))
408 (unless (or (re-search-forward
409 "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
410 nil t)
411 (re-search-forward
412 "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
413 nil t))
414 (error "XML: missing public id"))
415 (let ((pubid (match-string 1)))
416 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
417 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
418 (error "XML: missing system id"))
419 (push (list pubid (match-string 1) 'public) dtd)))
420 ((looking-at "SYSTEM\\s-+")
421 (goto-char (match-end 0))
422 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
423 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
424 (error "XML: missing system id"))
425 (push (list (match-string 1) 'system) dtd)))
426 (skip-syntax-forward " ")
427 (if (eq ?> (char-after))
428 (forward-char)
429 (skip-syntax-forward " ")
430 (if (not (eq (char-after) ?\[))
431 (error "XML: bad DTD")
432 (forward-char)
433 ;; Parse the rest of the DTD
434 ;; Fixme: Deal with ENTITY, ATTLIST, NOTATION, PIs.
435 (while (not (looking-at "\\s-*\\]"))
436 (skip-syntax-forward " ")
437 (cond
439 ;; Translation of rule [45] of XML specifications
440 ((looking-at
441 "<!ELEMENT\\s-+\\([[:alnum:].%;]+\\)\\s-+\\([^>]+\\)>")
443 (setq element (intern (match-string 1))
444 type (match-string-no-properties 2))
445 (setq end-pos (match-end 0))
447 ;; Translation of rule [46] of XML specifications
448 (cond
449 ((string-match "^EMPTY[ \t\n\r]*$" type) ;; empty declaration
450 (setq type 'empty))
451 ((string-match "^ANY[ \t\n\r]*$" type) ;; any type of contents
452 (setq type 'any))
453 ((string-match "^(\\(.*\\))[ \t\n\r]*$" type) ;; children ([47])
454 (setq type (xml-parse-elem-type (match-string 1 type))))
455 ((string-match "^%[^;]+;[ \t\n\r]*$" type) ;; substitution
456 nil)
458 (error "XML: Invalid element type in the DTD")))
460 ;; rule [45]: the element declaration must be unique
461 (if (assoc element dtd)
462 (error "XML: element declarations must be unique in a DTD (<%s>)"
463 (symbol-name element)))
465 ;; Store the element in the DTD
466 (push (list element type) dtd)
467 (goto-char end-pos))
468 ((looking-at "<!--")
469 (search-forward "-->"))
472 (error "XML: Invalid DTD item")))
474 ;; Skip the end of the DTD
475 (search-forward ">"))))
476 (nreverse dtd)))
479 (defun xml-parse-elem-type (string)
480 "Convert element type STRING into a Lisp structure."
482 (let (elem modifier)
483 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
484 (progn
485 (setq elem (match-string 1 string)
486 modifier (match-string 2 string))
487 (if (string-match "|" elem)
488 (setq elem (cons 'choice
489 (mapcar 'xml-parse-elem-type
490 (split-string elem "|"))))
491 (if (string-match "," elem)
492 (setq elem (cons 'seq
493 (mapcar 'xml-parse-elem-type
494 (split-string elem ",")))))))
495 (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string)
496 (setq elem (match-string 1 string)
497 modifier (match-string 2 string))))
499 (if (and (stringp elem) (string= elem "#PCDATA"))
500 (setq elem 'pcdata))
502 (cond
503 ((string= modifier "+")
504 (list '+ elem))
505 ((string= modifier "*")
506 (list '* elem))
507 ((string= modifier "?")
508 (list '\? elem))
510 elem))))
512 ;;*******************************************************************
513 ;;**
514 ;;** Substituting special XML sequences
515 ;;**
516 ;;*******************************************************************
518 (eval-when-compile
519 (defvar str)) ; dynamic from replace-regexp-in-string
521 ;; Fixme: Take declared entities from the DTD when they're available.
522 (defun xml-substitute-entity (match)
523 "Subroutine of xml-substitute-special."
524 (save-match-data
525 (let ((match1 (match-string 1 str)))
526 (cond ((string= match1 "lt") "<")
527 ((string= match1 "gt") ">")
528 ((string= match1 "apos") "'")
529 ((string= match1 "quot") "\"")
530 ((string= match1 "amp") "&")
531 ((and (string-match "#\\([0-9]+\\)" match1)
532 (let ((c (decode-char
533 'ucs
534 (string-to-number (match-string 1 match1)))))
535 (if c (string c))))) ; else unrepresentable
536 ((and (string-match "#x\\([[:xdigit:]]+\\)" match1)
537 (let ((c (decode-char
538 'ucs
539 (string-to-number (match-string 1 match1) 16))))
540 (if c (string c)))))
541 ;; Default to asis. Arguably, unrepresentable code points
542 ;; might be best replaced with U+FFFD.
543 (t match)))))
545 (defun xml-substitute-special (string)
546 "Return STRING, after subsituting entity references."
547 ;; This originally made repeated passes through the string from the
548 ;; beginning, which isn't correct, since then either "&amp;amp;" or
549 ;; "&#38;amp;" won't DTRT.
550 (replace-regexp-in-string "&\\([^;]+\\);"
551 #'xml-substitute-entity string t t))
553 ;;*******************************************************************
554 ;;**
555 ;;** Printing a tree.
556 ;;** This function is intended mainly for debugging purposes.
557 ;;**
558 ;;*******************************************************************
560 (defun xml-debug-print (xml)
561 (dolist (node xml)
562 (xml-debug-print-internal node "")))
564 (defun xml-debug-print-internal (xml indent-string)
565 "Outputs the XML tree in the current buffer.
566 The first line is indented with INDENT-STRING."
567 (let ((tree xml)
568 attlist)
569 (insert indent-string ?< (symbol-name (xml-node-name tree)))
571 ;; output the attribute list
572 (setq attlist (xml-node-attributes tree))
573 (while attlist
574 (insert ?\ (symbol-name (caar attlist)) "=\"" (cdar attlist) ?\")
575 (setq attlist (cdr attlist)))
577 (insert ?>)
579 (setq tree (xml-node-children tree))
581 ;; output the children
582 (dolist (node tree)
583 (cond
584 ((listp node)
585 (insert ?\n)
586 (xml-debug-print-internal node (concat indent-string " ")))
587 ((stringp node) (insert node))
589 (error "Invalid XML tree"))))
591 (insert ?\n indent-string
592 ?< ?/ (symbol-name (xml-node-name xml)) ?>)))
594 (provide 'xml)
596 ;;; xml.el ends here