25851e2a9ea174d9eb7cf7f99b4134a94fe133cb
[elisp/gnus.git-] / contrib / xml.el
1 ;; @(#) xml.el --- XML parser
2
3 ;; Copyright (C) 2000 Free Software Foundation, Inc.
4
5 ;; Author: Emmanuel Briot  <briot@gnat.com>
6 ;; Maintainer: Emmanuel Briot <briot@gnat.com>
7 ;; Keywords: xml
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 2, or (at your option)
14 ;; 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; 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.
25
26 ;;; Commentary:
27
28 ;; This file contains a full XML parser. It parses a file, and returns a list
29 ;; that can be used internally by any other lisp file.
30 ;; See some example in todo.el
31
32 ;;; FILE FORMAT
33
34 ;; It does not parse the DTD, if present in the XML file, but knows how to
35 ;; ignore it. The XML file is assumed to be well-formed. In case of error, the
36 ;; parsing stops and the XML file is shown where the parsing stopped.
37 ;;
38 ;; It also knows how to ignore comments, as well as the special ?xml? tag
39 ;; in the XML file.
40 ;;
41 ;; The XML file should have the following format:
42 ;;    <node1 attr1="name1" attr2="name2" ...>value
43 ;;       <node2 attr3="name3" attr4="name4">value2</node2>
44 ;;       <node3 attr5="name5" attr6="name6">value3</node3>
45 ;;    </node1>
46 ;; Of course, the name of the nodes and attributes can be anything. There can
47 ;; be any number of attributes (or none), as well as any number of children
48 ;; below the nodes.
49 ;;
50 ;; There can be only top level node, but with any number of children below.
51
52 ;;; LIST FORMAT
53
54 ;; The functions `xml-parse-file' and `xml-parse-tag' return a list with
55 ;; the following format:
56 ;;
57 ;;    xml-list   ::= (node node ...)
58 ;;    node       ::= (tag_name attribute-list . child_node_list)
59 ;;    child_node_list ::= child_node child_node ...
60 ;;    child_node ::= node | string
61 ;;    tag_name   ::= string
62 ;;    attribute_list ::= (("attribute" . "value") ("attribute" . "value") ...)
63 ;;                       | nil
64 ;;    string     ::= "..."
65 ;;
66 ;; Some macros are provided to ease the parsing of this list
67
68 ;;; Code:
69
70 ;;*******************************************************************
71 ;;**
72 ;;**  Macros to parse the list
73 ;;**
74 ;;*******************************************************************
75
76 (defmacro xml-node-name       (node)
77   "Return the tag associated with NODE.
78 The tag is a lower-case symbol."
79   (list 'car node))
80
81 (defmacro xml-node-attributes (node)
82   "Return the list of attributes of NODE.
83 The list can be nil."
84   (list 'nth 1 node))
85
86 (defmacro xml-node-children   (node)
87   "Return the list of children of NODE.
88 This is a list of nodes, and it can be nil."
89   (list 'cddr node))
90
91 (defun xml-get-children (node child-name)
92   "Return the children of NODE whose tag is CHILD-NAME.
93 CHILD-NAME should be a lower case symbol."
94   (let ((children (xml-node-children node))
95         match)
96     (while children
97       (if (car children)
98           (if (equal (xml-node-name (car children)) child-name)
99               (set 'match (append match (list (car children))))))
100       (set 'children (cdr children)))
101     match))
102
103 (defun xml-get-attribute (node attribute)
104   "Get from NODE the value of ATTRIBUTE.
105 An empty string is returned if the attribute was not found."
106   (if (xml-node-attributes node)
107       (let ((value (assoc attribute (xml-node-attributes node))))
108         (if value
109             (cdr value)
110           ""))
111     ""))
112
113 ;;*******************************************************************
114 ;;**
115 ;;**  Creating the list
116 ;;**
117 ;;*******************************************************************
118
119 (defun xml-parse-file (file &optional parse-dtd)
120   "Parse the well-formed XML FILE.
121 If FILE is already edited, this will keep the buffer alive.
122 Returns the top node with all its children.
123 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped."
124   (let ((keep))
125     (if (get-file-buffer file)
126         (progn
127           (set-buffer (get-file-buffer file))
128           (setq keep (point)))
129       (find-file file))
130     
131     (let ((xml (xml-parse-region (point-min)
132                                  (point-max)
133                                  (current-buffer)
134                                  parse-dtd)))
135       (if keep
136           (goto-char keep)
137         (kill-buffer (current-buffer)))
138       xml)))
139
140 (defun xml-parse-region (beg end &optional buffer parse-dtd)
141   "Parse the region from BEG to END in BUFFER.
142 If BUFFER is nil, it defaults to the current buffer.
143 Returns the XML list for the region, or raises an error if the region
144 is not a well-formed XML file.
145 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped,
146 and returned as the first element of the list"
147   (let (xml result dtd)
148     (save-excursion
149       (if buffer
150           (set-buffer buffer))
151       (goto-char beg)
152       (while (< (point) end)
153         (if (search-forward "<" end t)
154             (progn
155               (forward-char -1)
156               (if (null xml)
157                   (progn
158                     (set 'result (xml-parse-tag end parse-dtd))
159                     (cond
160                      ((listp (car result))
161                       (set 'dtd (car result))
162                       (add-to-list 'xml (cdr result)))
163                      (t
164                       (add-to-list 'xml result))))
165
166                 ;;  translation of rule [1] of XML specifications
167                 (error "XML files can have only one toplevel tag.")))
168           (goto-char end)))
169       (if parse-dtd
170           (cons dtd (reverse xml))
171         (reverse xml)))))
172
173
174 (defun xml-parse-tag (end &optional parse-dtd)
175   "Parse the tag that is just in front of point.
176 The end tag must be found before the position END in the current buffer.
177 If PARSE-DTD is non-nil, the DTD of the document, if any, is parsed and
178 returned as the first element in the list.
179 Returns one of:
180    - a list : the matching node
181    - nil    : the point is not looking at a tag.
182    - a cons cell: the first element is the DTD, the second is the node"
183   (cond
184    ;; Processing instructions (like the <?xml version="1.0"?> tag at the
185    ;; beginning of a document)
186    ((looking-at "<\\?")
187     (search-forward "?>" end)
188     (skip-chars-forward " \t\n")
189     (xml-parse-tag end))
190    ;;  Character data (CDATA) sections, in which no tag should be interpreted
191    ((looking-at "<!\\[CDATA\\[")
192     (let ((pos (match-end 0)))
193       (unless (search-forward "]]>" end t)
194         (error "CDATA section does not end anywhere in the document"))
195       (buffer-substring-no-properties pos (match-beginning 0))))
196    ;;  DTD for the document
197    ((looking-at "<!DOCTYPE")
198     (let (dtd)
199       (if parse-dtd
200           (set 'dtd (xml-parse-dtd end))
201         (xml-skip-dtd end))
202       (skip-chars-forward " \t\n")
203       (if dtd
204           (cons dtd (xml-parse-tag end))
205         (xml-parse-tag end))))
206    ;;  skip comments
207    ((looking-at "<!--")
208     (search-forward "-->" end)
209     (skip-chars-forward " \t\n")
210     (xml-parse-tag end))
211    ;;  end tag
212    ((looking-at "</")
213     '())
214    ;;  opening tag
215    ((looking-at "<\\([^/> \t\n]+\\)")
216     (let* ((node-name (match-string 1))
217            (children (list (intern node-name)))
218            (case-fold-search nil) ;; XML is case-sensitive
219            pos)
220       (goto-char (match-end 1))
221
222       ;; parses the attribute list
223       (set 'children (append children (list (xml-parse-attlist end))))
224
225       ;; is this an empty element ?
226       (if (looking-at "/>")
227           (progn
228             (forward-char 2)
229             (skip-chars-forward " \t\n")
230             (append children '("")))
231
232         ;; is this a valid start tag ?
233         (if (= (char-after) ?>)
234             (progn
235               (forward-char 1)
236               (skip-chars-forward " \t\n")
237               ;;  Now check that we have the right end-tag. Note that this one might
238               ;;  contain spaces after the tag name
239               (while (not (looking-at (concat "</" node-name "[ \t\n]*>")))
240                 (cond
241                  ((looking-at "</")
242                   (error (concat
243                           "XML: invalid syntax -- invalid end tag (expecting "
244                           node-name
245                           ") at pos " (number-to-string (point)))))
246                  ((= (char-after) ?<)
247                   (set 'children (append children (list (xml-parse-tag end)))))
248                  (t
249                   (set 'pos (point))
250                   (search-forward "<" end)
251                   (forward-char -1)
252                   (let ((string (buffer-substring-no-properties pos (point)))
253                         (pos 0))
254                     
255                     ;; Clean up the string (no newline characters)
256                     ;; Not done, since as per XML specifications, the XML processor
257                     ;; should always pass the whole string to the application.
258                     ;;      (while (string-match "\\s +" string pos)
259                     ;;        (set 'string (replace-match " " t t string))
260                     ;;        (set 'pos (1+ (match-beginning 0))))
261                     
262                     (set 'children (append children
263                                            (list (xml-substitute-special string))))))))
264               (goto-char (match-end 0))
265               (skip-chars-forward " \t\n")
266               (if (> (point) end)
267                   (error "XML: End tag for %s not found before end of region."
268                          node-name))
269               children
270               )
271
272           ;;  This was an invalid start tag
273           (error "XML: Invalid attribute list")
274           ))))
275    ))
276
277 (defun xml-parse-attlist (end)
278   "Return the attribute-list that point is looking at.
279 The search for attributes end at the position END in the current buffer.
280 Leaves the point on the first non-blank character after the tag."
281   (let ((attlist '())
282         name)
283     (skip-chars-forward " \t\n")
284     (while (looking-at "\\([a-zA-Z_:][-a-zA-Z0-9._:]*\\)[ \t\n]*=[ \t\n]*")
285       (set 'name (intern (match-string 1)))
286       (goto-char (match-end 0))
287
288       ;; Do we have a string between quotes (or double-quotes),
289       ;;  or a simple word ?
290       (unless (looking-at "\"\\([^\"]+\\)\"")
291         (unless (looking-at "'\\([^\"]+\\)'")
292           (error "XML: Attribute values must be given between quotes.")))
293
294       ;; Each attribute must be unique within a given element
295       (if (assoc name attlist)
296           (error "XML: each attribute must be unique within an element."))
297       
298       (set 'attlist (append attlist
299                             (list (cons name (match-string-no-properties 1)))))
300       (goto-char (match-end 0))
301       (skip-chars-forward " \t\n")
302       (if (> (point) end)
303           (error "XML: end of attribute list not found before end of region."))
304       )
305     attlist
306     ))
307
308 ;;*******************************************************************
309 ;;**
310 ;;**  The DTD (document type declaration)
311 ;;**  The following functions know how to skip or parse the DTD of
312 ;;**  a document
313 ;;**
314 ;;*******************************************************************
315
316 (defun xml-skip-dtd (end)
317   "Skip the DTD that point is looking at.
318 The DTD must end before the position END in the current buffer.
319 The point must be just before the starting tag of the DTD.
320 This follows the rule [28] in the XML specifications."
321   (forward-char (length "<!DOCTYPE"))
322   (if (looking-at "[ \t\n]*>")
323       (error "XML: invalid DTD (excepting name of the document)"))
324   (condition-case nil
325       (progn
326         (forward-word 1)  ;; name of the document
327         (skip-chars-forward " \t\n")
328         (if (looking-at "\\[")
329             (re-search-forward "\\][ \t\n]*>" end)
330           (search-forward ">" end)))
331     (error (error "XML: No end to the DTD"))))
332
333 (defun xml-parse-dtd (end)
334   "Parse the DTD that point is looking at.
335 The DTD must end before the position END in the current buffer."
336   (let (dtd type element end-pos)
337     (forward-char (length "<!DOCTYPE"))
338     (skip-chars-forward " \t\n")
339     (if (looking-at ">")
340         (error "XML: invalid DTD (excepting name of the document)"))
341
342     ;;  Get the name of the document
343     (looking-at "\\sw+")
344     (set 'dtd (list 'dtd (match-string-no-properties 0)))
345     (goto-char (match-end 0))
346
347     (skip-chars-forward " \t\n")
348
349     ;;  External DTDs => don't know how to handle them yet
350     (if (looking-at "SYSTEM")
351         (error "XML: Don't know how to handle external DTDs."))
352     
353     (if (not (= (char-after) ?\[))
354         (error "XML: Unknown declaration in the DTD."))
355
356     ;;  Parse the rest of the DTD
357     (forward-char 1)
358     (while (and (not (looking-at "[ \t\n]*\\]"))
359                 (<= (point) end))
360       (cond
361
362        ;;  Translation of rule [45] of XML specifications
363        ((looking-at
364          "[\t \n]*<!ELEMENT[ \t\n]+\\([a-zA-Z0-9.%;]+\\)[ \t\n]+\\([^>]+\\)>")
365
366         (setq element (intern (match-string-no-properties 1))
367               type    (match-string-no-properties 2))
368         (set 'end-pos (match-end 0))
369         
370         ;;  Translation of rule [46] of XML specifications
371         (cond
372          ((string-match "^EMPTY[ \t\n]*$" type)     ;; empty declaration
373           (set 'type 'empty))
374          ((string-match "^ANY[ \t\n]*$" type)       ;; any type of contents
375           (set 'type 'any))
376          ((string-match "^(\\(.*\\))[ \t\n]*$" type) ;; children ([47])
377           (set 'type (xml-parse-elem-type (match-string-no-properties 1 type))))
378          ((string-match "^%[^;]+;[ \t\n]*$" type)   ;; substitution
379           nil)
380          (t
381           (error "XML: Invalid element type in the DTD")))
382
383         ;;  rule [45]: the element declaration must be unique
384         (if (assoc element dtd)
385             (error "XML: elements declaration must be unique in a DTD (<%s>)."
386                    (symbol-name element)))
387         
388         ;;  Store the element in the DTD
389         (set 'dtd (append dtd (list (list element type))))
390         (goto-char end-pos)
391         )
392
393
394        (t
395         (error "XML: Invalid DTD item"))
396        )
397       )
398
399     ;;  Skip the end of the DTD
400     (search-forward ">" end)
401   dtd
402   ))
403
404
405 (defun xml-parse-elem-type (string)
406   "Convert a STRING for an element type into an elisp structure."
407
408   (let (elem modifier)
409     (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
410         (progn
411           (setq elem     (match-string 1 string)
412                 modifier (match-string 2 string))
413           (if (string-match "|" elem)
414               (set 'elem (append '(choice)
415                                (mapcar 'xml-parse-elem-type
416                                        (split-string elem "|"))))
417             (if (string-match "," elem)
418                 (set 'elem (append '(seq)
419                                  (mapcar 'xml-parse-elem-type
420                                          (split-string elem ","))))
421               )))
422       (if (string-match "[ \t\n]*\\([^+*?]+\\)\\([+*?]?\\)" string)
423           (setq elem     (match-string 1 string)
424                 modifier (match-string 2 string))))
425
426       (if (and (stringp elem)
427                (string= elem "#PCDATA"))
428           (set 'elem 'pcdata))
429     
430       (cond
431        ((string= modifier "+")
432         (list '+ elem))
433        ((string= modifier "*")
434         (list '* elem))
435        ((string= modifier "?")
436         (list '? elem))
437        (t
438         elem))))
439
440
441 ;;*******************************************************************
442 ;;**
443 ;;**  Substituting special XML sequences
444 ;;**
445 ;;*******************************************************************
446
447 (defun xml-substitute-special (string)
448   "Return STRING, after subsituting special XML sequences."
449   (while (string-match "&amp;" string)
450     (set 'string (replace-match "&"  t nil string)))
451   (while (string-match "&lt;" string)
452     (set 'string (replace-match "<"  t nil string)))
453   (while (string-match "&gt;" string)
454     (set 'string (replace-match ">"  t nil string)))
455   (while (string-match "&apos;" string)
456     (set 'string (replace-match "'"  t nil string)))
457   (while (string-match "&quot;" string)
458     (set 'string (replace-match "\"" t nil string)))
459   string)
460
461 ;;*******************************************************************
462 ;;**
463 ;;**  Printing a tree.
464 ;;**  This function is intended mainly for debugging purposes.
465 ;;**
466 ;;*******************************************************************
467
468 (defun xml-debug-print (xml)
469   (while xml
470     (xml-debug-print-internal (car xml) "")
471     (set 'xml (cdr xml)))
472   )
473
474 (defun xml-debug-print-internal (xml &optional indent-string)
475   "Outputs the XML tree in the current buffer.
476 The first line indented with INDENT-STRING."
477   (let ((tree xml)
478         attlist)
479     (unless indent-string
480       (set 'indent-string ""))
481     
482     (insert indent-string "<" (symbol-name (xml-node-name tree)))
483     
484     ;;  output the attribute list
485     (set 'attlist (xml-node-attributes tree))
486     (while attlist
487       (insert " ")
488       (insert (symbol-name (caar attlist)) "=\"" (cdar attlist) "\"")
489       (set 'attlist (cdr attlist)))
490     
491     (insert ">")
492     
493     (set 'tree (xml-node-children tree))
494
495     ;;  output the children
496     (while tree
497       (cond
498        ((listp (car tree))
499         (insert "\n")
500         (xml-debug-print-internal (car tree) (concat indent-string "  "))
501         )
502        ((stringp (car tree))
503         (insert (car tree))
504         )
505        (t
506         (error "Invalid XML tree")))
507       (set 'tree (cdr tree))
508      )
509
510     (insert "\n" indent-string
511             "</" (symbol-name (xml-node-name xml)) ">")
512     ))
513
514 (provide 'xml)
515
516 ;;; xml.el ends here