* lisp/comint.el (comint-output-filter): Filter out repeated prompts.
[bpt/emacs.git] / lisp / xml.el
CommitLineData
1cd7adc6 1;;; xml.el --- XML parser
47db06aa 2
acaf905b 3;; Copyright (C) 2000-2012 Free Software Foundation, Inc.
47db06aa
GM
4
5;; Author: Emmanuel Briot <briot@gnat.com>
720058f2 6;; Maintainer: Mark A. Hershberger <mah@everybody.org>
a98e819b 7;; Keywords: xml, data
47db06aa
GM
8
9;; This file is part of GNU Emacs.
10
eb3fa2cf 11;; GNU Emacs is free software: you can redistribute it and/or modify
47db06aa 12;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
47db06aa
GM
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
eb3fa2cf 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
47db06aa
GM
23
24;;; Commentary:
25
a98e819b
DL
26;; This file contains a somewhat incomplete non-validating XML parser. It
27;; parses a file, and returns a list that can be used internally by
a1dfa9a3 28;; any other Lisp libraries.
47db06aa
GM
29
30;;; FILE FORMAT
31
a98e819b
DL
32;; The document type declaration may either be ignored or (optionally)
33;; parsed, but currently the parsing will only accept element
a1dfa9a3 34;; declarations. The XML file is assumed to be well-formed. In case
a98e819b
DL
35;; of error, the parsing stops and the XML file is shown where the
36;; parsing stopped.
47db06aa 37;;
a98e819b 38;; It also knows how to ignore comments and processing instructions.
47db06aa
GM
39;;
40;; The XML file should have the following format:
653558a1
GM
41;; <node1 attr1="name1" attr2="name2" ...>value
42;; <node2 attr3="name3" attr4="name4">value2</node2>
43;; <node3 attr5="name5" attr6="name6">value3</node3>
47db06aa 44;; </node1>
a1dfa9a3 45;; Of course, the name of the nodes and attributes can be anything. There can
47db06aa
GM
46;; be any number of attributes (or none), as well as any number of children
47;; below the nodes.
48;;
49;; There can be only top level node, but with any number of children below.
50
51;;; LIST FORMAT
52
c7f8d055
SM
53;; The functions `xml-parse-file', `xml-parse-region' and
54;; `xml-parse-tag' return a list with the following format:
47db06aa
GM
55;;
56;; xml-list ::= (node node ...)
c7f8d055 57;; node ::= (qname attribute-list . child_node_list)
47db06aa
GM
58;; child_node_list ::= child_node child_node ...
59;; child_node ::= node | string
c7f8d055
SM
60;; qname ::= (:namespace-uri . "name") | "name"
61;; attribute_list ::= ((qname . "value") (qname . "value") ...)
47db06aa
GM
62;; | nil
63;; string ::= "..."
64;;
a98e819b
DL
65;; Some macros are provided to ease the parsing of this list.
66;; Whitespace is preserved. Fixme: There should be a tree-walker that
67;; can remove it.
47db06aa 68
c7f8d055
SM
69;; TODO:
70;; * xml:base, xml:space support
71;; * more complete DOCTYPE parsing
72;; * pi support
73
47db06aa
GM
74;;; Code:
75
f6fcdfff
CY
76;; Note that buffer-substring and match-string were formerly used in
77;; several places, because the -no-properties variants remove
78;; composition info. However, after some discussion on emacs-devel,
79;; the consensus was that the speed of the -no-properties variants was
80;; a worthwhile tradeoff especially since we're usually parsing files
81;; instead of hand-crafted XML.
a98e819b 82
47db06aa
GM
83;;*******************************************************************
84;;**
85;;** Macros to parse the list
86;;**
87;;*******************************************************************
88
f8ab034e
MH
89(defconst xml-undefined-entity "?"
90 "What to substitute for undefined entities")
91
6d12a4df
MH
92(defvar xml-entity-alist
93 '(("lt" . "<")
94 ("gt" . ">")
95 ("apos" . "'")
96 ("quot" . "\"")
97 ("amp" . "&"))
7f3fbd5d
CY
98 "Alist of defined XML entities.")
99
100(defvar xml-parameter-entity-alist nil
101 "Alist of defined XML parametric entities.")
6d12a4df
MH
102
103(defvar xml-sub-parser nil
7f3fbd5d 104 "Non-nil when the XML parser is parsing an XML fragment.")
6d12a4df
MH
105
106(defvar xml-validating-parser nil
107 "Set to non-nil to get validity checking.")
108
971489ea 109(defsubst xml-node-name (node)
47db06aa 110 "Return the tag associated with NODE.
a1dfa9a3
SM
111Without namespace-aware parsing, the tag is a symbol.
112
113With namespace-aware parsing, the tag is a cons of a string
114representing the uri of the namespace with the local name of the
115tag. For example,
116
117 <foo>
118
119would be represented by
120
121 '(\"\" . \"foo\")."
122
971489ea 123 (car node))
47db06aa 124
971489ea 125(defsubst xml-node-attributes (node)
47db06aa
GM
126 "Return the list of attributes of NODE.
127The list can be nil."
971489ea 128 (nth 1 node))
47db06aa 129
971489ea 130(defsubst xml-node-children (node)
47db06aa
GM
131 "Return the list of children of NODE.
132This is a list of nodes, and it can be nil."
971489ea 133 (cddr node))
47db06aa
GM
134
135(defun xml-get-children (node child-name)
136 "Return the children of NODE whose tag is CHILD-NAME.
a1dfa9a3 137CHILD-NAME should match the value returned by `xml-node-name'."
971489ea
SM
138 (let ((match ()))
139 (dolist (child (xml-node-children node))
a1dfa9a3
SM
140 (if (and (listp child)
141 (equal (xml-node-name child) child-name))
142 (push child match)))
971489ea 143 (nreverse match)))
47db06aa 144
9bcd6a7e 145(defun xml-get-attribute-or-nil (node attribute)
47db06aa 146 "Get from NODE the value of ATTRIBUTE.
a1dfa9a3 147Return nil if the attribute was not found.
9bcd6a7e
EZ
148
149See also `xml-get-attribute'."
2e9bdf15 150 (cdr (assoc attribute (xml-node-attributes node))))
9bcd6a7e
EZ
151
152(defsubst xml-get-attribute (node attribute)
153 "Get from NODE the value of ATTRIBUTE.
154An empty string is returned if the attribute was not found.
155
156See also `xml-get-attribute-or-nil'."
157 (or (xml-get-attribute-or-nil node attribute) ""))
47db06aa
GM
158
159;;*******************************************************************
160;;**
161;;** Creating the list
162;;**
163;;*******************************************************************
164
a98e819b 165;;;###autoload
2d42509a 166(defun xml-parse-file (file &optional parse-dtd parse-ns)
a98e819b 167 "Parse the well-formed XML file FILE.
fbf2e7ad 168Return the top node with all its children.
2d42509a
JB
169If PARSE-DTD is non-nil, the DTD is parsed rather than skipped.
170If PARSE-NS is non-nil, then QNAMES are expanded."
fbf2e7ad
CY
171 (with-temp-buffer
172 (insert-file-contents file)
173 (xml--parse-buffer parse-dtd parse-ns)))
47db06aa 174
b3218de1 175(eval-and-compile
63b446bc 176(let* ((start-chars (concat "[:alpha:]:_"))
6d12a4df 177 (name-chars (concat "-[:digit:]." start-chars))
b3218de1 178 ;;[3] S ::= (#x20 | #x9 | #xD | #xA)+
6d12a4df 179 (whitespace "[ \t\n\r]"))
b3218de1
CY
180 ;; [4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6]
181 ;; | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF]
182 ;; | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF]
183 ;; | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD]
184 ;; | [#x10000-#xEFFFF]
185 (defconst xml-name-start-char-re (concat "[" start-chars "]"))
186 ;; [4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7
187 ;; | [#x0300-#x036F] | [#x203F-#x2040]
188 (defconst xml-name-char-re (concat "[" name-chars "]"))
189 ;; [5] Name ::= NameStartChar (NameChar)*
190 (defconst xml-name-re (concat xml-name-start-char-re xml-name-char-re "*"))
191 ;; [6] Names ::= Name (#x20 Name)*
192 (defconst xml-names-re (concat xml-name-re "\\(?: " xml-name-re "\\)*"))
193 ;; [7] Nmtoken ::= (NameChar)+
194 (defconst xml-nmtoken-re (concat xml-name-char-re "+"))
195 ;; [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*
196 (defconst xml-nmtokens-re (concat xml-nmtoken-re "\\(?: " xml-name-re "\\)*"))
197 ;; [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
198 (defconst xml-char-ref-re "\\(?:&#[0-9]+;\\|&#x[0-9a-fA-F]+;\\)")
199 ;; [68] EntityRef ::= '&' Name ';'
200 (defconst xml-entity-ref (concat "&" xml-name-re ";"))
201 ;; [69] PEReference ::= '%' Name ';'
202 (defconst xml-pe-reference-re (concat "%" xml-name-re ";"))
203 ;; [67] Reference ::= EntityRef | CharRef
204 (defconst xml-reference-re (concat "\\(?:" xml-entity-ref "\\|" xml-char-ref-re "\\)"))
205 ;; [10] AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'"
206 (defconst xml-att-value-re (concat "\\(?:\"\\(?:[^&\"]\\|" xml-reference-re "\\)*\"\\|"
207 "'\\(?:[^&']\\|" xml-reference-re "\\)*'\\)"))
208 ;; [56] TokenizedType ::= 'ID' [VC: ID] [VC: One ID / Element Type] [VC: ID Attribute Default]
209 ;; | 'IDREF' [VC: IDREF]
210 ;; | 'IDREFS' [VC: IDREF]
211 ;; | 'ENTITY' [VC: Entity Name]
212 ;; | 'ENTITIES' [VC: Entity Name]
213 ;; | 'NMTOKEN' [VC: Name Token]
214 ;; | 'NMTOKENS' [VC: Name Token]
215 (defconst xml-tokenized-type-re (concat "\\(?:ID\\|IDREF\\|IDREFS\\|ENTITY\\|"
216 "ENTITIES\\|NMTOKEN\\|NMTOKENS\\)"))
217 ;; [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
218 (defconst xml-notation-type-re
219 (concat "\\(?:NOTATION" whitespace "(" whitespace "*" xml-name-re
220 "\\(?:" whitespace "*|" whitespace "*" xml-name-re "\\)*"
221 whitespace "*)\\)"))
222 ;; [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
223 ;; [VC: Enumeration] [VC: No Duplicate Tokens]
224 (defconst xml-enumeration-re (concat "\\(?:(" whitespace "*" xml-nmtoken-re
225 "\\(?:" whitespace "*|" whitespace "*"
226 xml-nmtoken-re "\\)*"
23d519e4 227 whitespace ")\\)"))
b3218de1
CY
228 ;; [57] EnumeratedType ::= NotationType | Enumeration
229 (defconst xml-enumerated-type-re (concat "\\(?:" xml-notation-type-re
230 "\\|" xml-enumeration-re "\\)"))
231 ;; [54] AttType ::= StringType | TokenizedType | EnumeratedType
232 ;; [55] StringType ::= 'CDATA'
233 (defconst xml-att-type-re (concat "\\(?:CDATA\\|" xml-tokenized-type-re
234 "\\|" xml-notation-type-re
235 "\\|" xml-enumerated-type-re "\\)"))
236 ;; [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
237 (defconst xml-default-decl-re (concat "\\(?:#REQUIRED\\|#IMPLIED\\|\\(?:#FIXED"
238 whitespace "\\)*" xml-att-value-re "\\)"))
239 ;; [53] AttDef ::= S Name S AttType S DefaultDecl
240 (defconst xml-att-def-re (concat "\\(?:" whitespace "*" xml-name-re
241 whitespace "*" xml-att-type-re
242 whitespace "*" xml-default-decl-re "\\)"))
243 ;; [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
244 ;; | "'" ([^%&'] | PEReference | Reference)* "'"
245 (defconst xml-entity-value-re (concat "\\(?:\"\\(?:[^%&\"]\\|" xml-pe-reference-re
246 "\\|" xml-reference-re
247 "\\)*\"\\|'\\(?:[^%&']\\|"
248 xml-pe-reference-re "\\|"
249 xml-reference-re "\\)*'\\)"))))
250
251;; [75] ExternalID ::= 'SYSTEM' S SystemLiteral
252;; | 'PUBLIC' S PubidLiteral S SystemLiteral
253;; [76] NDataDecl ::= S 'NDATA' S
254;; [73] EntityDef ::= EntityValue| (ExternalID NDataDecl?)
255;; [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
256;; [74] PEDef ::= EntityValue | ExternalID
257;; [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
258;; [70] EntityDecl ::= GEDecl | PEDecl
6d12a4df 259
a98e819b
DL
260;; Note that this is setup so that we can do whitespace-skipping with
261;; `(skip-syntax-forward " ")', inter alia. Previously this was slow
262;; compared with `re-search-forward', but that has been fixed. Also
263;; note that the standard syntax table contains other characters with
264;; whitespace syntax, like NBSP, but they are invalid in contexts in
265;; which we might skip whitespace -- specifically, they're not
266;; NameChars [XML 4].
267
268(defvar xml-syntax-table
269 (let ((table (make-syntax-table)))
270 ;; Get space syntax correct per XML [3].
271 (dotimes (c 31)
272 (modify-syntax-entry c "." table)) ; all are space in standard table
5178753d 273 (dolist (c '(?\t ?\n ?\r)) ; these should be space
a98e819b
DL
274 (modify-syntax-entry c " " table))
275 ;; For skipping attributes.
276 (modify-syntax-entry ?\" "\"" table)
277 (modify-syntax-entry ?' "\"" table)
278 ;; Non-alnum name chars should be symbol constituents (`-' and `_'
279 ;; are OK by default).
280 (modify-syntax-entry ?. "_" table)
281 (modify-syntax-entry ?: "_" table)
282 ;; XML [89]
aaaa8abb
MH
283 (unless (featurep 'xemacs)
284 (dolist (c '(#x00B7 #x02D0 #x02D1 #x0387 #x0640 #x0E46 #x0EC6 #x3005
285 #x3031 #x3032 #x3033 #x3034 #x3035 #x309D #x309E #x30FC
286 #x30FD #x30FE))
287 (modify-syntax-entry (decode-char 'ucs c) "w" table)))
a98e819b
DL
288 ;; Fixme: rest of [4]
289 table)
290 "Syntax table used by `xml-parse-region'.")
291
292;; XML [5]
293;; Note that [:alpha:] matches all multibyte chars with word syntax.
ab161457
JPW
294(eval-and-compile
295 (defconst xml-name-regexp "[[:alpha:]_:][[:alnum:]._:-]*"))
a98e819b
DL
296
297;; Fixme: This needs re-writing to deal with the XML grammar properly, i.e.
298;; document ::= prolog element Misc*
299;; prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
300
301;;;###autoload
2d42509a 302(defun xml-parse-region (beg end &optional buffer parse-dtd parse-ns)
47db06aa
GM
303 "Parse the region from BEG to END in BUFFER.
304If BUFFER is nil, it defaults to the current buffer.
305Returns the XML list for the region, or raises an error if the region
2d42509a 306is not well-formed XML.
47db06aa 307If PARSE-DTD is non-nil, the DTD is parsed rather than skipped,
2d42509a
JB
308and returned as the first element of the list.
309If PARSE-NS is non-nil, then QNAMES are expanded."
39d58fc0
MH
310 ;; Use fixed syntax table to ensure regexp char classes and syntax
311 ;; specs DTRT.
fbf2e7ad
CY
312 (unless buffer
313 (setq buffer (current-buffer)))
314 (with-temp-buffer
315 (insert-buffer-substring buffer beg end)
316 (xml--parse-buffer parse-dtd parse-ns)))
317
318(defun xml--parse-buffer (parse-dtd parse-ns)
39d58fc0
MH
319 (with-syntax-table (standard-syntax-table)
320 (let ((case-fold-search nil) ; XML is case-sensitive.
7f3fbd5d
CY
321 ;; Prevent entity definitions from changing the defaults
322 (xml-entity-alist xml-entity-alist)
323 (xml-parameter-entity-alist xml-parameter-entity-alist)
39d58fc0 324 xml result dtd)
fbf2e7ad
CY
325 (goto-char (point-min))
326 (while (not (eobp))
327 (if (search-forward "<" nil t)
328 (progn
329 (forward-char -1)
330 (setq result (xml-parse-tag parse-dtd parse-ns))
331 (cond
332 ((null result)
333 ;; Not looking at an xml start tag.
334 (unless (eobp)
335 (forward-char 1)))
336 ((and xml (not xml-sub-parser))
337 ;; Translation of rule [1] of XML specifications
338 (error "XML: (Not Well-Formed) Only one root tag allowed"))
339 ((and (listp (car result))
340 parse-dtd)
341 (setq dtd (car result))
342 (if (cdr result) ; possible leading comment
343 (add-to-list 'xml (cdr result))))
344 (t
345 (add-to-list 'xml result))))
346 (goto-char (point-max))))
347 (if parse-dtd
348 (cons dtd (nreverse xml))
349 (nreverse xml)))))
47db06aa 350
c7f8d055 351(defun xml-maybe-do-ns (name default xml-ns)
a1dfa9a3
SM
352 "Perform any namespace expansion.
353NAME is the name to perform the expansion on.
c7f8d055
SM
354DEFAULT is the default namespace. XML-NS is a cons of namespace
355names to uris. When namespace-aware parsing is off, then XML-NS
356is nil.
357
358During namespace-aware parsing, any name without a namespace is
359put into the namespace identified by DEFAULT. nil is used to
360specify that the name shouldn't be given a namespace."
361 (if (consp xml-ns)
362 (let* ((nsp (string-match ":" name))
363 (lname (if nsp (substring name (match-end 0)) name))
364 (prefix (if nsp (substring name 0 (match-beginning 0)) default))
365 (special (and (string-equal lname "xmlns") (not prefix)))
366 ;; Setting default to nil will insure that there is not
367 ;; matching cons in xml-ns. In which case we
368 (ns (or (cdr (assoc (if special "xmlns" prefix)
369 xml-ns))
6d12a4df 370 "")))
c7f8d055
SM
371 (cons ns (if special "" lname)))
372 (intern name)))
47db06aa 373
6d12a4df
MH
374(defun xml-parse-fragment (&optional parse-dtd parse-ns)
375 "Parse xml-like fragments."
376 (let ((xml-sub-parser t)
7f3fbd5d
CY
377 ;; Prevent entity definitions from changing the defaults
378 (xml-entity-alist xml-entity-alist)
379 (xml-parameter-entity-alist xml-parameter-entity-alist)
6d12a4df
MH
380 children)
381 (while (not (eobp))
382 (let ((bit (xml-parse-tag
383 parse-dtd parse-ns)))
384 (if children
385 (setq children (append (list bit) children))
386 (if (stringp bit)
387 (setq children (list bit))
388 (setq children bit)))))
389 (reverse children)))
390
2d42509a 391(defun xml-parse-tag (&optional parse-dtd parse-ns)
a98e819b 392 "Parse the tag at point.
47db06aa
GM
393If PARSE-DTD is non-nil, the DTD of the document, if any, is parsed and
394returned as the first element in the list.
2d42509a 395If PARSE-NS is non-nil, then QNAMES are expanded.
47db06aa 396Returns one of:
a98e819b
DL
397 - a list : the matching node
398 - nil : the point is not looking at a tag.
399 - a pair : the first element is the DTD, the second is the node."
6d12a4df
MH
400 (let ((xml-validating-parser (or parse-dtd xml-validating-parser))
401 (xml-ns (if (consp parse-ns)
2d42509a
JB
402 parse-ns
403 (if parse-ns
404 (list
5178753d 405 ;; Default for empty prefix is no namespace
6d12a4df 406 (cons "" "")
c7f8d055 407 ;; "xml" namespace
6d12a4df 408 (cons "xml" "http://www.w3.org/XML/1998/namespace")
2d42509a 409 ;; We need to seed the xmlns namespace
6d12a4df 410 (cons "xmlns" "http://www.w3.org/2000/xmlns/"))))))
2d42509a
JB
411 (cond
412 ;; Processing instructions (like the <?xml version="1.0"?> tag at the
413 ;; beginning of a document).
414 ((looking-at "<\\?")
415 (search-forward "?>")
416 (skip-syntax-forward " ")
417 (xml-parse-tag parse-dtd xml-ns))
418 ;; Character data (CDATA) sections, in which no tag should be interpreted
419 ((looking-at "<!\\[CDATA\\[")
420 (let ((pos (match-end 0)))
421 (unless (search-forward "]]>" nil t)
6d12a4df 422 (error "XML: (Not Well Formed) CDATA section does not end anywhere in the document"))
ae026110 423 (concat
f6fcdfff 424 (buffer-substring-no-properties pos (match-beginning 0))
ae026110 425 (xml-parse-string))))
2d42509a 426 ;; DTD for the document
7f3fbd5d 427 ((looking-at "<!DOCTYPE[ \t\n\r]")
6d12a4df
MH
428 (let ((dtd (xml-parse-dtd parse-ns)))
429 (skip-syntax-forward " ")
430 (if xml-validating-parser
431 (cons dtd (xml-parse-tag nil xml-ns))
432 (xml-parse-tag nil xml-ns))))
2d42509a
JB
433 ;; skip comments
434 ((looking-at "<!--")
435 (search-forward "-->")
a268160b 436 (skip-syntax-forward " ")
18edb22d 437 (unless (eobp)
772b2e2c
CY
438 (let ((xml-sub-parser t))
439 (xml-parse-tag parse-dtd xml-ns))))
2d42509a
JB
440 ;; end tag
441 ((looking-at "</")
442 '())
443 ;; opening tag
444 ((looking-at "<\\([^/>[:space:]]+\\)")
445 (goto-char (match-end 1))
34638996
EZ
446
447 ;; Parse this node
f6fcdfff 448 (let* ((node-name (match-string-no-properties 1))
5178753d
MH
449 ;; Parse the attribute list.
450 (attrs (xml-parse-attlist xml-ns))
06b60517 451 children)
c7f8d055 452
5178753d
MH
453 ;; add the xmlns:* attrs to our cache
454 (when (consp xml-ns)
c7f8d055
SM
455 (dolist (attr attrs)
456 (when (and (consp (car attr))
6d12a4df
MH
457 (equal "http://www.w3.org/2000/xmlns/"
458 (caar attr)))
459 (push (cons (cdar attr) (cdr attr))
c7f8d055
SM
460 xml-ns))))
461
5178753d 462 (setq children (list attrs (xml-maybe-do-ns node-name "" xml-ns)))
c7f8d055 463
2d42509a
JB
464 ;; is this an empty element ?
465 (if (looking-at "/>")
47db06aa 466 (progn
6d12a4df 467 (forward-char 2)
971489ea 468 (nreverse children))
6d12a4df
MH
469
470 ;; is this a valid start tag ?
471 (if (eq (char-after) ?>)
472 (progn
473 (forward-char 1)
474 ;; Now check that we have the right end-tag. Note that this
475 ;; one might contain spaces after the tag name
476 (let ((end (concat "</" node-name "\\s-*>")))
477 (while (not (looking-at end))
478 (cond
479 ((looking-at "</")
480 (error "XML: (Not Well-Formed) Invalid end tag (expecting %s) at pos %d"
481 node-name (point)))
482 ((= (char-after) ?<)
483 (let ((tag (xml-parse-tag nil xml-ns)))
484 (when tag
485 (push tag children))))
486 (t
487 (let ((expansion (xml-parse-string)))
488 (setq children
489 (if (stringp expansion)
490 (if (stringp (car children))
491 ;; The two strings were separated by a comment.
aaaa8abb 492 (setq children (append (list (concat (car children) expansion))
6d12a4df
MH
493 (cdr children)))
494 (setq children (append (list expansion) children)))
495 (setq children (append expansion children))))))))
496
497 (goto-char (match-end 0))
498 (nreverse children)))
499 ;; This was an invalid start tag (Expected ">", but didn't see it.)
500 (error "XML: (Well-Formed) Couldn't parse tag: %s"
f6fcdfff 501 (buffer-substring-no-properties (- (point) 10) (+ (point) 1)))))))
6d12a4df
MH
502 (t ;; (Not one of PI, CDATA, Comment, End tag, or Start tag)
503 (unless xml-sub-parser ; Usually, we error out.
504 (error "XML: (Well-Formed) Invalid character"))
505
506 ;; However, if we're parsing incrementally, then we need to deal
507 ;; with stray CDATA.
508 (xml-parse-string)))))
509
510(defun xml-parse-string ()
511 "Parse the next whatever. Could be a string, or an element."
5178753d 512 (let* ((pos (point))
98b69232 513 (string (progn (skip-chars-forward "^<")
f6fcdfff 514 (buffer-substring-no-properties pos (point)))))
5178753d
MH
515 ;; Clean up the string. As per XML specifications, the XML
516 ;; processor should always pass the whole string to the
517 ;; application. But \r's should be replaced:
518 ;; http://www.w3.org/TR/2000/REC-xml-20001006#sec-line-ends
519 (setq pos 0)
520 (while (string-match "\r\n?" string pos)
521 (setq string (replace-match "\n" t t string))
522 (setq pos (1+ (match-beginning 0))))
523
524 (xml-substitute-special string)))
47db06aa 525
c7f8d055 526(defun xml-parse-attlist (&optional xml-ns)
a1dfa9a3
SM
527 "Return the attribute-list after point.
528Leave point at the first non-blank character after the tag."
971489ea 529 (let ((attlist ())
34638996 530 end-pos name)
a98e819b
DL
531 (skip-syntax-forward " ")
532 (while (looking-at (eval-when-compile
533 (concat "\\(" xml-name-regexp "\\)\\s-*=\\s-*")))
c7f8d055 534 (setq end-pos (match-end 0))
f6fcdfff 535 (setq name (xml-maybe-do-ns (match-string-no-properties 1) nil xml-ns))
c7f8d055 536 (goto-char end-pos)
47db06aa 537
a158ff81
JB
538 ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
539
47db06aa
GM
540 ;; Do we have a string between quotes (or double-quotes),
541 ;; or a simple word ?
a158ff81 542 (if (looking-at "\"\\([^\"]*\\)\"")
34638996 543 (setq end-pos (match-end 0))
f0ec1711 544 (if (looking-at "'\\([^']*\\)'")
34638996 545 (setq end-pos (match-end 0))
6d12a4df 546 (error "XML: (Not Well-Formed) Attribute values must be given between quotes")))
47db06aa
GM
547
548 ;; Each attribute must be unique within a given element
549 (if (assoc name attlist)
6d12a4df 550 (error "XML: (Not Well-Formed) Each attribute must be unique within an element"))
524425ae 551
a158ff81
JB
552 ;; Multiple whitespace characters should be replaced with a single one
553 ;; in the attributes
06b60517 554 (let ((string (match-string-no-properties 1)))
a98e819b 555 (replace-regexp-in-string "\\s-\\{2,\\}" " " string)
6d12a4df
MH
556 (let ((expansion (xml-substitute-special string)))
557 (unless (stringp expansion)
91af3942 558 ; We say this is the constraint. It is actually that neither
5178753d 559 ; external entities nor "<" can be in an attribute value.
6d12a4df
MH
560 (error "XML: (Not Well-Formed) Entities in attributes cannot expand into elements"))
561 (push (cons name expansion) attlist)))
a158ff81 562
34638996 563 (goto-char end-pos)
a98e819b 564 (skip-syntax-forward " "))
971489ea 565 (nreverse attlist)))
47db06aa
GM
566
567;;*******************************************************************
568;;**
569;;** The DTD (document type declaration)
570;;** The following functions know how to skip or parse the DTD of
571;;** a document
572;;**
573;;*******************************************************************
574
a98e819b
DL
575;; Fixme: This fails at least if the DTD contains conditional sections.
576
577(defun xml-skip-dtd ()
578 "Skip the DTD at point.
47db06aa 579This follows the rule [28] in the XML specifications."
6d12a4df
MH
580 (let ((xml-validating-parser nil))
581 (xml-parse-dtd)))
47db06aa 582
6d12a4df 583(defun xml-parse-dtd (&optional parse-ns)
a98e819b
DL
584 "Parse the DTD at point."
585 (forward-char (eval-when-compile (length "<!DOCTYPE")))
586 (skip-syntax-forward " ")
6d12a4df
MH
587 (if (and (looking-at ">")
588 xml-validating-parser)
589 (error "XML: (Validity) Invalid DTD (expecting name of the document)"))
524425ae 590
971489ea 591 ;; Get the name of the document
a98e819b 592 (looking-at xml-name-regexp)
f6fcdfff 593 (let ((dtd (list (match-string-no-properties 0) 'dtd))
fbf2e7ad
CY
594 (xml-parameter-entity-alist xml-parameter-entity-alist)
595 (parameter-entity-re (eval-when-compile
596 (concat "%\\(" xml-name-re "\\);")))
597 next-parameter-entity)
47db06aa 598 (goto-char (match-end 0))
a98e819b 599 (skip-syntax-forward " ")
7f3fbd5d
CY
600
601 ;; External subset (XML [75])
a98e819b
DL
602 (cond ((looking-at "PUBLIC\\s-+")
603 (goto-char (match-end 0))
604 (unless (or (re-search-forward
605 "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
606 nil t)
607 (re-search-forward
608 "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
609 nil t))
6d12a4df 610 (error "XML: Missing Public ID"))
f6fcdfff 611 (let ((pubid (match-string-no-properties 1)))
6d12a4df 612 (skip-syntax-forward " ")
a98e819b
DL
613 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
614 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
6d12a4df 615 (error "XML: Missing System ID"))
f6fcdfff 616 (push (list pubid (match-string-no-properties 1) 'public) dtd)))
a98e819b
DL
617 ((looking-at "SYSTEM\\s-+")
618 (goto-char (match-end 0))
619 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
620 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
6d12a4df 621 (error "XML: Missing System ID"))
f6fcdfff 622 (push (list (match-string-no-properties 1) 'system) dtd)))
a98e819b 623 (skip-syntax-forward " ")
7f3fbd5d
CY
624
625 (if (eq (char-after) ?>)
626
627 ;; No internal subset
a98e819b 628 (forward-char)
a98e819b 629
7f3fbd5d
CY
630 ;; Internal subset (XML [28b])
631 (unless (eq (char-after) ?\[)
632 (error "XML: Bad DTD"))
633 (forward-char)
634
fbf2e7ad
CY
635 ;; [2.8]: "markup declarations may be made up in whole or in
636 ;; part of the replacement text of parameter entities."
637
638 ;; Since parameter entities are valid only within the DTD, we
639 ;; first search for the position of the next possible parameter
640 ;; entity. Then, search for the next DTD element; if it ends
641 ;; before the next parameter entity, expand the parameter entity
642 ;; and try again.
643 (setq next-parameter-entity
644 (save-excursion
645 (if (re-search-forward parameter-entity-re nil t)
646 (match-beginning 0))))
647
7f3fbd5d
CY
648 ;; Parse the rest of the DTD
649 ;; Fixme: Deal with NOTATION, PIs.
650 (while (not (looking-at "\\s-*\\]"))
651 (skip-syntax-forward " ")
652 (cond
653 ;; Element declaration [45]:
6fe566a7
CY
654 ((and (looking-at (eval-when-compile
655 (concat "<!ELEMENT\\s-+\\(" xml-name-re
656 "\\)\\s-+\\([^>]+\\)>")))
fbf2e7ad
CY
657 (or (null next-parameter-entity)
658 (<= (match-end 0) next-parameter-entity)))
7f3fbd5d
CY
659 (let ((element (match-string-no-properties 1))
660 (type (match-string-no-properties 2))
661 (end-pos (match-end 0)))
662 ;; Translation of rule [46] of XML specifications
a98e819b 663 (cond
6fe566a7 664 ((string-match "\\`EMPTY\\s-*\\'" type) ; empty declaration
a98e819b 665 (setq type 'empty))
6fe566a7 666 ((string-match "\\`ANY\\s-*$" type) ; any type of contents
a98e819b 667 (setq type 'any))
6fe566a7
CY
668 ((string-match "\\`(\\(.*\\))\\s-*\\'" type) ; children ([47])
669 (setq type (xml-parse-elem-type
670 (match-string-no-properties 1 type))))
671 ((string-match "^%[^;]+;[ \t\n\r]*\\'" type) ; substitution
a98e819b 672 nil)
7f3fbd5d
CY
673 (xml-validating-parser
674 (error "XML: (Validity) Invalid element type in the DTD")))
27720433 675
7f3fbd5d
CY
676 ;; rule [45]: the element declaration must be unique
677 (and (assoc element dtd)
678 xml-validating-parser
679 (error "XML: (Validity) DTD element declarations must be unique (<%s>)"
680 element))
a98e819b
DL
681
682 ;; Store the element in the DTD
683 (push (list element type) dtd)
7f3fbd5d
CY
684 (goto-char end-pos)))
685
686 ;; Attribute-list declaration [52] (currently unsupported):
fbf2e7ad
CY
687 ((and (looking-at (eval-when-compile
688 (concat "<!ATTLIST[ \t\n\r]*\\(" xml-name-re
689 "\\)[ \t\n\r]*\\(" xml-att-def-re
690 "\\)*[ \t\n\r]*>")))
691 (or (null next-parameter-entity)
692 (<= (match-end 0) next-parameter-entity)))
7f3fbd5d
CY
693 (goto-char (match-end 0)))
694
fbf2e7ad 695 ;; Comments (skip to end, ignoring parameter entity):
7f3fbd5d 696 ((looking-at "<!--")
fbf2e7ad
CY
697 (search-forward "-->")
698 (and next-parameter-entity
699 (> (point) next-parameter-entity)
700 (setq next-parameter-entity
701 (save-excursion
702 (if (re-search-forward parameter-entity-re nil t)
703 (match-beginning 0))))))
7f3fbd5d
CY
704
705 ;; Internal entity declarations:
fbf2e7ad
CY
706 ((and (looking-at (eval-when-compile
707 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
708 xml-name-re "\\)[ \t\n\r]*\\("
709 xml-entity-value-re "\\)[ \t\n\r]*>")))
710 (or (null next-parameter-entity)
711 (<= (match-end 0) next-parameter-entity)))
7f3fbd5d
CY
712 (let* ((name (prog1 (match-string-no-properties 2)
713 (goto-char (match-end 0))))
714 (alist (if (match-string 1)
715 'xml-parameter-entity-alist
716 'xml-entity-alist))
717 ;; Retrieve the deplacement text:
718 (value (xml--entity-replacement-text
719 ;; Entity value, sans quotation marks:
720 (substring (match-string-no-properties 3) 1 -1))))
721 ;; If the same entity is declared more than once, the
722 ;; first declaration is binding.
723 (unless (assoc name (symbol-value alist))
724 (set alist (cons (cons name value) (symbol-value alist))))))
725
726 ;; External entity declarations (currently unsupported):
fbf2e7ad
CY
727 ((and (or (looking-at (eval-when-compile
728 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
729 xml-name-re "\\)[ \t\n\r]+SYSTEM[ \t\n\r]+"
730 "\\(\"[^\"]*\"\\|'[^']*'\\)[ \t\n\r]*>")))
731 (looking-at (eval-when-compile
732 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
733 xml-name-re "\\)[ \t\n\r]+PUBLIC[ \t\n\r]+"
734 "\"[- \r\na-zA-Z0-9'()+,./:=?;!*#@$_%]*\""
735 "\\|'[- \r\na-zA-Z0-9()+,./:=?;!*#@$_%]*'"
736 "[ \t\n\r]+\\(\"[^\"]*\"\\|'[^']*'\\)"
737 "[ \t\n\r]*>"))))
738 (or (null next-parameter-entity)
739 (<= (match-end 0) next-parameter-entity)))
7f3fbd5d
CY
740 (goto-char (match-end 0)))
741
fbf2e7ad
CY
742 ;; If a parameter entity is in the way, expand it.
743 (next-parameter-entity
744 (save-excursion
745 (goto-char next-parameter-entity)
746 (unless (looking-at parameter-entity-re)
747 (error "XML: Internal error"))
748 (let* ((entity (match-string 1))
749 (beg (point-marker))
750 (elt (assoc entity xml-parameter-entity-alist)))
751 (if elt
752 (progn
753 (replace-match (cdr elt) t t)
754 ;; The replacement can itself be a parameter entity.
755 (goto-char next-parameter-entity))
756 (goto-char (match-end 0))))
757 (setq next-parameter-entity
758 (if (re-search-forward parameter-entity-re nil t)
759 (match-beginning 0)))))
7f3fbd5d
CY
760
761 ;; Anything else:
762 (xml-validating-parser
763 (error "XML: (Validity) Invalid DTD item"))))
764
6d12a4df 765 (if (looking-at "\\s-*]>")
23d519e4 766 (goto-char (match-end 0))))
461f3ad0 767 (nreverse dtd)))
47db06aa 768
7f3fbd5d
CY
769(defun xml--entity-replacement-text (string)
770 "Return the replacement text for the entity value STRING.
771The replacement text is obtained by replacing character
772references and parameter-entity references."
b3218de1
CY
773 (let ((ref-re (eval-when-compile
774 (concat "\\(?:&#\\([0-9]+\\)\\|&#x\\([0-9a-fA-F]+\\)\\|%\\("
775 xml-name-re "\\)\\);")))
7f3fbd5d
CY
776 children)
777 (while (string-match ref-re string)
778 (push (substring string 0 (match-beginning 0)) children)
779 (let ((remainder (substring string (match-end 0)))
780 ref val)
781 (cond ((setq ref (match-string 1 string))
782 ;; Decimal character reference
783 (setq val (decode-char 'ucs (string-to-number ref)))
784 (if val (push (string val) children)))
785 ;; Hexadecimal character reference
786 ((setq ref (match-string 2 string))
787 (setq val (decode-char 'ucs (string-to-number ref 16)))
788 (if val (push (string val) children)))
789 ;; Parameter entity reference
790 ((setq ref (match-string 3 string))
791 (setq val (assoc ref xml-parameter-entity-alist))
792 (if val
793 (push (cdr val) children)
794 (push (concat "%" ref ";") children))))
795 (setq string remainder)))
796 (mapconcat 'identity (nreverse (cons string children)) "")))
797
47db06aa 798(defun xml-parse-elem-type (string)
a98e819b 799 "Convert element type STRING into a Lisp structure."
47db06aa
GM
800
801 (let (elem modifier)
802 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
803 (progn
f6fcdfff
CY
804 (setq elem (match-string-no-properties 1 string)
805 modifier (match-string-no-properties 2 string))
47db06aa 806 (if (string-match "|" elem)
971489ea 807 (setq elem (cons 'choice
47db06aa
GM
808 (mapcar 'xml-parse-elem-type
809 (split-string elem "|"))))
810 (if (string-match "," elem)
971489ea 811 (setq elem (cons 'seq
47db06aa 812 (mapcar 'xml-parse-elem-type
a98e819b 813 (split-string elem ",")))))))
a158ff81 814 (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string)
f6fcdfff
CY
815 (setq elem (match-string-no-properties 1 string)
816 modifier (match-string-no-properties 2 string))))
47db06aa 817
971489ea
SM
818 (if (and (stringp elem) (string= elem "#PCDATA"))
819 (setq elem 'pcdata))
524425ae 820
971489ea
SM
821 (cond
822 ((string= modifier "+")
823 (list '+ elem))
824 ((string= modifier "*")
825 (list '* elem))
826 ((string= modifier "?")
0fa6f70c 827 (list '\? elem))
971489ea
SM
828 (t
829 elem))))
47db06aa 830
47db06aa
GM
831;;*******************************************************************
832;;**
833;;** Substituting special XML sequences
834;;**
835;;*******************************************************************
836
837(defun xml-substitute-special (string)
cd1181db 838 "Return STRING, after substituting entity references."
a98e819b
DL
839 ;; This originally made repeated passes through the string from the
840 ;; beginning, which isn't correct, since then either "&amp;amp;" or
841 ;; "&#38;amp;" won't DTRT.
47db06aa 842
6d12a4df
MH
843 (let ((point 0)
844 children end-point)
ae026110 845 (while (string-match "&\\([^;]*\\);" string point)
6d12a4df 846 (setq end-point (match-end 0))
f6fcdfff 847 (let* ((this-part (match-string-no-properties 1 string))
6d12a4df
MH
848 (prev-part (substring string point (match-beginning 0)))
849 (entity (assoc this-part xml-entity-alist))
06b60517 850 (expansion
6d12a4df
MH
851 (cond ((string-match "#\\([0-9]+\\)" this-part)
852 (let ((c (decode-char
853 'ucs
f6fcdfff 854 (string-to-number (match-string-no-properties 1 this-part)))))
6d12a4df
MH
855 (if c (string c))))
856 ((string-match "#x\\([[:xdigit:]]+\\)" this-part)
857 (let ((c (decode-char
858 'ucs
f6fcdfff 859 (string-to-number (match-string-no-properties 1 this-part) 16))))
6d12a4df
MH
860 (if c (string c))))
861 (entity
862 (cdr entity))
ae026110 863 ((eq (length this-part) 0)
27720433 864 (error "XML: (Not Well-Formed) No entity given"))
6d12a4df 865 (t
f8ab034e 866 (if xml-validating-parser
6d12a4df 867 (error "XML: (Validity) Undefined entity `%s'"
f8ab034e
MH
868 this-part)
869 xml-undefined-entity)))))
6d12a4df
MH
870
871 (cond ((null children)
f0d49437
MH
872 ;; FIXME: If we have an entity that expands into XML, this won't work.
873 (setq children
874 (concat prev-part expansion)))
6d12a4df
MH
875 ((stringp children)
876 (if (stringp expansion)
877 (setq children (concat children prev-part expansion))
878 (setq children (list expansion (concat prev-part children)))))
879 ((and (stringp expansion)
880 (stringp (car children)))
881 (setcar children (concat prev-part expansion (car children))))
882 ((stringp expansion)
883 (setq children (append (concat prev-part expansion)
884 children)))
885 ((stringp (car children))
886 (setcar children (concat (car children) prev-part))
887 (setq children (append expansion children)))
888 (t
889 (setq children (list expansion
890 prev-part
891 children))))
892 (setq point end-point)))
893 (cond ((stringp children)
894 (concat children (substring string point)))
895 ((stringp (car (last children)))
a3110b5d 896 (concat (car (last children)) (substring string point)))
6d12a4df
MH
897 ((null children)
898 string)
899 (t
a3110b5d
MH
900 (concat (mapconcat 'identity
901 (nreverse children)
902 "")
903 (substring string point))))))
904
571855b6
UJ
905(defun xml-substitute-numeric-entities (string)
906 "Substitute SGML numeric entities by their respective utf characters.
907This function replaces numeric entities in the input STRING and
908returns the modified string. For example \"&#42;\" gets replaced
909by \"*\"."
910 (if (and string (stringp string))
911 (let ((start 0))
912 (while (string-match "&#\\([0-9]+\\);" string start)
913 (condition-case nil
914 (setq string (replace-match
915 (string (read (substring string
916 (match-beginning 1)
917 (match-end 1))))
918 nil nil string))
919 (error nil))
920 (setq start (1+ (match-beginning 0))))
921 string)
922 nil))
923
47db06aa
GM
924;;*******************************************************************
925;;**
926;;** Printing a tree.
927;;** This function is intended mainly for debugging purposes.
928;;**
929;;*******************************************************************
930
27240aa4
AS
931(defun xml-debug-print (xml &optional indent-string)
932 "Outputs the XML in the current buffer.
933XML can be a tree or a list of nodes.
934The first line is indented with the optional INDENT-STRING."
935 (setq indent-string (or indent-string ""))
971489ea 936 (dolist (node xml)
27240aa4
AS
937 (xml-debug-print-internal node indent-string)))
938
939(defalias 'xml-print 'xml-debug-print)
47db06aa 940
7731c9f4 941(defun xml-escape-string (string)
7f3fbd5d 942 "Return STRING with entity substitutions made from `xml-entity-alist'."
7731c9f4
MH
943 (mapconcat (lambda (byte)
944 (let ((char (char-to-string byte)))
945 (if (rassoc char xml-entity-alist)
946 (concat "&" (car (rassoc char xml-entity-alist)) ";")
947 char)))
76a6127f 948 string ""))
7731c9f4 949
971489ea 950(defun xml-debug-print-internal (xml indent-string)
47db06aa 951 "Outputs the XML tree in the current buffer.
a98e819b 952The first line is indented with INDENT-STRING."
47db06aa
GM
953 (let ((tree xml)
954 attlist)
a98e819b 955 (insert indent-string ?< (symbol-name (xml-node-name tree)))
524425ae 956
47db06aa 957 ;; output the attribute list
971489ea 958 (setq attlist (xml-node-attributes tree))
47db06aa 959 (while attlist
7731c9f4
MH
960 (insert ?\ (symbol-name (caar attlist)) "=\""
961 (xml-escape-string (cdar attlist)) ?\")
971489ea 962 (setq attlist (cdr attlist)))
524425ae 963
971489ea 964 (setq tree (xml-node-children tree))
47db06aa 965
27240aa4
AS
966 (if (null tree)
967 (insert ?/ ?>)
968 (insert ?>)
969
970 ;; output the children
971 (dolist (node tree)
972 (cond
973 ((listp node)
974 (insert ?\n)
975 (xml-debug-print-internal node (concat indent-string " ")))
7731c9f4
MH
976 ((stringp node)
977 (insert (xml-escape-string node)))
27240aa4
AS
978 (t
979 (error "Invalid XML tree"))))
980
981 (when (not (and (null (cdr tree))
982 (stringp (car tree))))
983 (insert ?\n indent-string))
984 (insert ?< ?/ (symbol-name (xml-node-name xml)) ?>))))
47db06aa
GM
985
986(provide 'xml)
987
988;;; xml.el ends here