Remove a bogus declare ignore
[cxml.git] / xml / unparse.lisp
blobbf341888d68485e47a5a87d4041bf75a1023cebd
1 ;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: CXML; readtable: runes; Encoding: utf-8; -*-
2 ;;; ---------------------------------------------------------------------------
3 ;;; Title: Unparse XML
4 ;;; Title: (including support for canonic XML according to J.Clark)
5 ;;; Created: 1999-09-09
6 ;;; Author: Gilbert Baumann <unk6@rz.uni-karlsruhe.de>
7 ;;; Author: David Lichteblau <david@lichteblau.com>
8 ;;; License: Lisp-LGPL (See file COPYING for details).
9 ;;; ---------------------------------------------------------------------------
10 ;;; (c) copyright 1999 by Gilbert Baumann
11 ;;; (c) copyright 2004 by knowledgeTools Int. GmbH
12 ;;; (c) copyright 2004 by David Lichteblau (for headcraft.de)
13 ;;; (c) copyright 2005-2008 by David Lichteblau
15 ;;; This library is free software; you can redistribute it and/or
16 ;;; modify it under the terms of the GNU Library General Public
17 ;;; License as published by the Free Software Foundation; either
18 ;;; version 2 of the License, or (at your option) any later version.
19 ;;;
20 ;;; This library is distributed in the hope that it will be useful,
21 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 ;;; Library General Public License for more details.
24 ;;;
25 ;;; You should have received a copy of the GNU Library General Public
26 ;;; License along with this library; if not, write to the
27 ;;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
28 ;;; Boston, MA 02111-1307 USA.
30 (in-package :cxml)
32 ;;
33 ;; | Canonical XML
34 ;; | =============
35 ;; |
36 ;; | This document defines a subset of XML called canonical XML. The
37 ;; | intended use of canonical XML is in testing XML processors, as a
38 ;; | representation of the result of parsing an XML document.
39 ;; |
40 ;; | Every well-formed XML document has a unique structurally equivalent
41 ;; | canonical XML document. Two structurally equivalent XML documents have
42 ;; | a byte-for-byte identical canonical XML document. Canonicalizing an
43 ;; | XML document requires only information that an XML processor is
44 ;; | required to make available to an application.
45 ;; |
46 ;; | A canonical XML document conforms to the following grammar:
47 ;; |
48 ;; | CanonXML ::= Pi* element Pi*
49 ;; | element ::= Stag (Datachar | Pi | element)* Etag
50 ;; | Stag ::= '<' Name Atts '>'
51 ;; | Etag ::= '</' Name '>'
52 ;; | Pi ::= '<?' Name ' ' (((Char - S) Char*)? - (Char* '?>' Char*)) '?>'
53 ;; | Atts ::= (' ' Name '=' '"' Datachar* '"')*
54 ;; | Datachar ::= '&amp;' | '&lt;' | '&gt;' | '&quot;'
55 ;; | | '&#9;'| '&#10;'| '&#13;'
56 ;; | | (Char - ('&' | '<' | '>' | '"' | #x9 | #xA | #xD))
57 ;; | Name ::= (see XML spec)
58 ;; | Char ::= (see XML spec)
59 ;; | S ::= (see XML spec)
60 ;; |
61 ;; | Attributes are in lexicographical order (in Unicode bit order).
62 ;; |
63 ;; | A canonical XML document is encoded in UTF-8.
64 ;; |
65 ;; | Ignorable white space is considered significant and is treated
66 ;; | equivalently to data.
68 ;; -- James Clark (jjc@jclark.com)
71 ;;;; SINK: an xml output sink
73 (defclass sink (sax:content-handler)
74 ((ystream :initarg :ystream :accessor sink-ystream)
75 (width :initform 79 :initarg :width :accessor width)
76 (canonical :initform nil :initarg :canonical :accessor canonical)
77 (indentation :initform nil :initarg :indentation :accessor indentation)
78 (current-indentation :initform 0 :accessor current-indentation)
79 (notations :initform (make-buffer :element-type t) :accessor notations)
80 (name-for-dtd :accessor name-for-dtd)
81 (previous-notation :initform nil :accessor previous-notation)
82 (have-doctype :initform nil :accessor have-doctype)
83 (have-internal-subset :initform nil :accessor have-internal-subset)
84 (stack :initform nil :accessor stack)
85 (sink-omit-xml-declaration-p :initform nil
86 :initarg :omit-xml-declaration-p
87 :accessor sink-omit-xml-declaration-p)
88 (encoding :initarg :encoding :reader sink-encoding)))
90 #-rune-is-character
91 (defmethod hax:%want-strings-p ((handler sink))
92 nil)
94 (defmethod initialize-instance :after ((instance sink) &key)
95 (when (eq (canonical instance) t)
96 (setf (canonical instance) 1))
97 (unless (member (canonical instance) '(nil 1 2))
98 (error "Invalid canonical form: ~A" (canonical instance)))
99 (when (and (canonical instance) (indentation instance))
100 (error "Cannot indent XML in canonical mode"))
101 (when (and (canonical instance)
102 (not (eq (ystream-encoding (sink-ystream instance)) :utf-8)))
103 (error "Cannot use non-UTF-8 encoding in canonical mode"))
104 (when (let ((encoding (ystream-encoding (sink-ystream instance))))
105 (and (not (symbolp encoding))
106 (eq (babel-encodings:enc-name encoding) :utf-16)))
107 (sink-write-rune #/U+FEFF instance)))
109 (defun make-buffer (&key (element-type '(unsigned-byte 8)))
110 (make-array 1
111 :element-type element-type
112 :adjustable t
113 :fill-pointer 0))
115 ;; bisschen unschoen hier die ganze api zu duplizieren, aber die
116 ;; ystreams sind noch undokumentiert
117 (macrolet ((define-maker (make-sink make-ystream &rest args)
118 `(defun ,make-sink (,@args &rest initargs
119 &key encoding &allow-other-keys)
120 (let* ((encoding (or encoding "UTF-8"))
121 (ystream (,make-ystream ,@args)))
122 (setf (ystream-encoding ystream)
123 (runes:find-output-encoding encoding))
124 (apply #'make-instance
125 'sink
126 :ystream ystream
127 :encoding encoding
128 initargs)))))
129 (define-maker make-octet-vector-sink make-octet-vector-ystream)
130 (define-maker make-octet-stream-sink make-octet-stream-ystream stream)
131 (define-maker make-rod-sink make-rod-ystream)
133 #+rune-is-character
134 (define-maker make-character-stream-sink make-character-stream-ystream stream)
136 #-rune-is-character
137 (define-maker make-string-sink/utf8 make-string-ystream/utf8)
139 #-rune-is-character
140 (define-maker make-character-stream-sink/utf8
141 make-character-stream-ystream/utf8
142 stream))
144 #+rune-is-character
145 (defun make-string-sink (&rest args)
146 "@return{A serialization sink, i.e. a @class{SAX handler}}
148 Returns a handler that writes processes SAX events by writing an
149 equivalent XML document to a newly allocated string of unicode
150 characters.
152 The sink will return the string as a result from
153 @fun{sax:end-document}.
155 All sink creation functions share the same keyword arguments.
156 Refer to @fun{make-octet-vector-sink} for details on keyword
157 arguments."
158 (apply #'make-rod-sink args))
161 (defmethod sax:end-document ((sink sink))
162 (close-ystream (sink-ystream sink)))
165 (setf (documentation #'make-octet-vector-sink 'function)
166 "@arg[canonical]{canonical form, one of NIL, T, 1, 2. If specified,
167 serialization in canonical form is enabled. The two canonical
168 forms are useful to allow comparisons of XML documents and their
169 content model by character-by-character comparisons of
170 their serialized representation.}
171 @arg[indentation]{indentation level. An integer or nil. If
172 specified, a pretty-printing indentation mode is enabled. Note
173 that indentation as implemented currently changes the content model
174 unconditionally, and is usually helpful only for debugging purposes.}
175 @arg[encoding]{the character encoding to use. A string or
176 keyword. Values are interpreted by Babel. nil is also allowed
177 and means UTF-8.}
178 @arg[omit-xml-declaration]{Boolean. If true, no XML declaration
179 is written.}
180 @return{A serialization sink, i.e. a @class{SAX handler}}
182 Returns a handler that writes processes SAX events by writing an
183 equivalent XML document to a newly allocated vector of
184 @code{(unsigned-byte 8)}.
186 The following values for @code{canonical} are allowed:
188 @begin{itemize}
189 @item{t or 1: Canonical XML}
190 @item{2: Second Canonical Form}
191 @item{NIL: Use a more readable non-canonical representation.}
192 @end{itemize}
194 The sink will return the vector as a result from
195 @fun{sax:end-document}.
197 An internal subset will be included in the result regardless of the
198 canonical setting. It is the responsibility of the caller to not
199 report an internal subset for canonical <= 1, or only notations as
200 required for canonical = 2. For example, the include-doctype argument
201 to dom:map-document should be set to nil for the former behaviour and
202 :canonical-notations for the latter. ")
204 (setf (documentation #'make-octet-stream-sink 'function)
205 "@arg[stream]{An (unsigned-byte 8) stream.}
206 @return{A serialization sink, i.e. a @class{SAX handler}}
208 Returns a handler that writes processes SAX events by writing an
209 equivalent XML document to @var{stream}.
211 The sink will return @var{stream} as a result from
212 @fun{sax:end-document}.
214 All sink creation functions share the same keyword arguments.
215 Refer to @fun{make-octet-vector-sink} for details on keyword
216 arguments.")
218 (setf (documentation #'make-rod-sink 'function)
219 "@return{A serialization sink, i.e. a @class{SAX handler}}
221 Returns a handler that writes processes SAX events by writing an
222 equivalent XML document to a newly allocated string of unicode
223 characters (or on implementations without unicode support: a rod).
225 The sink will return the string (or rod) as a result from
226 @fun{sax:end-document}.
228 All sink creation functions share the same keyword arguments.
229 Refer to @fun{make-octet-vector-sink} for details on keyword
230 arguments.")
232 (setf (documentation #'make-character-stream-sink 'function)
233 "@arg[stream]{A character stream.}
234 @return{A serialization sink, i.e. a @class{SAX handler}}
236 Returns a handler that writes processes SAX events by writing an
237 equivalent XML document to @var{stream}.
239 The sink will return @var{stream} as a result from
240 @fun{sax:end-document}.
242 All sink creation functions share the same keyword arguments.
243 Refer to @fun{make-octet-vector-sink} for details on keyword
244 arguments.")
247 ;;;; doctype and notations
249 (defmethod sax:start-document ((sink sink))
250 (unless (or (canonical sink)
251 (sink-omit-xml-declaration-p sink))
252 (sink-write-rod #"<?xml version=\"1.0\" encoding=\"" sink)
253 (sink-write-rod (rod (sink-encoding sink)) sink)
254 (sink-write-rod #"\"?>" sink)
255 (sink-write-rune #/U+000A sink)))
257 (defmethod sax:start-dtd ((sink sink) name public-id system-id)
258 (setf (name-for-dtd sink) name)
259 (unless (canonical sink)
260 (ensure-doctype sink public-id system-id)))
262 (defun ensure-doctype (sink &optional public-id system-id)
263 (unless (have-doctype sink)
264 (setf (have-doctype sink) t)
265 (sink-write-rod #"<!DOCTYPE " sink)
266 (sink-write-rod (name-for-dtd sink) sink)
267 (cond
268 ((not (zerop (length public-id)))
269 (sink-write-rod #" PUBLIC \"" sink)
270 (sink-write-escapable-rod public-id sink)
271 (sink-write-rod #"\" \"" sink)
272 (sink-write-escapable-rod system-id sink)
273 (sink-write-rod #"\"" sink))
274 ((not (zerop (length system-id)))
275 (sink-write-rod #" SYSTEM \"" sink)
276 (sink-write-escapable-rod system-id sink)
277 (sink-write-rod #"\"" sink)))))
279 (defmethod sax:start-internal-subset ((sink sink))
280 (when (have-internal-subset sink)
281 (error "duplicate internal subset"))
282 (setf (have-internal-subset sink) t)
283 (ensure-doctype sink)
284 (sink-write-rod #" [" sink)
285 (sink-write-rune #/U+000A sink))
287 (defmethod sax:end-internal-subset ((sink sink))
288 (ensure-doctype sink)
289 (sink-write-rod #"]" sink))
291 (defmethod sax:unparsed-internal-subset ((sink sink) str)
292 (when (have-internal-subset sink)
293 (error "duplicate internal subset"))
294 (setf (have-internal-subset sink) t)
295 (ensure-doctype sink)
296 (sink-write-rod #" [" sink)
297 (sink-write-rune #/U+000A sink)
298 (sink-write-rod str sink)
299 (sink-write-rod #"]" sink))
301 ;; for the benefit of the XML test suite, prefer ' over "
302 (defun write-quoted-rod (x sink)
303 (let ((q (if (find #/' x) #/" #/'
304 ;; '" (thanks you Emacs indentation, the if ends here)
306 (sink-write-rune q sink)
307 (sink-write-rod x sink)
308 (sink-write-rune q sink)))
310 (defmethod sax:notation-declaration ((sink sink) name public-id system-id)
311 (let ((prev (previous-notation sink)))
312 (when (and (and (canonical sink) (>= (canonical sink) 2))
313 prev
314 (not (rod< prev name)))
315 (error "misordered notations; cannot unparse canonically"))
316 (setf (previous-notation sink) name))
317 (sink-write-rod #"<!NOTATION " sink)
318 (sink-write-rod name sink)
319 (cond
320 ((zerop (length public-id))
321 (sink-write-rod #" SYSTEM " sink)
322 (write-quoted-rod system-id sink))
323 ((zerop (length system-id))
324 (sink-write-rod #" PUBLIC " sink)
325 (write-quoted-rod public-id sink))
327 (sink-write-rod #" PUBLIC " sink)
328 (write-quoted-rod public-id sink)
329 (sink-write-rod #" " sink)
330 (write-quoted-rod system-id sink)))
331 (sink-write-rune #/> sink)
332 (sink-write-rune #/U+000A sink))
334 (defmethod sax:unparsed-entity-declaration
335 ((sink sink) name public-id system-id notation-name)
336 (unless (and (canonical sink) (< (canonical sink) 3))
337 (sink-write-rod #"<!ENTITY " sink)
338 (sink-write-rod name sink)
339 (cond
340 ((zerop (length public-id))
341 (sink-write-rod #" SYSTEM " sink)
342 (write-quoted-rod system-id sink))
343 ((zerop (length system-id))
344 (sink-write-rod #" PUBLIC " sink)
345 (write-quoted-rod public-id sink))
347 (sink-write-rod #" PUBLIC " sink)
348 (write-quoted-rod public-id sink)
349 (sink-write-rod #" " sink)
350 (write-quoted-rod system-id sink)))
351 (sink-write-rod #" NDATA " sink)
352 (sink-write-rod notation-name sink)
353 (sink-write-rune #/> sink)
354 (sink-write-rune #/U+000A sink)))
356 (defmethod sax:external-entity-declaration
357 ((sink sink) kind name public-id system-id)
358 (when (canonical sink)
359 (error "cannot serialize parsed entities in canonical mode"))
360 (sink-write-rod #"<!ENTITY " sink)
361 (when (eq kind :parameter)
362 (sink-write-rod #" % " sink))
363 (sink-write-rod name sink)
364 (cond
365 ((zerop (length public-id))
366 (sink-write-rod #" SYSTEM " sink)
367 (write-quoted-rod system-id sink))
368 ((zerop (length system-id))
369 (sink-write-rod #" PUBLIC " sink)
370 (write-quoted-rod public-id sink))
372 (sink-write-rod #" PUBLIC " sink)
373 (write-quoted-rod public-id sink)
374 (sink-write-rod #" " sink)
375 (write-quoted-rod system-id sink)))
376 (sink-write-rune #/> sink)
377 (sink-write-rune #/U+000A sink))
379 (defmethod sax:internal-entity-declaration ((sink sink) kind name value)
380 (when (canonical sink)
381 (error "cannot serialize parsed entities in canonical mode"))
382 (sink-write-rod #"<!ENTITY " sink)
383 (when (eq kind :parameter)
384 (sink-write-rod #" % " sink))
385 (sink-write-rod name sink)
386 (sink-write-rune #/U+0020 sink)
387 (sink-write-rune #/\" sink)
388 (sink-write-escapable-rod/dtd value sink)
389 (sink-write-rune #/\" sink)
390 (sink-write-rune #/> sink)
391 (sink-write-rune #/U+000A sink))
393 (defmethod sax:element-declaration ((sink sink) name model)
394 (when (canonical sink)
395 (error "cannot serialize element type declarations in canonical mode"))
396 (sink-write-rod #"<!ELEMENT " sink)
397 (sink-write-rod name sink)
398 (sink-write-rune #/U+0020 sink)
399 (labels ((walk (m)
400 (cond
401 ((eq m :EMPTY)
402 (sink-write-rod "EMPTY" sink))
403 ((eq m :PCDATA)
404 (sink-write-rod "#PCDATA" sink))
405 ((eq m :ANY)
406 (sink-write-rod "ANY" sink))
407 ((atom m)
408 (sink-write-escapable-rod m sink))
410 (ecase (car m)
411 (and
412 (sink-write-rune #/\( sink)
413 (loop for (n . rest) on (cdr m) do
414 (walk n)
415 (when rest
416 (sink-write-rune #\, sink)))
417 (sink-write-rune #/\) sink))
419 (sink-write-rune #/\( sink)
420 (loop for (n . rest) on (cdr m) do
421 (walk n)
422 (when rest
423 (sink-write-rune #\| sink)))
424 (sink-write-rune #/\) sink))
426 (walk (second m))
427 (sink-write-rune #/* sink))
429 (walk (second m))
430 (sink-write-rune #/+ sink))
432 (walk (second m))
433 (sink-write-rune #/? sink)))))))
434 (walk model))
435 (sink-write-rune #/> sink)
436 (sink-write-rune #/U+000A sink))
438 (defmethod sax:attribute-declaration ((sink sink) ename aname type default)
439 (when (canonical sink)
440 (error "cannot serialize attribute type declarations in canonical mode"))
441 (sink-write-rod #"<!ATTLIST " sink)
442 (sink-write-rod ename sink)
443 (sink-write-rune #/U+0020 sink)
444 (sink-write-rod aname sink)
445 (sink-write-rune #/U+0020 sink)
446 (cond
447 ((atom type)
448 (sink-write-rod (rod (string-upcase (symbol-name type))) sink))
450 (when (eq :NOTATION (car type))
451 (sink-write-rod #"NOTATION " sink))
452 (sink-write-rune #/\( sink)
453 (loop for (n . rest) on (cdr type) do
454 (sink-write-rod n sink)
455 (when rest
456 (sink-write-rune #\| sink)))
457 (sink-write-rune #/\) sink)))
458 (sink-write-rune #/U+0020 sink)
459 (cond
460 ((atom default)
461 (sink-write-rune #/# sink)
462 (sink-write-rod (rod (string-upcase (symbol-name default))) sink))
464 (when (eq :FIXED (car default))
465 (sink-write-rod #"#FIXED " sink))
466 (sink-write-rune #/\" sink)
467 (sink-write-escapable-rod (second default) sink)
468 (sink-write-rune #/\" sink)))
469 (sink-write-rune #/> sink)
470 (sink-write-rune #/U+000A sink))
472 (defmethod sax:end-dtd ((sink sink))
473 (when (have-doctype sink)
474 (sink-write-rod #">" sink)
475 (sink-write-rune #/U+000A sink)))
478 ;;;; elements
480 (defstruct (tag (:constructor make-tag (name)))
481 name
482 (n-children 0)
483 (have-gt nil))
485 (defun sink-fresh-line (sink)
486 (unless (zerop (ystream-column (sink-ystream sink)))
487 (sink-write-rune #/U+000A sink) ;newline
488 (indent sink)))
490 (defun maybe-close-tag (sink)
491 (let ((tag (car (stack sink))))
492 (when (and (tag-p tag) (not (tag-have-gt tag)))
493 (setf (tag-have-gt tag) t)
494 (sink-write-rune #/> sink))))
496 (defmethod sax:start-element
497 ((sink sink) namespace-uri local-name qname attributes)
498 (declare (ignore namespace-uri local-name))
499 (maybe-close-tag sink)
500 (when (stack sink)
501 (incf (tag-n-children (first (stack sink)))))
502 (push (make-tag qname) (stack sink))
503 (when (indentation sink)
504 (sink-fresh-line sink)
505 (start-indentation-block sink))
506 (sink-write-rune #/< sink)
507 (sink-write-rod qname sink)
508 (dolist (a (if (canonical sink)
509 (sort (copy-list attributes)
510 #'rod<
511 :key #'sax:attribute-qname)
512 attributes))
513 (sink-write-rune #/space sink)
514 (sink-write-rod (sax:attribute-qname a) sink)
515 (sink-write-rune #/= sink)
516 (sink-write-rune #/\" sink)
517 (if (canonical sink)
518 (sink-write-escapable-rod/canonical (sax:attribute-value a) sink)
519 (sink-write-escapable-rod/attribute (sax:attribute-value a) sink))
520 (sink-write-rune #/\" sink))
521 (when (canonical sink)
522 (maybe-close-tag sink)))
524 (defmethod sax:end-element
525 ((sink sink) namespace-uri local-name qname)
526 (declare (ignore namespace-uri local-name))
527 (let ((tag (pop (stack sink))))
528 (unless (tag-p tag)
529 (error "output does not nest: not in an element"))
530 (unless (rod= (tag-name tag) qname)
531 (error "output does not nest: expected ~A but got ~A"
532 (rod qname) (rod (tag-name tag))))
533 (when (indentation sink)
534 (end-indentation-block sink)
535 (unless (zerop (tag-n-children tag))
536 (sink-fresh-line sink)))
537 (cond
538 ((tag-have-gt tag)
539 (sink-write-rod '#.(string-rod "</") sink)
540 (sink-write-rod qname sink)
541 (sink-write-rod '#.(string-rod ">") sink))
543 (sink-write-rod #"/>" sink)))))
545 (defmethod sax:processing-instruction ((sink sink) target data)
546 (maybe-close-tag sink)
547 (unless (rod-equal target '#.(string-rod "xml"))
548 (sink-write-rod '#.(string-rod "<?") sink)
549 (sink-write-rod target sink)
550 (cond
551 ((plusp (length data))
552 (sink-write-rune #/space sink)
553 (sink-write-rod data sink))
554 ((canonical sink)
555 (sink-write-rune #/space sink)))
556 (sink-write-rod '#.(string-rod "?>") sink)))
558 (defmethod sax:start-cdata ((sink sink))
559 (maybe-close-tag sink)
560 (push :cdata (stack sink)))
562 (defmethod sax:characters ((sink sink) data)
563 (maybe-close-tag sink)
564 (cond
565 ((and (eq (car (stack sink)) :cdata)
566 (not (canonical sink))
567 (not (search #"]]" data)))
568 (when (indentation sink)
569 (sink-fresh-line sink))
570 (sink-write-rod #"<![CDATA[" sink)
571 ;; XXX signal error if body is unprintable?
572 ;; zzz no, in that case, split into multiple CDATA sections
573 (map nil (lambda (c) (sink-write-rune c sink)) data)
574 (sink-write-rod #"]]>" sink))
576 (if (indentation sink)
577 (unparse-indented-text data sink)
578 (if (canonical sink)
579 (sink-write-escapable-rod/canonical data sink)
580 (sink-write-escapable-rod data sink))))))
582 (defmethod sax:unescaped ((sink sink) data)
583 (maybe-close-tag sink)
584 (sink-write-rod data sink))
586 (defmethod sax:comment ((sink sink) data)
587 (maybe-close-tag sink)
588 (unless (canonical sink)
589 ;; XXX signal error if body is unprintable?
590 (sink-write-rod #"<!--" sink)
591 (map nil (lambda (c) (sink-write-rune c sink)) data)
592 (sink-write-rod #"-->" sink)))
594 (defmethod sax:end-cdata ((sink sink))
595 (unless (eq (pop (stack sink)) :cdata)
596 (error "output does not nest: not in a cdata section")))
598 (defun indent (sink)
599 (dotimes (x (current-indentation sink))
600 (sink-write-rune #/U+0020 sink)))
602 (defun start-indentation-block (sink)
603 (incf (current-indentation sink) (indentation sink)))
605 (defun end-indentation-block (sink)
606 (decf (current-indentation sink) (indentation sink)))
608 (defun unparse-indented-text (data sink)
609 (flet ((whitespacep (x)
610 (or (rune= x #/U+000A) (rune= x #/U+0020))))
611 (let* ((n (length data))
612 (pos (position-if-not #'whitespacep data))
613 (need-whitespace-p nil))
614 (cond
615 ((zerop n))
616 (pos
617 (sink-fresh-line sink)
618 (while (< pos n)
619 (let* ((w (or (position-if #'whitespacep data :start (1+ pos)) n))
620 (next (or (position-if-not #'whitespacep data :start w) n)))
621 (when need-whitespace-p
622 (if (< (+ (ystream-column (sink-ystream sink)) w (- pos))
623 (width sink))
624 (sink-write-rune #/U+0020 sink)
625 (sink-fresh-line sink)))
626 (sink-write-escapable-rod data sink :start pos :end w)
627 (setf need-whitespace-p (< w n))
628 (setf pos next))))
630 (sink-write-rune #/U+0020 sink))))))
632 (defun sink-write-escapable-rod (rod sink &key (start 0) (end (length rod)))
634 ;; OPTIMIZE ME
636 (let ((y (sink-ystream sink)))
637 (loop
638 for i from start below end
639 for c = (rune rod i)
641 (case c
642 (#/& (ystream-write-escapable-rod #.(string-rod "&amp;") y))
643 (#/< (ystream-write-escapable-rod #.(string-rod "&lt;") y))
644 ;; there's no need to escape > per se, but we're supposed to
645 ;; escape -->, which is harder to check for
646 (#/> (ystream-write-escapable-rod #.(string-rod "&gt;") y))
647 (#/U+000D (ystream-write-escapable-rod #.(string-rod "&#13;") y))
648 (t (ystream-write-escapable-rune c y))))))
650 (defun sink-write-escapable-rod/attribute
651 (rod sink &key (start 0) (end (length rod)))
653 ;; OPTIMIZE ME
655 (let ((y (sink-ystream sink)))
656 (loop
657 for i from start below end
658 for c = (rune rod i)
660 (case c
661 (#/& (ystream-write-escapable-rod #.(string-rod "&amp;") y))
662 (#/< (ystream-write-escapable-rod #.(string-rod "&lt;") y))
663 ;; there's no need to escape > per se, but we're supposed to
664 ;; escape -->, which is harder to check for
665 (#/> (ystream-write-escapable-rod #.(string-rod "&gt;") y))
666 (#/\" (ystream-write-escapable-rod #.(string-rod "&quot;") y))
667 (#/U+0009 (ystream-write-escapable-rod #.(string-rod "&#9;") y))
668 (#/U+000A (ystream-write-escapable-rod #.(string-rod "&#10;") y))
669 (#/U+000D (ystream-write-escapable-rod #.(string-rod "&#13;") y))
670 (t (ystream-write-escapable-rune c y))))))
672 (defun sink-write-escapable-rod/canonical
673 (rod sink &key (start 0) (end (length rod)))
675 ;; OPTIMIZE ME
677 (let ((y (sink-ystream sink)))
678 (loop
679 for i from start below end
680 for c = (rune rod i)
682 (case c
683 (#/& (ystream-write-escapable-rod #.(string-rod "&amp;") y))
684 (#/< (ystream-write-escapable-rod #.(string-rod "&lt;") y))
685 (#/> (ystream-write-escapable-rod #.(string-rod "&gt;") y))
686 (#/\" (ystream-write-escapable-rod #.(string-rod "&quot;") y))
687 (#/U+0009 (ystream-write-escapable-rod #.(string-rod "&#9;") y))
688 (#/U+000A (ystream-write-escapable-rod #.(string-rod "&#10;") y))
689 (#/U+000D (ystream-write-escapable-rod #.(string-rod "&#13;") y))
690 (t (ystream-write-escapable-rune c y))))))
692 (defun sink-write-escapable-rod/dtd
693 (rod sink &key (start 0) (end (length rod)))
694 (let ((y (sink-ystream sink)))
695 (loop
696 for i from start below end
697 for c = (rune rod i)
699 (case c
700 (#/% (ystream-write-escapable-rod #.(string-rod "&#37;") y))
701 (#/& (ystream-write-escapable-rod #.(string-rod "&amp;") y))
702 (#/< (ystream-write-escapable-rod #.(string-rod "&lt;") y))
703 (#/> (ystream-write-escapable-rod #.(string-rod "&gt;") y))
704 (#/\" (ystream-write-escapable-rod #.(string-rod "&quot;") y))
705 (#/U+0009 (ystream-write-escapable-rod #.(string-rod "&#9;") y))
706 (#/U+000A (ystream-write-escapable-rod #.(string-rod "&#10;") y))
707 (#/U+000D (ystream-write-escapable-rod #.(string-rod "&#13;") y))
708 (t (ystream-write-escapable-rune c y))))))
710 (defun sink-write-rune (c sink)
711 (ystream-write-rune c (sink-ystream sink)))
713 (defun sink-write-rod (r sink)
714 (ystream-write-rod r (sink-ystream sink)))
717 ;;;; convenience functions for DOMless XML serialization
719 (defvar *current-element*)
720 (defvar *sink*)
721 (defvar *unparse-namespace-bindings*)
722 (defvar *current-namespace-bindings*)
724 (defmacro with-xml-output (sink &body body)
725 "@arg[sink]{A @class{SAX handler}, evaluated}
726 @arg[body]{forms}
727 @return{The result of calling @code{sax:end-document} on @code{sink}.}
729 Evaluates sink and establishes it as the current output sink for
730 the following \"convenience serialization\" macros and functions:
731 @fun{with-element}, @fun{with-namespace}, @fun{doctype},
732 @fun{with-element*}, @fun{attribute}, @fun{attribute*}, @fun{text}
733 @fun{comment}, @fun{processing-instruction}, @fun{unescaped}.
735 Before @code{body} is evaluated, @fun{sax:start-document} is signalled
736 to the @code{sink}. Afterwards, @fun{sax:end-document} is signalled.
738 Note that convenience serialization delays some serialization events.
739 For example, @fun{with-element} delays signalling an opening tag
740 using @fun{sax:start-element} until it has information about all
741 possible attributes of the element. Because of this delay, it is
742 not usually safe to signal SAX events to the sink during the extent
743 of @code{with-xml-output}. However, @fun{with-output-sink} can be
744 used to force output of delayed events, allowing direct use of the
745 sink.
747 Example:
748 @pre{(with-xml-output (make-octet-stream-sink stream)
749 (with-element \"foo\"
750 (attribute \"xyz\" \"abc\")
751 (with-element \"bar\"
752 (attribute \"blub\" \"bla\"))
753 (text \"Hi there.\")))}"
754 `(invoke-with-xml-output (lambda () ,@body) ,sink))
756 (defmacro with-output-sink ((var) &body body)
757 "@arg[var]{A symbol, not evaluated.}
758 @arg[body]{forms, an implicit progn}
759 @return{The result of @code{body}.}
761 Allows safe use of manual calls to SAX functions during the extent
762 of @fun{with-xml-output},
764 Determines the current output sink established by @fun{with-xml-output},
765 as used by convenience serialization functions. Writes delayed
766 serialization events to the sink. Binds local variable @code{var} to the
767 sink and evaluates @code{body} as an implicit progn.
769 The consequences are undefined if this macro is used outside of the
770 extent of a call to @fun{with-xml-output}.
772 See @fun{with-xml-output} for details on delayed events."
773 `(invoke-with-output-sink (lambda (,var) ,@body)))
775 (defun invoke-with-xml-output (fn sink)
776 (let ((*sink* sink)
777 (*current-element* nil)
778 (*unparse-namespace-bindings* *initial-namespace-bindings*)
779 (*current-namespace-bindings* nil))
780 (sax:start-document *sink*)
781 (funcall fn)
782 (sax:end-document *sink*)))
784 (defun invoke-with-output-sink (fn)
785 (maybe-emit-start-tag)
786 (funcall fn *sink*))
788 (defmacro with-element (qname &body body)
789 "@arg[qname]{A string, evaluated.}
790 @arg[body]{forms, an implicit progn}
791 @return{The result of @code{body}.}
793 Writes an element to the current output sink.
795 This macro is a convenience wrapper around @fun{with-element*}.
797 @var{qname} is parsed to determine the element's namespace prefix
798 and local name. Then @fun{with-element*} is called on @var{body} using
799 the resulting values."
800 `(invoke-with-element (lambda () ,@body) ,qname))
802 (defmacro with-element* ((prefix lname) &body body)
803 "@arg[prefix]{Namespace prefix, a string (evaluated).}
804 @arg[lname]{Local name, a string (evaluated).}
805 @arg[body]{forms, an implicit progn}
806 @return{The result of @code{body}.}
808 Writes an element to the current output sink.
810 First, @var{prefix} is resolved to a namespace URI using the bindings
811 established by @fun{with-namespace}.
813 Next, body is evaluated as an implicit progn. During this time,
814 attributes for the element can be specified using @fun{attribute}.
816 Once information on the start tag is complete, @fun{start-element}
817 on the current output sink, using the specified namespace prefix and
818 local name specified by the arguments, the namespace URI computed as
819 described above,and including all attributes collected so far.
821 Information on the start tag is considered complete once the first of
822 the following situations occurs:
823 @begin{itemize}
824 @item{Before any child node of the element is written, e.g. using an
825 inner call of @fun{with-element},}
826 @item{Before the body of @fun{with-ouptut-sink} is evaluated.}
827 @item{After the end of @var{body} has been reached.}
828 @end{itemize}
830 Finally, sax:end-element is used to write an end tag, using the same
831 qualified name and namespace information as above."
832 `(invoke-with-element* (lambda () ,@body) ,prefix ,lname))
834 (defmacro with-namespace ((prefix uri) &body body)
835 "@arg[prefix]{Namespace prefix, a string (evaluated).}
836 @arg[uri]{Namespace URI, a string (evaluated).}
837 @arg[body]{forms, an implicit progn}
838 @return{The result of @code{body}.}
840 Registers @code{prefix} as a name for the namespace URI @code{uri}
841 for the extent of body.
843 Namespace bindings established by @code{with-namespace} are used by
844 @fun{with-element} and @fun{with-element*} as well as @fun{attribute}
845 and @fun{attribute*}."
846 `(invoke-with-namespace (lambda () ,@body) ,prefix ,uri))
848 (defun doctype (name public-id system-id &optional internal-subset)
849 "@arg[name]{Element name, a string.}
850 @arg[public-id]{String}
851 @arg[system-id]{A system ID as a @class{puri:uri}.}
852 @arg[internal-subset]{nil or a string}
853 @return{undocumented}
855 Writes a doctype declaration to the current output sink, using the
856 specified name, public ID, system ID, and optionally an internal subset."
857 (sax:start-dtd *sink* name public-id system-id)
858 (when internal-subset
859 (sax:unparsed-internal-subset *sink* internal-subset))
860 (sax:end-dtd *sink*))
862 (defun maybe-emit-start-tag ()
863 (when *current-element*
864 ;; starting child node, need to emit opening tag of parent first:
865 (destructuring-bind ((uri lname qname) &rest attributes) *current-element*
866 (sax:start-element *sink* uri lname qname (reverse attributes)))
867 (setf *current-element* nil)))
869 (defun invoke-with-namespace (fn prefix uri)
870 (let ((*unparse-namespace-bindings*
871 (acons prefix uri *unparse-namespace-bindings*))
872 (*current-namespace-bindings*
873 (acons prefix uri *current-namespace-bindings*)))
874 (sax:start-prefix-mapping *sink* prefix uri)
875 (multiple-value-prog1
876 (funcall fn)
877 (sax:end-prefix-mapping *sink* prefix))))
879 (defun invoke-with-element (fn qname)
880 (setf qname (rod qname))
881 (multiple-value-bind (prefix lname)
882 (split-qname qname)
883 (invoke-with-element* fn prefix lname qname)))
885 (defun find-unparse-namespace (prefix)
886 (cdr (assoc prefix *unparse-namespace-bindings* :test 'equal)))
888 (defun invoke-with-element* (fn prefix lname &optional qname)
889 (setf prefix (when prefix (rod prefix)))
890 (setf lname (rod lname))
891 (maybe-emit-start-tag)
892 (let* ((qname (or qname
893 (if prefix (concatenate 'rod prefix #":" lname) lname)))
894 (uri (find-unparse-namespace (or prefix #"")))
895 (*current-element*
896 (cons (list uri lname qname)
897 (mapcar (lambda (x)
898 (destructuring-bind (prefix &rest uri) x
899 (sax:make-attribute
900 :namespace-uri #"http://www.w3.org/2000/xmlns/"
901 :local-name prefix
902 :qname (if (zerop (length prefix))
903 #"xmlns"
904 (concatenate 'rod #"xmlns:" prefix))
905 :value uri)))
906 *current-namespace-bindings*))))
907 (multiple-value-prog1
908 (let ((*current-namespace-bindings* nil))
909 (funcall fn))
910 (maybe-emit-start-tag)
911 (sax:end-element *sink* uri lname qname))))
913 (defgeneric unparse-attribute (value))
914 (defmethod unparse-attribute ((value string)) value)
915 (defmethod unparse-attribute ((value null)) nil)
916 (defmethod unparse-attribute ((value integer)) (write-to-string value))
918 (defun attribute (qname value)
919 "@arg[qname]{Qualified name, a string.}
920 @arg[value]{Any value understood by @fun{unparse-attribute}, in particular
921 strings.}
922 @return{undocumented}
924 Collects an attribute for the start tag that is currently being written.
926 This function may only be called during the extent of a use of
927 @fun{with-element} or @fun{with-element*}, and only before the first
928 child node has been written.
930 An attribute for the current element is recorded using the namespace prefix
931 and local name specified by @var{qname}. The attribute's namespace prefix
932 is resolved to a namespace URI using the bindings established by
933 @fun{with-namespace},and that namespace URI is used for the attribute."
934 (setf qname (rod qname))
935 (multiple-value-bind (prefix lname)
936 (split-qname qname)
937 (attribute* prefix lname value qname)))
939 (defun attribute* (prefix lname value &optional qname)
940 "@arg[prefix]{Namespace prefix, a string.}
941 @arg[lname]{Local name, a string.}
942 @arg[value]{Any value understood by @fun{unparse-attribute}, in particular
943 strings.}
944 @return{undocumented}
946 Collects an attribute for the start tag that is currently being written.
948 This function may only be called during the extent of a use of
949 @fun{with-element} or @fun{with-element*}, and only before the first
950 child node has been written.
952 An attribute for the current element is recorded using the namespace prefix
953 and local name specified by arguments. @var{prefix} is resolved to a
954 namespace URI using the bindings established by @fun{with-namespace},
955 and that namespace URI is used for the attribute."
956 (setf value (unparse-attribute value))
957 (when value
958 (setf prefix (when prefix (rod prefix)))
959 (setf lname (rod lname))
960 (push (sax:make-attribute
961 :namespace-uri (find-unparse-namespace prefix)
962 :local-name lname
963 :qname (or qname
964 (if prefix (concatenate 'rod prefix #":" lname) lname))
965 :value (rod value))
966 (cdr *current-element*))))
968 (defun cdata (data)
969 "@arg[data]{String.}
970 @return{undocumented}
972 Writes a CDATA section to the current output sink, using @code{data} as
973 its contents.
975 Note: It is currently the caller's responsibily to ensure that the CDATA
976 section will not contain forbidden character sequences."
977 (maybe-emit-start-tag)
978 (sax:start-cdata *sink*)
979 (sax:characters *sink* (rod data))
980 (sax:end-cdata *sink*)
981 data)
983 (defun text (data)
984 "@arg[data]{String.}
985 @return{undocumented}
987 Writes a text node to the current output sink, using @code{data} as
988 its contents.
990 Note: It is currently the caller's responsibily to ensure that @code{data}
991 does not contain characters forbidden for character data."
992 (maybe-emit-start-tag)
993 (sax:characters *sink* (rod data))
994 data)
996 (defun comment (data)
997 "@arg[data]{String.}
998 @return{undocumented}
1000 Writes a comment to the current output sink, using @code{data} as
1001 its contents.
1003 Note: It is currently the caller's responsibily to ensure that @code{data}
1004 does not contain character sequences forbidden for comments."
1005 (maybe-emit-start-tag)
1006 (sax:comment *sink* (rod data))
1007 data)
1009 (defun processing-instruction (target data)
1010 "@arg[target]{String.}
1011 @arg[data]{String.}
1012 @return{undocumented}
1014 Writes a processing instruction to the current output sink, using
1015 @code{target} and @code{data} as its contents.
1017 Note: It is currently the caller's responsibily to ensure that
1018 @code{target} and @code{data} do not contain character sequences
1019 forbidden for processing instruction contents."
1020 (maybe-emit-start-tag)
1021 (sax:processing-instruction *sink* (rod target) (rod data))
1022 data)
1024 (defun unescaped (str)
1025 "@arg[data]{String.}
1026 @return{undocumented}
1028 If supported by the current output sink, writes character data directly
1029 to the sink's target.
1031 Use of this function is often an indicator of bad design. Avoid it
1032 if you can. (Implementation note: This function is supported because
1033 XSLT's XML output method requires it.)"
1034 (maybe-emit-start-tag)
1035 (sax:unescaped *sink* (rod str)))