Fix input method "probhat" for Bengali
[emacs.git] / lisp / xml.el
blob414300cb40207259c7de62d90f8572447c5c0ed0
1 ;;; xml.el --- XML parser
3 ;; Copyright (C) 2000-2016 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 3 of the License, or
14 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
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
28 ;; any other Lisp libraries.
30 ;;; FILE FORMAT
32 ;; The document type declaration may either be ignored or (optionally)
33 ;; parsed, but currently the parsing will only accept element
34 ;; declarations. The XML file is assumed to be well-formed. In case
35 ;; of error, the parsing stops and the XML file is shown where the
36 ;; parsing stopped.
38 ;; It also knows how to ignore comments and processing instructions.
40 ;; The XML file should have the following format:
41 ;; <node1 attr1="name1" attr2="name2" ...>value
42 ;; <node2 attr3="name3" attr4="name4">value2</node2>
43 ;; <node3 attr5="name5" attr6="name6">value3</node3>
44 ;; </node1>
45 ;; Of course, the name of the nodes and attributes can be anything. There can
46 ;; be any number of attributes (or none), as well as any number of children
47 ;; below the nodes.
49 ;; There can be only top level node, but with any number of children below.
51 ;;; LIST FORMAT
53 ;; The functions `xml-parse-file', `xml-parse-region' and
54 ;; `xml-parse-tag' return a list with the following format:
56 ;; xml-list ::= (node node ...)
57 ;; node ::= (qname attribute-list . child_node_list)
58 ;; child_node_list ::= child_node child_node ...
59 ;; child_node ::= node | string
60 ;; qname ::= (:namespace-uri . "name") | "name"
61 ;; attribute_list ::= ((qname . "value") (qname . "value") ...)
62 ;; | nil
63 ;; string ::= "..."
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.
69 ;; TODO:
70 ;; * xml:base, xml:space support
71 ;; * more complete DOCTYPE parsing
72 ;; * pi support
74 ;;; Code:
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.
83 ;;; Macros to parse the list
85 (defconst xml-undefined-entity "?"
86 "What to substitute for undefined entities")
88 (defconst xml-default-ns '(("" . "")
89 ("xml" . "http://www.w3.org/XML/1998/namespace")
90 ("xmlns" . "http://www.w3.org/2000/xmlns/"))
91 "Alist mapping default XML namespaces to their URIs.")
93 (defvar xml-entity-alist
94 '(("lt" . "&#60;")
95 ("gt" . ">")
96 ("apos" . "'")
97 ("quot" . "\"")
98 ("amp" . "&#38;"))
99 "Alist mapping XML entities to their replacement text.")
101 (defvar xml-entity-expansion-limit 20000
102 "The maximum size of entity reference expansions.
103 If the size of the buffer increases by this many characters while
104 expanding entity references in a segment of character data, the
105 XML parser signals an error. Setting this to nil removes the
106 limit (making the parser vulnerable to XML bombs).")
108 (defvar xml-parameter-entity-alist nil
109 "Alist of defined XML parametric entities.")
111 (defvar xml-sub-parser nil
112 "Non-nil when the XML parser is parsing an XML fragment.")
114 (defvar xml-validating-parser nil
115 "Set to non-nil to get validity checking.")
117 (defsubst xml-node-name (node)
118 "Return the tag associated with NODE.
119 Without namespace-aware parsing, the tag is a symbol.
121 With namespace-aware parsing, the tag is a cons of a string
122 representing the uri of the namespace with the local name of the
123 tag. For example,
125 <foo>
127 would be represented by
129 (\"\" . \"foo\").
131 If you'd just like a plain symbol instead, use `symbol-qnames' in
132 the PARSE-NS argument."
134 (car node))
136 (defsubst xml-node-attributes (node)
137 "Return the list of attributes of NODE.
138 The list can be nil."
139 (nth 1 node))
141 (defsubst xml-node-children (node)
142 "Return the list of children of NODE.
143 This is a list of nodes, and it can be nil."
144 (cddr node))
146 (defun xml-get-children (node child-name)
147 "Return the children of NODE whose tag is CHILD-NAME.
148 CHILD-NAME should match the value returned by `xml-node-name'."
149 (let ((match ()))
150 (dolist (child (xml-node-children node))
151 (if (and (listp child)
152 (equal (xml-node-name child) child-name))
153 (push child match)))
154 (nreverse match)))
156 (defun xml-get-attribute-or-nil (node attribute)
157 "Get from NODE the value of ATTRIBUTE.
158 Return nil if the attribute was not found.
160 See also `xml-get-attribute'."
161 (cdr (assoc attribute (xml-node-attributes node))))
163 (defsubst xml-get-attribute (node attribute)
164 "Get from NODE the value of ATTRIBUTE.
165 An empty string is returned if the attribute was not found.
167 See also `xml-get-attribute-or-nil'."
168 (or (xml-get-attribute-or-nil node attribute) ""))
170 ;;; Regular expressions for XML components
172 ;; The following regexps are used as subexpressions in regexps that
173 ;; are `eval-when-compile'd for efficiency, so they must be defined at
174 ;; compile time.
175 (eval-and-compile
177 ;; [4] NameStartChar
178 ;; See the definition of word syntax in `xml-syntax-table'.
179 (defconst xml-name-start-char-re (concat "[[:word:]:_]"))
181 ;; [4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7
182 ;; | [#x0300-#x036F] | [#x203F-#x2040]
183 (defconst xml-name-char-re (concat "[-0-9.[:word:]:_·̀-ͯ‿-⁀]"))
185 ;; [5] Name ::= NameStartChar (NameChar)*
186 (defconst xml-name-re (concat xml-name-start-char-re xml-name-char-re "*"))
188 ;; [6] Names ::= Name (#x20 Name)*
189 (defconst xml-names-re (concat xml-name-re "\\(?: " xml-name-re "\\)*"))
191 ;; [7] Nmtoken ::= (NameChar)+
192 (defconst xml-nmtoken-re (concat xml-name-char-re "+"))
194 ;; [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*
195 (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]+;\\)")
200 ;; [68] EntityRef ::= '&' Name ';'
201 (defconst xml-entity-ref (concat "&" xml-name-re ";"))
203 (defconst xml-entity-or-char-ref-re (concat "&\\(?:#\\(x\\)?\\([0-9a-fA-F]+\\)\\|\\("
204 xml-name-re "\\)\\);"))
206 ;; [69] PEReference ::= '%' Name ';'
207 (defconst xml-pe-reference-re (concat "%\\(" xml-name-re "\\);"))
209 ;; [67] Reference ::= EntityRef | CharRef
210 (defconst xml-reference-re (concat "\\(?:" xml-entity-ref "\\|" xml-char-ref-re "\\)"))
212 ;; [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
213 ;; | "'" ([^<&'] | Reference)* "'"
214 (defconst xml-att-value-re (concat "\\(?:\"\\(?:[^&\"]\\|"
215 xml-reference-re "\\)*\"\\|"
216 "'\\(?:[^&']\\|" xml-reference-re
217 "\\)*'\\)"))
219 ;; [56] TokenizedType ::= 'ID'
220 ;; [VC: ID] [VC: One ID / Element Type] [VC: ID Attribute Default]
221 ;; | 'IDREF' [VC: IDREF]
222 ;; | 'IDREFS' [VC: IDREF]
223 ;; | 'ENTITY' [VC: Entity Name]
224 ;; | 'ENTITIES' [VC: Entity Name]
225 ;; | 'NMTOKEN' [VC: Name Token]
226 ;; | 'NMTOKENS' [VC: Name Token]
227 (defconst xml-tokenized-type-re (concat "\\(?:ID\\|IDREF\\|IDREFS\\|ENTITY\\|"
228 "ENTITIES\\|NMTOKEN\\|NMTOKENS\\)"))
230 ;; [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
231 (defconst xml-notation-type-re
232 (concat "\\(?:NOTATION\\s-+(\\s-*" xml-name-re
233 "\\(?:\\s-*|\\s-*" xml-name-re "\\)*\\s-*)\\)"))
235 ;; [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
236 ;; [VC: Enumeration] [VC: No Duplicate Tokens]
237 (defconst xml-enumeration-re (concat "\\(?:(\\s-*" xml-nmtoken-re
238 "\\(?:\\s-*|\\s-*" xml-nmtoken-re
239 "\\)*\\s-+)\\)"))
241 ;; [57] EnumeratedType ::= NotationType | Enumeration
242 (defconst xml-enumerated-type-re (concat "\\(?:" xml-notation-type-re
243 "\\|" xml-enumeration-re "\\)"))
245 ;; [54] AttType ::= StringType | TokenizedType | EnumeratedType
246 ;; [55] StringType ::= 'CDATA'
247 (defconst xml-att-type-re (concat "\\(?:CDATA\\|" xml-tokenized-type-re
248 "\\|" xml-notation-type-re
249 "\\|" xml-enumerated-type-re "\\)"))
251 ;; [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
252 (defconst xml-default-decl-re (concat "\\(?:#REQUIRED\\|#IMPLIED\\|"
253 "\\(?:#FIXED\\s-+\\)*"
254 xml-att-value-re "\\)"))
256 ;; [53] AttDef ::= S Name S AttType S DefaultDecl
257 (defconst xml-att-def-re (concat "\\(?:\\s-*" xml-name-re
258 "\\s-*" xml-att-type-re
259 "\\s-*" xml-default-decl-re "\\)"))
261 ;; [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
262 ;; | "'" ([^%&'] | PEReference | Reference)* "'"
263 (defconst xml-entity-value-re (concat "\\(?:\"\\(?:[^%&\"]\\|"
264 xml-pe-reference-re
265 "\\|" xml-reference-re
266 "\\)*\"\\|'\\(?:[^%&']\\|"
267 xml-pe-reference-re "\\|"
268 xml-reference-re "\\)*'\\)"))
269 ) ; End of `eval-when-compile'
272 ;; [75] ExternalID ::= 'SYSTEM' S SystemLiteral
273 ;; | 'PUBLIC' S PubidLiteral S SystemLiteral
274 ;; [76] NDataDecl ::= S 'NDATA' S
275 ;; [73] EntityDef ::= EntityValue| (ExternalID NDataDecl?)
276 ;; [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
277 ;; [74] PEDef ::= EntityValue | ExternalID
278 ;; [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
279 ;; [70] EntityDecl ::= GEDecl | PEDecl
281 ;; Note that this is setup so that we can do whitespace-skipping with
282 ;; `(skip-syntax-forward " ")', inter alia. Previously this was slow
283 ;; compared with `re-search-forward', but that has been fixed.
285 (defvar xml-syntax-table
286 ;; By default, characters have symbol syntax.
287 (let ((table (make-char-table 'syntax-table '(3))))
288 ;; The XML space chars [3], and nothing else, have space syntax.
289 (dolist (c '(?\s ?\t ?\r ?\n))
290 (modify-syntax-entry c " " table))
291 ;; The characters in NameStartChar [4], aside from ':' and '_',
292 ;; have word syntax. This is used by `xml-name-start-char-re'.
293 (modify-syntax-entry '(?A . ?Z) "w" table)
294 (modify-syntax-entry '(?a . ?z) "w" table)
295 (modify-syntax-entry '(#xC0 . #xD6) "w" table)
296 (modify-syntax-entry '(#xD8 . #XF6) "w" table)
297 (modify-syntax-entry '(#xF8 . #X2FF) "w" table)
298 (modify-syntax-entry '(#x370 . #X37D) "w" table)
299 (modify-syntax-entry '(#x37F . #x1FFF) "w" table)
300 (modify-syntax-entry '(#x200C . #x200D) "w" table)
301 (modify-syntax-entry '(#x2070 . #x218F) "w" table)
302 (modify-syntax-entry '(#x2C00 . #x2FEF) "w" table)
303 (modify-syntax-entry '(#x3001 . #xD7FF) "w" table)
304 (modify-syntax-entry '(#xF900 . #xFDCF) "w" table)
305 (modify-syntax-entry '(#xFDF0 . #xFFFD) "w" table)
306 (modify-syntax-entry '(#x10000 . #xEFFFF) "w" table)
307 table)
308 "Syntax table used by the XML parser.
309 In this syntax table, the XML space characters [ \\t\\r\\n], and
310 only those characters, have whitespace syntax.")
312 ;;; Entry points:
314 ;;;###autoload
315 (defun xml-parse-file (file &optional parse-dtd parse-ns)
316 "Parse the well-formed XML file FILE.
317 Return the top node with all its children.
318 If PARSE-DTD is non-nil, the DTD is parsed rather than skipped.
320 If PARSE-NS is non-nil, then QNAMES are expanded. By default,
321 the variable `xml-default-ns' is the mapping from namespaces to
322 URIs, and expanded names will be returned as a cons
324 (\"namespace:\" . \"foo\").
326 If PARSE-NS is an alist, it will be used as the mapping from
327 namespace to URIs instead.
329 If it is the symbol `symbol-qnames', expanded names will be
330 returned as a plain symbol `namespace:foo' instead of a cons.
332 Both features can be combined by providing a cons cell
334 (symbol-qnames . ALIST)."
335 (with-temp-buffer
336 (insert-file-contents file)
337 (xml--parse-buffer parse-dtd parse-ns)))
339 ;;;###autoload
340 (defun xml-parse-region (&optional beg end buffer parse-dtd parse-ns)
341 "Parse the region from BEG to END in BUFFER.
342 Return the XML parse tree, or raise an error if the region does
343 not contain well-formed XML.
345 If BEG is nil, it defaults to `point-min'.
346 If END is nil, it defaults to `point-max'.
347 If BUFFER is nil, it defaults to the current buffer.
348 If PARSE-DTD is non-nil, parse the DTD and return it as the first
349 element of the list.
350 If PARSE-NS is non-nil, then QNAMES are expanded. By default,
351 the variable `xml-default-ns' is the mapping from namespaces to
352 URIs, and expanded names will be returned as a cons
354 (\"namespace:\" . \"foo\").
356 If PARSE-NS is an alist, it will be used as the mapping from
357 namespace to URIs instead.
359 If it is the symbol `symbol-qnames', expanded names will be
360 returned as a plain symbol `namespace:foo' instead of a cons.
362 Both features can be combined by providing a cons cell
364 (symbol-qnames . ALIST)."
365 ;; Use fixed syntax table to ensure regexp char classes and syntax
366 ;; specs DTRT.
367 (unless buffer
368 (setq buffer (current-buffer)))
369 (with-temp-buffer
370 (insert-buffer-substring-no-properties buffer beg end)
371 (xml--parse-buffer parse-dtd parse-ns)))
373 ;; XML [5]
375 ;; Fixme: This needs re-writing to deal with the XML grammar properly, i.e.
376 ;; document ::= prolog element Misc*
377 ;; prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
379 (defun xml--parse-buffer (parse-dtd parse-ns)
380 (with-syntax-table xml-syntax-table
381 (let ((case-fold-search nil) ; XML is case-sensitive.
382 ;; Prevent entity definitions from changing the defaults
383 (xml-entity-alist xml-entity-alist)
384 (xml-parameter-entity-alist xml-parameter-entity-alist)
385 xml result dtd)
386 (goto-char (point-min))
387 (while (not (eobp))
388 (if (search-forward "<" nil t)
389 (progn
390 (forward-char -1)
391 (setq result (xml-parse-tag-1 parse-dtd parse-ns))
392 (cond
393 ((null result)
394 ;; Not looking at an xml start tag.
395 (unless (eobp)
396 (forward-char 1)))
397 ((and xml (not xml-sub-parser))
398 ;; Translation of rule [1] of XML specifications
399 (error "XML: (Not Well-Formed) Only one root tag allowed"))
400 ((and (listp (car result))
401 parse-dtd)
402 (setq dtd (car result))
403 (if (cdr result) ; possible leading comment
404 (add-to-list 'xml (cdr result))))
406 (add-to-list 'xml result))))
407 (goto-char (point-max))))
408 (if parse-dtd
409 (cons dtd (nreverse xml))
410 (nreverse xml)))))
412 (defun xml-maybe-do-ns (name default xml-ns)
413 "Perform any namespace expansion.
414 NAME is the name to perform the expansion on.
415 DEFAULT is the default namespace. XML-NS is a cons of namespace
416 names to uris. When namespace-aware parsing is off, then XML-NS
417 is nil.
419 During namespace-aware parsing, any name without a namespace is
420 put into the namespace identified by DEFAULT. nil is used to
421 specify that the name shouldn't be given a namespace.
422 Expanded names will by default be returned as a cons. If you
423 would like to get plain symbols instead, provide a cons cell
425 (symbol-qnames . ALIST)
427 in the XML-NS argument."
428 (if (consp xml-ns)
429 (let* ((symbol-qnames (eq (car-safe xml-ns) 'symbol-qnames))
430 (nsp (string-match ":" name))
431 (lname (if nsp (substring name (match-end 0)) name))
432 (prefix (if nsp (substring name 0 (match-beginning 0)) default))
433 (special (and (string-equal lname "xmlns") (not prefix)))
434 ;; Setting default to nil will insure that there is not
435 ;; matching cons in xml-ns. In which case we
436 (ns (or (cdr (assoc (if special "xmlns" prefix)
437 (if symbol-qnames (cdr xml-ns) xml-ns)))
438 "")))
439 (if (and symbol-qnames
440 (not (string= prefix "xmlns")))
441 (intern (concat ns lname))
442 (cons ns (if special "" lname))))
443 (intern name)))
445 (defun xml-parse-tag (&optional parse-dtd parse-ns)
446 "Parse the tag at point.
447 If PARSE-DTD is non-nil, the DTD of the document, if any, is parsed and
448 returned as the first element in the list.
449 If PARSE-NS is non-nil, expand QNAMES; for further details, see
450 `xml-parse-region'.
452 Return one of:
453 - a list : the matching node
454 - nil : the point is not looking at a tag.
455 - a pair : the first element is the DTD, the second is the node."
456 (let* ((case-fold-search nil)
457 ;; Prevent entity definitions from changing the defaults
458 (xml-entity-alist xml-entity-alist)
459 (xml-parameter-entity-alist xml-parameter-entity-alist)
460 (buf (current-buffer))
461 (pos (point)))
462 (with-temp-buffer
463 (with-syntax-table xml-syntax-table
464 (insert-buffer-substring-no-properties buf pos)
465 (goto-char (point-min))
466 (xml-parse-tag-1 parse-dtd parse-ns)))))
468 (defun xml-parse-tag-1 (&optional parse-dtd parse-ns)
469 "Like `xml-parse-tag', but possibly modify the buffer while working."
470 (let* ((xml-validating-parser (or parse-dtd xml-validating-parser))
471 (xml-ns
472 (cond ((eq parse-ns 'symbol-qnames)
473 (cons 'symbol-qnames xml-default-ns))
474 ((or (consp (car-safe parse-ns))
475 (and (eq (car-safe parse-ns) 'symbol-qnames)
476 (listp (cdr parse-ns))))
477 parse-ns)
478 (parse-ns
479 xml-default-ns))))
480 (cond
481 ;; Processing instructions, like <?xml version="1.0"?>.
482 ((looking-at-p "<\\?")
483 (search-forward "?>")
484 (skip-syntax-forward " ")
485 (xml-parse-tag-1 parse-dtd xml-ns))
486 ;; Character data (CDATA) sections, in which no tag should be interpreted
487 ((looking-at "<!\\[CDATA\\[")
488 (let ((pos (match-end 0)))
489 (unless (search-forward "]]>" nil t)
490 (error "XML: (Not Well Formed) CDATA section does not end anywhere in the document"))
491 (concat
492 (buffer-substring-no-properties pos (match-beginning 0))
493 (xml-parse-string))))
494 ;; DTD for the document
495 ((looking-at-p "<!DOCTYPE[ \t\n\r]")
496 (let ((dtd (xml-parse-dtd parse-ns)))
497 (skip-syntax-forward " ")
498 (if xml-validating-parser
499 (cons dtd (xml-parse-tag-1 nil xml-ns))
500 (xml-parse-tag-1 nil xml-ns))))
501 ;; skip comments
502 ((looking-at-p "<!--")
503 (search-forward "-->")
504 ;; FIXME: This loses the skipped-over spaces.
505 (skip-syntax-forward " ")
506 (unless (eobp)
507 (let ((xml-sub-parser t))
508 (xml-parse-tag-1 parse-dtd xml-ns))))
509 ;; end tag
510 ((looking-at-p "</")
511 '())
512 ;; opening tag
513 ((looking-at (eval-when-compile (concat "<\\(" xml-name-re "\\)")))
514 (goto-char (match-end 1))
515 ;; Parse this node
516 (let* ((node-name (match-string-no-properties 1))
517 ;; Parse the attribute list.
518 (attrs (xml-parse-attlist xml-ns))
519 children)
520 ;; add the xmlns:* attrs to our cache
521 (when (consp xml-ns)
522 (dolist (attr attrs)
523 (when (and (consp (car attr))
524 (equal "http://www.w3.org/2000/xmlns/"
525 (caar attr)))
526 (push (cons (cdar attr) (cdr attr))
527 (if (symbolp (car xml-ns))
528 (cdr xml-ns)
529 xml-ns)))))
530 (setq children (list attrs (xml-maybe-do-ns node-name "" xml-ns)))
531 (cond
532 ;; is this an empty element ?
533 ((looking-at-p "/>")
534 (forward-char 2)
535 (nreverse children))
536 ;; is this a valid start tag ?
537 ((eq (char-after) ?>)
538 (forward-char 1)
539 ;; Now check that we have the right end-tag.
540 (let ((end (concat "</" node-name "\\s-*>")))
541 (while (not (looking-at end))
542 (cond
543 ((eobp)
544 (error "XML: (Not Well-Formed) End of document while reading element `%s'"
545 node-name))
546 ((looking-at-p "</")
547 (forward-char 2)
548 (error "XML: (Not Well-Formed) Invalid end tag `%s' (expecting `%s')"
549 (let ((pos (point)))
550 (buffer-substring pos (if (re-search-forward "\\s-*>" nil t)
551 (match-beginning 0)
552 (point-max))))
553 node-name))
554 ;; Read a sub-element and push it onto CHILDREN.
555 ((= (char-after) ?<)
556 (let ((tag (xml-parse-tag-1 nil xml-ns)))
557 (when tag
558 (push tag children))))
559 ;; Read some character data.
561 (let ((expansion (xml-parse-string)))
562 (push (if (stringp (car children))
563 ;; If two strings were separated by a
564 ;; comment, concat them.
565 (concat (pop children) expansion)
566 expansion)
567 children)))))
568 ;; Move point past the end-tag.
569 (goto-char (match-end 0))
570 (nreverse children)))
571 ;; Otherwise this was an invalid start tag (expected ">" not found.)
573 (error "XML: (Well-Formed) Couldn't parse tag: %s"
574 (buffer-substring-no-properties (- (point) 10) (+ (point) 1)))))))
576 ;; (Not one of PI, CDATA, Comment, End tag, or Start tag)
578 (unless xml-sub-parser ; Usually, we error out.
579 (error "XML: (Well-Formed) Invalid character"))
580 ;; However, if we're parsing incrementally, then we need to deal
581 ;; with stray CDATA.
582 (let ((s (xml-parse-string)))
583 (when (zerop (length s))
584 ;; We haven't consumed any input! We must throw an error in
585 ;; order to prevent looping forever.
586 (error "XML: (Not Well-Formed) Could not parse: %s"
587 (buffer-substring-no-properties
588 (point) (min (+ (point) 10) (point-max)))))
589 s)))))
591 (defun xml-parse-string ()
592 "Parse character data at point, and return it as a string.
593 Leave point at the start of the next thing to parse. This
594 function can modify the buffer by expanding entity and character
595 references."
596 (let ((start (point))
597 ;; Keep track of the size of the rest of the buffer:
598 (old-remaining-size (- (buffer-size) (point)))
599 ref val)
600 (while (and (not (eobp))
601 (not (looking-at-p "<")))
602 ;; Find the next < or & character.
603 (skip-chars-forward "^<&")
604 (when (eq (char-after) ?&)
605 ;; If we find an entity or character reference, expand it.
606 (unless (looking-at xml-entity-or-char-ref-re)
607 (error "XML: (Not Well-Formed) Invalid entity reference"))
608 ;; For a character reference, the next entity or character
609 ;; reference must be after the replacement. [4.6] "Numerical
610 ;; character references are expanded immediately when
611 ;; recognized and MUST be treated as character data."
612 (if (setq ref (match-string 2))
613 (progn ; Numeric char reference
614 (setq val (save-match-data
615 (decode-char 'ucs (string-to-number
616 ref (if (match-string 1) 16)))))
617 (and (null val)
618 xml-validating-parser
619 (error "XML: (Validity) Invalid character reference `%s'"
620 (match-string 0)))
621 (replace-match (if val (string val) xml-undefined-entity) t t))
622 ;; For an entity reference, search again from the start of
623 ;; the replaced text, since the replacement can contain
624 ;; entity or character references, or markup.
625 (setq ref (match-string 3)
626 val (assoc ref xml-entity-alist))
627 (and (null val)
628 xml-validating-parser
629 (error "XML: (Validity) Undefined entity `%s'" ref))
630 (replace-match (or (cdr val) xml-undefined-entity) t t)
631 (goto-char (match-beginning 0)))
632 ;; Check for XML bombs.
633 (and xml-entity-expansion-limit
634 (> (- (buffer-size) (point))
635 (+ old-remaining-size xml-entity-expansion-limit))
636 (error "XML: Entity reference expansion \
637 surpassed `xml-entity-expansion-limit'"))))
638 ;; [2.11] Clean up line breaks.
639 (let ((end-marker (point-marker)))
640 (goto-char start)
641 (while (re-search-forward "\r\n?" end-marker t)
642 (replace-match "\n" t t))
643 (goto-char end-marker)
644 (buffer-substring start (point)))))
646 (defun xml-parse-attlist (&optional xml-ns)
647 "Return the attribute-list after point.
648 Leave point at the first non-blank character after the tag."
649 (let ((attlist ())
650 end-pos name)
651 (skip-syntax-forward " ")
652 (while (looking-at (eval-when-compile
653 (concat "\\(" xml-name-re "\\)\\s-*=\\s-*")))
654 (setq end-pos (match-end 0))
655 (setq name (xml-maybe-do-ns (match-string-no-properties 1) nil xml-ns))
656 (goto-char end-pos)
658 ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
660 ;; Do we have a string between quotes (or double-quotes),
661 ;; or a simple word ?
662 (if (looking-at "\"\\([^\"]*\\)\"")
663 (setq end-pos (match-end 0))
664 (if (looking-at "'\\([^']*\\)'")
665 (setq end-pos (match-end 0))
666 (error "XML: (Not Well-Formed) Attribute values must be given between quotes")))
668 ;; Each attribute must be unique within a given element
669 (if (assoc name attlist)
670 (error "XML: (Not Well-Formed) Each attribute must be unique within an element"))
672 ;; Multiple whitespace characters should be replaced with a single one
673 ;; in the attributes
674 (let ((string (match-string-no-properties 1)))
675 (replace-regexp-in-string "\\s-\\{2,\\}" " " string)
676 (let ((expansion (xml-substitute-special string)))
677 (unless (stringp expansion)
678 ;; We say this is the constraint. It is actually that
679 ;; neither external entities nor "<" can be in an
680 ;; attribute value.
681 (error "XML: (Not Well-Formed) Entities in attributes cannot expand into elements"))
682 (push (cons name expansion) attlist)))
684 (goto-char end-pos)
685 (skip-syntax-forward " "))
686 (nreverse attlist)))
688 ;;; DTD (document type declaration)
690 ;; The following functions know how to skip or parse the DTD of a
691 ;; document. FIXME: it fails at least if the DTD contains conditional
692 ;; sections.
694 (defun xml-skip-dtd ()
695 "Skip the DTD at point.
696 This follows the rule [28] in the XML specifications."
697 (let ((xml-validating-parser nil))
698 (xml-parse-dtd)))
700 (defun xml-parse-dtd (&optional _parse-ns)
701 "Parse the DTD at point."
702 (forward-char (eval-when-compile (length "<!DOCTYPE")))
703 (skip-syntax-forward " ")
704 (if (and (looking-at-p ">")
705 xml-validating-parser)
706 (error "XML: (Validity) Invalid DTD (expecting name of the document)"))
708 ;; Get the name of the document
709 (looking-at xml-name-re)
710 (let ((dtd (list (match-string-no-properties 0) 'dtd))
711 (xml-parameter-entity-alist xml-parameter-entity-alist)
712 next-parameter-entity)
713 (goto-char (match-end 0))
714 (skip-syntax-forward " ")
716 ;; External subset (XML [75])
717 (cond ((looking-at "PUBLIC\\s-+")
718 (goto-char (match-end 0))
719 (unless (or (re-search-forward
720 "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
721 nil t)
722 (re-search-forward
723 "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
724 nil t))
725 (error "XML: Missing Public ID"))
726 (let ((pubid (match-string-no-properties 1)))
727 (skip-syntax-forward " ")
728 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
729 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
730 (error "XML: Missing System ID"))
731 (push (list pubid (match-string-no-properties 1) 'public) dtd)))
732 ((looking-at "SYSTEM\\s-+")
733 (goto-char (match-end 0))
734 (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
735 (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
736 (error "XML: Missing System ID"))
737 (push (list (match-string-no-properties 1) 'system) dtd)))
738 (skip-syntax-forward " ")
740 (if (eq (char-after) ?>)
742 ;; No internal subset
743 (forward-char)
745 ;; Internal subset (XML [28b])
746 (unless (eq (char-after) ?\[)
747 (error "XML: Bad DTD"))
748 (forward-char)
750 ;; [2.8]: "markup declarations may be made up in whole or in
751 ;; part of the replacement text of parameter entities."
753 ;; Since parameter entities are valid only within the DTD, we
754 ;; first search for the position of the next possible parameter
755 ;; entity. Then, search for the next DTD element; if it ends
756 ;; before the next parameter entity, expand the parameter entity
757 ;; and try again.
758 (setq next-parameter-entity
759 (save-excursion
760 (if (re-search-forward xml-pe-reference-re nil t)
761 (match-beginning 0))))
763 ;; Parse the rest of the DTD
764 ;; Fixme: Deal with NOTATION, PIs.
765 (while (not (looking-at-p "\\s-*\\]"))
766 (skip-syntax-forward " ")
767 (cond
768 ((eobp)
769 (error "XML: (Well-Formed) End of document while reading DTD"))
770 ;; Element declaration [45]:
771 ((and (looking-at (eval-when-compile
772 (concat "<!ELEMENT\\s-+\\(" xml-name-re
773 "\\)\\s-+\\([^>]+\\)>")))
774 (or (null next-parameter-entity)
775 (<= (match-end 0) next-parameter-entity)))
776 (let ((element (match-string-no-properties 1))
777 (type (match-string-no-properties 2))
778 (end-pos (match-end 0)))
779 ;; Translation of rule [46] of XML specifications
780 (cond
781 ((string-match-p "\\`EMPTY\\s-*\\'" type) ; empty declaration
782 (setq type 'empty))
783 ((string-match-p "\\`ANY\\s-*$" type) ; any type of contents
784 (setq type 'any))
785 ((string-match "\\`(\\(.*\\))\\s-*\\'" type) ; children ([47])
786 (setq type (xml-parse-elem-type
787 (match-string-no-properties 1 type))))
788 ((string-match-p "^%[^;]+;[ \t\n\r]*\\'" type) ; substitution
789 nil)
790 (xml-validating-parser
791 (error "XML: (Validity) Invalid element type in the DTD")))
793 ;; rule [45]: the element declaration must be unique
794 (and (assoc element dtd)
795 xml-validating-parser
796 (error "XML: (Validity) DTD element declarations must be unique (<%s>)"
797 element))
799 ;; Store the element in the DTD
800 (push (list element type) dtd)
801 (goto-char end-pos)))
803 ;; Attribute-list declaration [52] (currently unsupported):
804 ((and (looking-at (eval-when-compile
805 (concat "<!ATTLIST[ \t\n\r]*\\(" xml-name-re
806 "\\)[ \t\n\r]*\\(" xml-att-def-re
807 "\\)*[ \t\n\r]*>")))
808 (or (null next-parameter-entity)
809 (<= (match-end 0) next-parameter-entity)))
810 (goto-char (match-end 0)))
812 ;; Comments (skip to end, ignoring parameter entity):
813 ((looking-at-p "<!--")
814 (search-forward "-->")
815 (and next-parameter-entity
816 (> (point) next-parameter-entity)
817 (setq next-parameter-entity
818 (save-excursion
819 (if (re-search-forward xml-pe-reference-re nil t)
820 (match-beginning 0))))))
822 ;; Internal entity declarations:
823 ((and (looking-at (eval-when-compile
824 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
825 xml-name-re "\\)[ \t\n\r]*\\("
826 xml-entity-value-re "\\)[ \t\n\r]*>")))
827 (or (null next-parameter-entity)
828 (<= (match-end 0) next-parameter-entity)))
829 (let* ((name (prog1 (match-string-no-properties 2)
830 (goto-char (match-end 0))))
831 (alist (if (match-string 1)
832 'xml-parameter-entity-alist
833 'xml-entity-alist))
834 ;; Retrieve the deplacement text:
835 (value (xml--entity-replacement-text
836 ;; Entity value, sans quotation marks:
837 (substring (match-string-no-properties 3) 1 -1))))
838 ;; If the same entity is declared more than once, the
839 ;; first declaration is binding.
840 (unless (assoc name (symbol-value alist))
841 (set alist (cons (cons name value) (symbol-value alist))))))
843 ;; External entity declarations (currently unsupported):
844 ((and (or (looking-at (eval-when-compile
845 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
846 xml-name-re "\\)[ \t\n\r]+SYSTEM[ \t\n\r]+"
847 "\\(\"[^\"]*\"\\|'[^']*'\\)[ \t\n\r]*>")))
848 (looking-at (eval-when-compile
849 (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
850 xml-name-re "\\)[ \t\n\r]+PUBLIC[ \t\n\r]+"
851 "\"[- \r\na-zA-Z0-9'()+,./:=?;!*#@$_%]*\""
852 "\\|'[- \r\na-zA-Z0-9()+,./:=?;!*#@$_%]*'"
853 "[ \t\n\r]+\\(\"[^\"]*\"\\|'[^']*'\\)"
854 "[ \t\n\r]*>"))))
855 (or (null next-parameter-entity)
856 (<= (match-end 0) next-parameter-entity)))
857 (goto-char (match-end 0)))
859 ;; If a parameter entity is in the way, expand it.
860 (next-parameter-entity
861 (save-excursion
862 (goto-char next-parameter-entity)
863 (unless (looking-at xml-pe-reference-re)
864 (error "XML: Internal error"))
865 (let* ((entity (match-string 1))
866 (elt (assoc entity xml-parameter-entity-alist)))
867 (if elt
868 (progn
869 (replace-match (cdr elt) t t)
870 ;; The replacement can itself be a parameter entity.
871 (goto-char next-parameter-entity))
872 (goto-char (match-end 0))))
873 (setq next-parameter-entity
874 (if (re-search-forward xml-pe-reference-re nil t)
875 (match-beginning 0)))))
877 ;; Anything else is garbage (ignored if not validating).
878 (xml-validating-parser
879 (error "XML: (Validity) Invalid DTD item"))
881 (skip-chars-forward "^]"))))
883 (if (looking-at "\\s-*]>")
884 (goto-char (match-end 0))))
885 (nreverse dtd)))
887 (defun xml--entity-replacement-text (string)
888 "Return the replacement text for the entity value STRING.
889 The replacement text is obtained by replacing character
890 references and parameter-entity references."
891 (let ((ref-re (eval-when-compile
892 (concat "\\(?:&#\\([0-9]+\\)\\|&#x\\([0-9a-fA-F]+\\)\\|%\\("
893 xml-name-re "\\)\\);")))
894 children)
895 (while (string-match ref-re string)
896 (push (substring string 0 (match-beginning 0)) children)
897 (let ((remainder (substring string (match-end 0)))
898 ref val)
899 (cond ((setq ref (match-string 1 string))
900 ;; Decimal character reference
901 (setq val (decode-char 'ucs (string-to-number ref)))
902 (if val (push (string val) children)))
903 ;; Hexadecimal character reference
904 ((setq ref (match-string 2 string))
905 (setq val (decode-char 'ucs (string-to-number ref 16)))
906 (if val (push (string val) children)))
907 ;; Parameter entity reference
908 ((setq ref (match-string 3 string))
909 (setq val (assoc ref xml-parameter-entity-alist))
910 (and (null val)
911 xml-validating-parser
912 (error "XML: (Validity) Undefined parameter entity `%s'" ref))
913 (push (or (cdr val) xml-undefined-entity) children)))
914 (setq string remainder)))
915 (mapconcat 'identity (nreverse (cons string children)) "")))
917 (defun xml-parse-elem-type (string)
918 "Convert element type STRING into a Lisp structure."
920 (let (elem modifier)
921 (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
922 (progn
923 (setq elem (match-string-no-properties 1 string)
924 modifier (match-string-no-properties 2 string))
925 (if (string-match-p "|" elem)
926 (setq elem (cons 'choice
927 (mapcar 'xml-parse-elem-type
928 (split-string elem "|"))))
929 (if (string-match-p "," elem)
930 (setq elem (cons 'seq
931 (mapcar 'xml-parse-elem-type
932 (split-string elem ",")))))))
933 (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string)
934 (setq elem (match-string-no-properties 1 string)
935 modifier (match-string-no-properties 2 string))))
937 (if (and (stringp elem) (string= elem "#PCDATA"))
938 (setq elem 'pcdata))
940 (cond
941 ((string= modifier "+")
942 (list '+ elem))
943 ((string= modifier "*")
944 (list '* elem))
945 ((string= modifier "?")
946 (list '\? elem))
948 elem))))
950 ;;; Substituting special XML sequences
952 (defun xml-substitute-special (string)
953 "Return STRING, after substituting entity and character references.
954 STRING is assumed to occur in an XML attribute value."
955 (let ((strlen (length string))
956 children)
957 (while (string-match xml-entity-or-char-ref-re string)
958 (push (substring string 0 (match-beginning 0)) children)
959 (let* ((remainder (substring string (match-end 0)))
960 (is-hex (match-string 1 string)) ; Is it a hex numeric reference?
961 (ref (match-string 2 string))) ; Numeric part of reference
962 (if ref
963 ;; [4.6] Character references are included as
964 ;; character data.
965 (let ((val (decode-char 'ucs (string-to-number ref (if is-hex 16)))))
966 (push (cond (val (string val))
967 (xml-validating-parser
968 (error "XML: (Validity) Undefined character `x%s'" ref))
969 (t xml-undefined-entity))
970 children)
971 (setq string remainder
972 strlen (length string)))
973 ;; [4.4.5] Entity references are "included in literal".
974 ;; Note that we don't need do anything special to treat
975 ;; quotes as normal data characters.
976 (setq ref (match-string 3 string)) ; entity name
977 (let ((val (or (cdr (assoc ref xml-entity-alist))
978 (if xml-validating-parser
979 (error "XML: (Validity) Undefined entity `%s'" ref)
980 xml-undefined-entity))))
981 (setq string (concat val remainder)))
982 (and xml-entity-expansion-limit
983 (> (length string) (+ strlen xml-entity-expansion-limit))
984 (error "XML: Passed `xml-entity-expansion-limit' while expanding `&%s;'"
985 ref)))))
986 (mapconcat 'identity (nreverse (cons string children)) "")))
988 (defun xml-substitute-numeric-entities (string)
989 "Substitute SGML numeric entities by their respective utf characters.
990 This function replaces numeric entities in the input STRING and
991 returns the modified string. For example \"&#42;\" gets replaced
992 by \"*\"."
993 (if (and string (stringp string))
994 (let ((start 0))
995 (while (string-match "&#\\([0-9]+\\);" string start)
996 (ignore-errors
997 (setq string (replace-match
998 (string (read (substring string
999 (match-beginning 1)
1000 (match-end 1))))
1001 nil nil string)))
1002 (setq start (1+ (match-beginning 0))))
1003 string)
1004 nil))
1006 ;;; Printing a parse tree (mainly for debugging).
1008 (defun xml-debug-print (xml &optional indent-string)
1009 "Outputs the XML in the current buffer.
1010 XML can be a tree or a list of nodes.
1011 The first line is indented with the optional INDENT-STRING."
1012 (setq indent-string (or indent-string ""))
1013 (dolist (node xml)
1014 (xml-debug-print-internal node indent-string)))
1016 (defalias 'xml-print 'xml-debug-print)
1018 (defun xml-escape-string (string)
1019 "Convert STRING into a string containing valid XML character data.
1020 Replace occurrences of &<>\\='\" in STRING with their default XML
1021 entity references (e.g., replace each & with &amp;).
1023 XML character data must not contain & or < characters, nor the >
1024 character under some circumstances. The XML spec does not impose
1025 restriction on \" or \\=', but we just substitute for these too
1026 \(as is permitted by the spec)."
1027 (with-temp-buffer
1028 (insert string)
1029 (dolist (substitution '(("&" . "&amp;")
1030 ("<" . "&lt;")
1031 (">" . "&gt;")
1032 ("'" . "&apos;")
1033 ("\"" . "&quot;")))
1034 (goto-char (point-min))
1035 (while (search-forward (car substitution) nil t)
1036 (replace-match (cdr substitution) t t nil)))
1037 (buffer-string)))
1039 (defun xml-debug-print-internal (xml indent-string)
1040 "Outputs the XML tree in the current buffer.
1041 The first line is indented with INDENT-STRING."
1042 (let ((tree xml)
1043 attlist)
1044 (insert indent-string ?< (symbol-name (xml-node-name tree)))
1046 ;; output the attribute list
1047 (setq attlist (xml-node-attributes tree))
1048 (while attlist
1049 (insert ?\ (symbol-name (caar attlist)) "=\""
1050 (xml-escape-string (cdar attlist)) ?\")
1051 (setq attlist (cdr attlist)))
1053 (setq tree (xml-node-children tree))
1055 (if (null tree)
1056 (insert ?/ ?>)
1057 (insert ?>)
1059 ;; output the children
1060 (dolist (node tree)
1061 (cond
1062 ((listp node)
1063 (insert ?\n)
1064 (xml-debug-print-internal node (concat indent-string " ")))
1065 ((stringp node)
1066 (insert (xml-escape-string node)))
1068 (error "Invalid XML tree"))))
1070 (when (not (and (null (cdr tree))
1071 (stringp (car tree))))
1072 (insert ?\n indent-string))
1073 (insert ?< ?/ (symbol-name (xml-node-name xml)) ?>))))
1075 (provide 'xml)
1077 ;;; xml.el ends here