(ibuffer-backward-line, ibuffer-forward-line)
[emacs.git] / lisp / xml.el
blobf62b70fceb453a0f389cd53d3e03f6839a50e9ed
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)
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 (nreverse children))
279 ;; is this a valid start tag ?
280 (if (eq (char-after) ?>)
281 (progn
282 (forward-char 1)
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))
287 (cond
288 ((looking-at "</")
289 (error "XML: Invalid end tag (expecting %s) at pos %d"
290 node-name (point)))
291 ((= (char-after) ?<)
292 (let ((tag (xml-parse-tag)))
293 (when tag
294 (push tag children))))
296 (setq pos (point))
297 (search-forward "<")
298 (forward-char -1)
299 (let ((string (buffer-substring pos (point)))
300 (pos 0))
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))
312 (setq children
313 (if (stringp (car children))
314 ;; The two strings were separated by a comment.
315 (cons (concat (car children) string)
316 (cdr children))
317 (cons string children))))))))
319 (goto-char (match-end 0))
320 (nreverse children))
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."
329 (let ((attlist ())
330 start-pos name)
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
352 ;; in the attributes
353 (let ((string (match-string 1))
354 (pos 0))
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 " "))
362 (nreverse attlist)))
364 ;;*******************************************************************
365 ;;**
366 ;;** The DTD (document type declaration)
367 ;;** The following functions know how to skip or parse the DTD of
368 ;;** a document
369 ;;**
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)"))
380 (condition-case nil
381 (progn
382 (forward-sexp)
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 " ")
393 (if (looking-at ">")
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 " ")
403 ;; XML [75]
404 (cond ((looking-at "PUBLIC\\s-+")
405 (goto-char (match-end 0))
406 (unless (or (re-search-forward
407 "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
408 nil t)
409 (re-search-forward
410 "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
411 nil t))
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))
426 (forward-char)
427 (skip-syntax-forward " ")
428 (if (not (eq (char-after) ?\[))
429 (error "XML: bad DTD")
430 (forward-char)
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 " ")
435 (cond
437 ;; Translation of rule [45] of XML specifications
438 ((looking-at
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
446 (cond
447 ((string-match "^EMPTY[ \t\n\r]*$" type) ;; empty declaration
448 (setq type 'empty))
449 ((string-match "^ANY[ \t\n\r]*$" type) ;; any type of contents
450 (setq type 'any))
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
454 nil)
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)
465 (goto-char end-pos))
466 ((looking-at "<!--")
467 (search-forward "-->"))
470 (error "XML: Invalid DTD item")))
472 ;; Skip the end of the DTD
473 (search-forward ">"))))
474 (nreverse dtd)))
477 (defun xml-parse-elem-type (string)
478 "Convert element type STRING into a Lisp structure."
480 (let (elem modifier)
481 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
482 (progn
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"))
498 (setq elem 'pcdata))
500 (cond
501 ((string= modifier "+")
502 (list '+ elem))
503 ((string= modifier "*")
504 (list '* elem))
505 ((string= modifier "?")
506 (list '\? elem))
508 elem))))
510 ;;*******************************************************************
511 ;;**
512 ;;** Substituting special XML sequences
513 ;;**
514 ;;*******************************************************************
516 (eval-when-compile
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."
522 (save-match-data
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
531 'ucs
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
536 'ucs
537 (string-to-number (match-string 1 match1) 16))))
538 (if c (string c)))))
539 ;; Default to asis. Arguably, unrepresentable code points
540 ;; might be best replaced with U+FFFD.
541 (t match)))))
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;amp;" or
547 ;; "&#38;amp;" won't DTRT.
548 (replace-regexp-in-string "&\\([^;]+\\);"
549 #'xml-substitute-entity string t t))
551 ;;*******************************************************************
552 ;;**
553 ;;** Printing a tree.
554 ;;** This function is intended mainly for debugging purposes.
555 ;;**
556 ;;*******************************************************************
558 (defun xml-debug-print (xml)
559 (dolist (node 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."
565 (let ((tree xml)
566 attlist)
567 (insert indent-string ?< (symbol-name (xml-node-name tree)))
569 ;; output the attribute list
570 (setq attlist (xml-node-attributes tree))
571 (while attlist
572 (insert ?\ (symbol-name (caar attlist)) "=\"" (cdar attlist) ?\")
573 (setq attlist (cdr attlist)))
575 (insert ?>)
577 (setq tree (xml-node-children tree))
579 ;; output the children
580 (dolist (node tree)
581 (cond
582 ((listp node)
583 (insert ?\n)
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)) ?>)))
592 (provide 'xml)
594 ;;; xml.el ends here