xml.el 34 KB

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