Mercurial > genshi > mirror
annotate genshi/core.py @ 408:4675d5cf6c67 trunk
Update copyright year for files modified this year.
author | cmlenz |
---|---|
date | Wed, 21 Feb 2007 14:25:44 +0000 |
parents | 228907abb726 |
children | 073640758a42 |
rev | line source |
---|---|
1 | 1 # -*- coding: utf-8 -*- |
2 # | |
408 | 3 # Copyright (C) 2006-2007 Edgewall Software |
1 | 4 # All rights reserved. |
5 # | |
6 # This software is licensed as described in the file COPYING, which | |
7 # you should have received as part of this distribution. The terms | |
230 | 8 # are also available at http://genshi.edgewall.org/wiki/License. |
1 | 9 # |
10 # This software consists of voluntary contributions made by many | |
11 # individuals. For the exact contribution history, see the revision | |
230 | 12 # history and logs, available at http://genshi.edgewall.org/log/. |
1 | 13 |
14 """Core classes for markup processing.""" | |
15 | |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
16 import operator |
397
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
17 |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
18 from genshi.util import plaintext, stripentities, striptags |
1 | 19 |
377
9aa6aa18fa35
Add `Attrs` class to `genshi.core.__all__`, so that it can be imported directly from the `genshi` package.
cmlenz
parents:
345
diff
changeset
|
20 __all__ = ['Stream', 'Markup', 'escape', 'unescape', 'Attrs', 'Namespace', |
9aa6aa18fa35
Add `Attrs` class to `genshi.core.__all__`, so that it can be imported directly from the `genshi` package.
cmlenz
parents:
345
diff
changeset
|
21 'QName'] |
1 | 22 |
23 | |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
24 class StreamEventKind(str): |
397
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
25 """A kind of event on a markup stream.""" |
279
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
26 __slots__ = [] |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
27 _instances = {} |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
28 |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
29 def __new__(cls, val): |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
30 return cls._instances.setdefault(val, str.__new__(cls, val)) |
1 | 31 |
32 | |
33 class Stream(object): | |
34 """Represents a stream of markup events. | |
35 | |
36 This class is basically an iterator over the events. | |
37 | |
397
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
38 Stream events are tuples of the form: |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
39 |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
40 (kind, data, position) |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
41 |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
42 where `kind` is the event kind (such as `START`, `END`, `TEXT`, etc), `data` |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
43 depends on the kind of event, and `position` is a `(filename, line, offset)` |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
44 tuple that contains the location of the original element or text in the |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
45 input. If the original location is unknown, `position` is `(None, -1, -1)`. |
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
46 |
1 | 47 Also provided are ways to serialize the stream to text. The `serialize()` |
48 method will return an iterator over generated strings, while `render()` | |
49 returns the complete generated text at once. Both accept various parameters | |
50 that impact the way the stream is serialized. | |
51 """ | |
52 __slots__ = ['events'] | |
53 | |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
54 START = StreamEventKind('START') # a start tag |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
55 END = StreamEventKind('END') # an end tag |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
56 TEXT = StreamEventKind('TEXT') # literal text |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
57 DOCTYPE = StreamEventKind('DOCTYPE') # doctype declaration |
143
3d4c214c979a
CDATA sections in XML input now appear as CDATA sections in the output. This should address the problem with escaping the contents of `<style>` and `<script>` elements, which would only get interpreted correctly if the output was served as `application/xhtml+xml`. Closes #24.
cmlenz
parents:
141
diff
changeset
|
58 START_NS = StreamEventKind('START_NS') # start namespace mapping |
3d4c214c979a
CDATA sections in XML input now appear as CDATA sections in the output. This should address the problem with escaping the contents of `<style>` and `<script>` elements, which would only get interpreted correctly if the output was served as `application/xhtml+xml`. Closes #24.
cmlenz
parents:
141
diff
changeset
|
59 END_NS = StreamEventKind('END_NS') # end namespace mapping |
3d4c214c979a
CDATA sections in XML input now appear as CDATA sections in the output. This should address the problem with escaping the contents of `<style>` and `<script>` elements, which would only get interpreted correctly if the output was served as `application/xhtml+xml`. Closes #24.
cmlenz
parents:
141
diff
changeset
|
60 START_CDATA = StreamEventKind('START_CDATA') # start CDATA section |
3d4c214c979a
CDATA sections in XML input now appear as CDATA sections in the output. This should address the problem with escaping the contents of `<style>` and `<script>` elements, which would only get interpreted correctly if the output was served as `application/xhtml+xml`. Closes #24.
cmlenz
parents:
141
diff
changeset
|
61 END_CDATA = StreamEventKind('END_CDATA') # end CDATA section |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
62 PI = StreamEventKind('PI') # processing instruction |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
63 COMMENT = StreamEventKind('COMMENT') # comment |
1 | 64 |
65 def __init__(self, events): | |
66 """Initialize the stream with a sequence of markup events. | |
67 | |
27 | 68 @param events: a sequence or iterable providing the events |
1 | 69 """ |
70 self.events = events | |
71 | |
72 def __iter__(self): | |
73 return iter(self.events) | |
74 | |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
75 def __or__(self, function): |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
76 """Override the "bitwise or" operator to apply filters or serializers |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
77 to the stream, providing a syntax similar to pipes on Unix shells. |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
78 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
79 Assume the following stream produced by the `HTML` function: |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
80 |
230 | 81 >>> from genshi.input import HTML |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
82 >>> html = HTML('''<p onclick="alert('Whoa')">Hello, world!</p>''') |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
83 >>> print html |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
84 <p onclick="alert('Whoa')">Hello, world!</p> |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
85 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
86 A filter such as the HTML sanitizer can be applied to that stream using |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
87 the pipe notation as follows: |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
88 |
230 | 89 >>> from genshi.filters import HTMLSanitizer |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
90 >>> sanitizer = HTMLSanitizer() |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
91 >>> print html | sanitizer |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
92 <p>Hello, world!</p> |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
93 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
94 Filters can be any function that accepts and produces a stream (where |
397
31742fe6d47e
* Moved some utility functions from `genshi.core` to `genshi.util` (backwards compatibility preserved via imports)
cmlenz
parents:
382
diff
changeset
|
95 a stream is anything that iterates over events): |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
96 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
97 >>> def uppercase(stream): |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
98 ... for kind, data, pos in stream: |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
99 ... if kind is TEXT: |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
100 ... data = data.upper() |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
101 ... yield kind, data, pos |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
102 >>> print html | sanitizer | uppercase |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
103 <p>HELLO, WORLD!</p> |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
104 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
105 Serializers can also be used with this notation: |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
106 |
230 | 107 >>> from genshi.output import TextSerializer |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
108 >>> output = TextSerializer() |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
109 >>> print html | sanitizer | uppercase | output |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
110 HELLO, WORLD! |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
111 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
112 Commonly, serializers should be used at the end of the "pipeline"; |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
113 using them somewhere in the middle may produce unexpected results. |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
114 """ |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
115 return Stream(_ensure(function(self))) |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
116 |
123
10279d2eeec9
Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents:
116
diff
changeset
|
117 def filter(self, *filters): |
10279d2eeec9
Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents:
116
diff
changeset
|
118 """Apply filters to the stream. |
113
d10fbba1d5e0
Removed the `sanitize()` method from the `Markup` class, and migrate the existing unit tests to `markup.tests.filters`. Provide a `Stream.filter()` method instead which can be used to conveniently apply a filter to a stream.
cmlenz
parents:
111
diff
changeset
|
119 |
123
10279d2eeec9
Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents:
116
diff
changeset
|
120 This method returns a new stream with the given filters applied. The |
10279d2eeec9
Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents:
116
diff
changeset
|
121 filters must be callables that accept the stream object as parameter, |
10279d2eeec9
Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents:
116
diff
changeset
|
122 and return the filtered stream. |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
123 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
124 The call: |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
125 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
126 stream.filter(filter1, filter2) |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
127 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
128 is equivalent to: |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
129 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
130 stream | filter1 | filter2 |
113
d10fbba1d5e0
Removed the `sanitize()` method from the `Markup` class, and migrate the existing unit tests to `markup.tests.filters`. Provide a `Stream.filter()` method instead which can be used to conveniently apply a filter to a stream.
cmlenz
parents:
111
diff
changeset
|
131 """ |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
132 return reduce(operator.or_, (self,) + filters) |
113
d10fbba1d5e0
Removed the `sanitize()` method from the `Markup` class, and migrate the existing unit tests to `markup.tests.filters`. Provide a `Stream.filter()` method instead which can be used to conveniently apply a filter to a stream.
cmlenz
parents:
111
diff
changeset
|
133 |
123
10279d2eeec9
Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents:
116
diff
changeset
|
134 def render(self, method='xml', encoding='utf-8', **kwargs): |
1 | 135 """Return a string representation of the stream. |
136 | |
137 @param method: determines how the stream is serialized; can be either | |
200
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
138 "xml", "xhtml", "html", "text", or a custom serializer |
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
139 class |
1 | 140 @param encoding: how the output string should be encoded; if set to |
141 `None`, this method returns a `unicode` object | |
142 | |
143 Any additional keyword arguments are passed to the serializer, and thus | |
144 depend on the `method` parameter value. | |
145 """ | |
123
10279d2eeec9
Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents:
116
diff
changeset
|
146 generator = self.serialize(method=method, **kwargs) |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
147 output = u''.join(list(generator)) |
1 | 148 if encoding is not None: |
200
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
149 errors = 'replace' |
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
150 if method != 'text': |
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
151 errors = 'xmlcharrefreplace' |
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
152 return output.encode(encoding, errors) |
8
3710e3d0d4a2
`Stream.render()` was masking `TypeError`s (fix based on suggestion by Matt Good).
cmlenz
parents:
6
diff
changeset
|
153 return output |
1 | 154 |
278
d6c58473a9d0
Fix the handling of namespace context for match templates.
cmlenz
parents:
230
diff
changeset
|
155 def select(self, path, namespaces=None, variables=None): |
1 | 156 """Return a new stream that contains the events matching the given |
157 XPath expression. | |
158 | |
159 @param path: a string containing the XPath expression | |
160 """ | |
230 | 161 from genshi.path import Path |
278
d6c58473a9d0
Fix the handling of namespace context for match templates.
cmlenz
parents:
230
diff
changeset
|
162 return Path(path).select(self, namespaces, variables) |
1 | 163 |
123
10279d2eeec9
Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents:
116
diff
changeset
|
164 def serialize(self, method='xml', **kwargs): |
1 | 165 """Generate strings corresponding to a specific serialization of the |
166 stream. | |
167 | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
168 Unlike the `render()` method, this method is a generator that returns |
1 | 169 the serialized output incrementally, as opposed to returning a single |
170 string. | |
171 | |
172 @param method: determines how the stream is serialized; can be either | |
200
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
173 "xml", "xhtml", "html", "text", or a custom serializer |
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
174 class |
147
a4a0ca41b6ad
Use `xmlcharrefreplace` when encoding the output in `Stream.render()`, so that encoding the output to legacy encodings such as ASCII or ISO-8859-1 should always work.
cmlenz
parents:
145
diff
changeset
|
175 |
a4a0ca41b6ad
Use `xmlcharrefreplace` when encoding the output in `Stream.render()`, so that encoding the output to legacy encodings such as ASCII or ISO-8859-1 should always work.
cmlenz
parents:
145
diff
changeset
|
176 Any additional keyword arguments are passed to the serializer, and thus |
a4a0ca41b6ad
Use `xmlcharrefreplace` when encoding the output in `Stream.render()`, so that encoding the output to legacy encodings such as ASCII or ISO-8859-1 should always work.
cmlenz
parents:
145
diff
changeset
|
177 depend on the `method` parameter value. |
1 | 178 """ |
230 | 179 from genshi import output |
1 | 180 cls = method |
181 if isinstance(method, basestring): | |
96
fa08aef181a2
Add an XHTML serialization method. Now really need to get rid of some code duplication in the `markup.output` module.
cmlenz
parents:
91
diff
changeset
|
182 cls = {'xml': output.XMLSerializer, |
fa08aef181a2
Add an XHTML serialization method. Now really need to get rid of some code duplication in the `markup.output` module.
cmlenz
parents:
91
diff
changeset
|
183 'xhtml': output.XHTMLSerializer, |
200
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
184 'html': output.HTMLSerializer, |
5861f4446c26
Add serialization to plain text, based on cboos' patch. Closes #41.
cmlenz
parents:
182
diff
changeset
|
185 'text': output.TextSerializer}[method] |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
186 return cls(**kwargs)(_ensure(self)) |
1 | 187 |
188 def __str__(self): | |
189 return self.render() | |
190 | |
191 def __unicode__(self): | |
192 return self.render(encoding=None) | |
193 | |
194 | |
69 | 195 START = Stream.START |
196 END = Stream.END | |
197 TEXT = Stream.TEXT | |
198 DOCTYPE = Stream.DOCTYPE | |
199 START_NS = Stream.START_NS | |
200 END_NS = Stream.END_NS | |
143
3d4c214c979a
CDATA sections in XML input now appear as CDATA sections in the output. This should address the problem with escaping the contents of `<style>` and `<script>` elements, which would only get interpreted correctly if the output was served as `application/xhtml+xml`. Closes #24.
cmlenz
parents:
141
diff
changeset
|
201 START_CDATA = Stream.START_CDATA |
3d4c214c979a
CDATA sections in XML input now appear as CDATA sections in the output. This should address the problem with escaping the contents of `<style>` and `<script>` elements, which would only get interpreted correctly if the output was served as `application/xhtml+xml`. Closes #24.
cmlenz
parents:
141
diff
changeset
|
202 END_CDATA = Stream.END_CDATA |
69 | 203 PI = Stream.PI |
204 COMMENT = Stream.COMMENT | |
205 | |
111
2368c3becc52
Some fixes and more unit tests for the XPath engine.
cmlenz
parents:
100
diff
changeset
|
206 def _ensure(stream): |
2368c3becc52
Some fixes and more unit tests for the XPath engine.
cmlenz
parents:
100
diff
changeset
|
207 """Ensure that every item on the stream is actually a markup event.""" |
2368c3becc52
Some fixes and more unit tests for the XPath engine.
cmlenz
parents:
100
diff
changeset
|
208 for event in stream: |
145
47bbd9d2a5af
* Fix error in expression evaluation when the expression evaluates to an iterable that does not produce event tuples.
cmlenz
parents:
143
diff
changeset
|
209 if type(event) is not tuple: |
47bbd9d2a5af
* Fix error in expression evaluation when the expression evaluates to an iterable that does not produce event tuples.
cmlenz
parents:
143
diff
changeset
|
210 if hasattr(event, 'totuple'): |
47bbd9d2a5af
* Fix error in expression evaluation when the expression evaluates to an iterable that does not produce event tuples.
cmlenz
parents:
143
diff
changeset
|
211 event = event.totuple() |
47bbd9d2a5af
* Fix error in expression evaluation when the expression evaluates to an iterable that does not produce event tuples.
cmlenz
parents:
143
diff
changeset
|
212 else: |
47bbd9d2a5af
* Fix error in expression evaluation when the expression evaluates to an iterable that does not produce event tuples.
cmlenz
parents:
143
diff
changeset
|
213 event = TEXT, unicode(event), (None, -1, -1) |
47bbd9d2a5af
* Fix error in expression evaluation when the expression evaluates to an iterable that does not produce event tuples.
cmlenz
parents:
143
diff
changeset
|
214 yield event |
111
2368c3becc52
Some fixes and more unit tests for the XPath engine.
cmlenz
parents:
100
diff
changeset
|
215 |
69 | 216 |
345 | 217 class Attrs(tuple): |
218 """Immutable sequence type that stores the attributes of an element. | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
219 |
345 | 220 Ordering of the attributes is preserved, while accessing by name is also |
221 supported. | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
222 |
182
2f30ce3fb85e
Renamed `Attributes` to `Attrs` to reduce the verbosity.
cmlenz
parents:
172
diff
changeset
|
223 >>> attrs = Attrs([('href', '#'), ('title', 'Foo')]) |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
224 >>> attrs |
403
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
225 Attrs([('href', '#'), ('title', 'Foo')]) |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
226 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
227 >>> 'href' in attrs |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
228 True |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
229 >>> 'tabindex' in attrs |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
230 False |
403
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
231 >>> attrs.get('title') |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
232 'Foo' |
345 | 233 |
234 Instances may not be manipulated directly. Instead, the operators `|` and | |
235 `-` can be used to produce new instances that have specific attributes | |
236 added, replaced or removed. | |
237 | |
238 To remove an attribute, use the `-` operator. The right hand side can be | |
239 either a string or a set/sequence of strings, identifying the name(s) of | |
240 the attribute(s) to remove: | |
241 | |
242 >>> attrs - 'title' | |
403
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
243 Attrs([('href', '#')]) |
345 | 244 >>> attrs - ('title', 'href') |
245 Attrs() | |
246 | |
247 The original instance is not modified, but the operator can of course be | |
248 used with an assignment: | |
249 | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
250 >>> attrs |
403
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
251 Attrs([('href', '#'), ('title', 'Foo')]) |
345 | 252 >>> attrs -= 'title' |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
253 >>> attrs |
403
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
254 Attrs([('href', '#')]) |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
255 |
345 | 256 To add a new attribute, use the `|` operator, where the right hand value |
257 is a sequence of `(name, value)` tuples (which includes `Attrs` instances): | |
170
6b265e02d099
Allow initialization of `Attributes` with keyword arguments.
cmlenz
parents:
161
diff
changeset
|
258 |
403
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
259 >>> attrs | [('title', 'Bar')] |
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
260 Attrs([('href', '#'), ('title', 'Bar')]) |
171
7fcf8e04514e
Follow-up to [214]: allow initializing `Attributes` with attribute names that contain dashes or conflict with a reserved word (such as ?class?.)
cmlenz
parents:
170
diff
changeset
|
261 |
345 | 262 If the attributes already contain an attribute with a given name, the value |
263 of that attribute is replaced: | |
171
7fcf8e04514e
Follow-up to [214]: allow initializing `Attributes` with attribute names that contain dashes or conflict with a reserved word (such as ?class?.)
cmlenz
parents:
170
diff
changeset
|
264 |
403
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
265 >>> attrs | [('href', 'http://example.org/')] |
228907abb726
Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents:
397
diff
changeset
|
266 Attrs([('href', 'http://example.org/')]) |
171
7fcf8e04514e
Follow-up to [214]: allow initializing `Attributes` with attribute names that contain dashes or conflict with a reserved word (such as ?class?.)
cmlenz
parents:
170
diff
changeset
|
267 |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
268 """ |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
269 __slots__ = [] |
1 | 270 |
271 def __contains__(self, name): | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
272 """Return whether the list includes an attribute with the specified |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
273 name. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
274 """ |
133
79f445396cd7
Minor cleanup and performance improvement for the builder module.
cmlenz
parents:
123
diff
changeset
|
275 for attr, _ in self: |
79f445396cd7
Minor cleanup and performance improvement for the builder module.
cmlenz
parents:
123
diff
changeset
|
276 if attr == name: |
79f445396cd7
Minor cleanup and performance improvement for the builder module.
cmlenz
parents:
123
diff
changeset
|
277 return True |
1 | 278 |
345 | 279 def __getslice__(self, i, j): |
280 return Attrs(tuple.__getslice__(self, i, j)) | |
281 | |
282 def __or__(self, attrs): | |
283 """Return a new instance that contains the attributes in `attrs` in | |
284 addition to any already existing attributes. | |
285 """ | |
286 repl = dict([(an, av) for an, av in attrs if an in self]) | |
287 return Attrs([(sn, repl.get(sn, sv)) for sn, sv in self] + | |
288 [(an, av) for an, av in attrs if an not in self]) | |
289 | |
326
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
290 def __repr__(self): |
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
291 if not self: |
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
292 return 'Attrs()' |
345 | 293 return 'Attrs([%s])' % ', '.join([repr(item) for item in self]) |
294 | |
295 def __sub__(self, names): | |
296 """Return a new instance with all attributes with a name in `names` are | |
297 removed. | |
298 """ | |
299 if isinstance(names, basestring): | |
300 names = (names,) | |
301 return Attrs([(name, val) for name, val in self if name not in names]) | |
326
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
302 |
1 | 303 def get(self, name, default=None): |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
304 """Return the value of the attribute with the specified name, or the |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
305 value of the `default` parameter if no such attribute is found. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
306 """ |
1 | 307 for attr, value in self: |
308 if attr == name: | |
309 return value | |
310 return default | |
311 | |
77
f5ec6d4a61e4
* Simplify implementation of the individual XPath tests (use closures instead of callable classes)
cmlenz
parents:
73
diff
changeset
|
312 def totuple(self): |
161
7b1f07496bf7
Various docstring additions and other cosmetic changes.
cmlenz
parents:
147
diff
changeset
|
313 """Return the attributes as a markup event. |
7b1f07496bf7
Various docstring additions and other cosmetic changes.
cmlenz
parents:
147
diff
changeset
|
314 |
7b1f07496bf7
Various docstring additions and other cosmetic changes.
cmlenz
parents:
147
diff
changeset
|
315 The returned event is a TEXT event, the data is the value of all |
7b1f07496bf7
Various docstring additions and other cosmetic changes.
cmlenz
parents:
147
diff
changeset
|
316 attributes joined together. |
7b1f07496bf7
Various docstring additions and other cosmetic changes.
cmlenz
parents:
147
diff
changeset
|
317 """ |
77
f5ec6d4a61e4
* Simplify implementation of the individual XPath tests (use closures instead of callable classes)
cmlenz
parents:
73
diff
changeset
|
318 return TEXT, u''.join([x[1] for x in self]), (None, -1, -1) |
f5ec6d4a61e4
* Simplify implementation of the individual XPath tests (use closures instead of callable classes)
cmlenz
parents:
73
diff
changeset
|
319 |
1 | 320 |
321 class Markup(unicode): | |
322 """Marks a string as being safe for inclusion in HTML/XML output without | |
323 needing to be escaped. | |
324 """ | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
325 __slots__ = [] |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
326 |
27 | 327 def __new__(cls, text='', *args): |
1 | 328 if args: |
136 | 329 text %= tuple(map(escape, args)) |
27 | 330 return unicode.__new__(cls, text) |
1 | 331 |
332 def __add__(self, other): | |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
333 return Markup(unicode(self) + unicode(escape(other))) |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
334 |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
335 def __radd__(self, other): |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
336 return Markup(unicode(escape(other)) + unicode(self)) |
1 | 337 |
338 def __mod__(self, args): | |
339 if not isinstance(args, (list, tuple)): | |
340 args = [args] | |
136 | 341 return Markup(unicode.__mod__(self, tuple(map(escape, args)))) |
1 | 342 |
343 def __mul__(self, num): | |
344 return Markup(unicode(self) * num) | |
345 | |
204
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
346 def __rmul__(self, num): |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
347 return Markup(num * unicode(self)) |
51d4101f49ca
* Implement reverse add/mul operators for `Markup` class, so that the result is also a `Markup` instance.
cmlenz
parents:
200
diff
changeset
|
348 |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
349 def __repr__(self): |
382
2682dabbcd04
* Added documentation for the various stream event kinds.
cmlenz
parents:
377
diff
changeset
|
350 return '<%s %r>' % (self.__class__.__name__, unicode(self)) |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
10
diff
changeset
|
351 |
54 | 352 def join(self, seq, escape_quotes=True): |
353 return Markup(unicode(self).join([escape(item, quotes=escape_quotes) | |
34 | 354 for item in seq])) |
1 | 355 |
356 def escape(cls, text, quotes=True): | |
357 """Create a Markup instance from a string and escape special characters | |
358 it may contain (<, >, & and \"). | |
359 | |
360 If the `quotes` parameter is set to `False`, the \" character is left | |
361 as is. Escaping quotes is generally only required for strings that are | |
362 to be used in attribute values. | |
363 """ | |
73 | 364 if not text: |
365 return cls() | |
366 if type(text) is cls: | |
1 | 367 return text |
73 | 368 text = unicode(text).replace('&', '&') \ |
369 .replace('<', '<') \ | |
370 .replace('>', '>') | |
1 | 371 if quotes: |
372 text = text.replace('"', '"') | |
373 return cls(text) | |
374 escape = classmethod(escape) | |
375 | |
376 def unescape(self): | |
377 """Reverse-escapes &, <, > and \" and returns a `unicode` object.""" | |
378 if not self: | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
379 return u'' |
1 | 380 return unicode(self).replace('"', '"') \ |
381 .replace('>', '>') \ | |
382 .replace('<', '<') \ | |
383 .replace('&', '&') | |
384 | |
116 | 385 def stripentities(self, keepxmlentities=False): |
386 """Return a copy of the text with any character or numeric entities | |
387 replaced by the equivalent UTF-8 characters. | |
388 | |
389 If the `keepxmlentities` parameter is provided and evaluates to `True`, | |
390 the core XML entities (&, ', >, < and ") are not | |
391 stripped. | |
6 | 392 """ |
116 | 393 return Markup(stripentities(self, keepxmlentities=keepxmlentities)) |
394 | |
395 def striptags(self): | |
396 """Return a copy of the text with all XML/HTML tags removed.""" | |
397 return Markup(striptags(self)) | |
1 | 398 |
399 | |
400 escape = Markup.escape | |
401 | |
402 def unescape(text): | |
403 """Reverse-escapes &, <, > and \" and returns a `unicode` object.""" | |
404 if not isinstance(text, Markup): | |
405 return text | |
406 return text.unescape() | |
407 | |
408 | |
409 class Namespace(object): | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
410 """Utility class creating and testing elements with a namespace. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
411 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
412 Internally, namespace URIs are encoded in the `QName` of any element or |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
413 attribute, the namespace URI being enclosed in curly braces. This class |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
414 helps create and test these strings. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
415 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
416 A `Namespace` object is instantiated with the namespace URI. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
417 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
418 >>> html = Namespace('http://www.w3.org/1999/xhtml') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
419 >>> html |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
420 <Namespace "http://www.w3.org/1999/xhtml"> |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
421 >>> html.uri |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
422 u'http://www.w3.org/1999/xhtml' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
423 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
424 The `Namespace` object can than be used to generate `QName` objects with |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
425 that namespace: |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
426 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
427 >>> html.body |
326
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
428 QName(u'http://www.w3.org/1999/xhtml}body') |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
429 >>> html.body.localname |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
430 u'body' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
431 >>> html.body.namespace |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
432 u'http://www.w3.org/1999/xhtml' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
433 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
434 The same works using item access notation, which is useful for element or |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
435 attribute names that are not valid Python identifiers: |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
436 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
437 >>> html['body'] |
326
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
438 QName(u'http://www.w3.org/1999/xhtml}body') |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
439 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
440 A `Namespace` object can also be used to test whether a specific `QName` |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
441 belongs to that namespace using the `in` operator: |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
442 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
443 >>> qname = html.body |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
444 >>> qname in html |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
445 True |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
446 >>> qname in Namespace('http://www.w3.org/2002/06/xhtml2') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
447 False |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
448 """ |
224
90d62225f411
Implement support for namespace prefixes in XPath expressions.
cmlenz
parents:
204
diff
changeset
|
449 def __new__(cls, uri): |
90d62225f411
Implement support for namespace prefixes in XPath expressions.
cmlenz
parents:
204
diff
changeset
|
450 if type(uri) is cls: |
90d62225f411
Implement support for namespace prefixes in XPath expressions.
cmlenz
parents:
204
diff
changeset
|
451 return uri |
90d62225f411
Implement support for namespace prefixes in XPath expressions.
cmlenz
parents:
204
diff
changeset
|
452 return object.__new__(cls, uri) |
90d62225f411
Implement support for namespace prefixes in XPath expressions.
cmlenz
parents:
204
diff
changeset
|
453 |
279
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
454 def __getnewargs__(self): |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
455 return (self.uri,) |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
456 |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
457 def __getstate__(self): |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
458 return self.uri |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
459 |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
460 def __setstate__(self, uri): |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
461 self.uri = uri |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
462 |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
463 def __init__(self, uri): |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
464 self.uri = unicode(uri) |
1 | 465 |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
466 def __contains__(self, qname): |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
467 return qname.namespace == self.uri |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
468 |
278
d6c58473a9d0
Fix the handling of namespace context for match templates.
cmlenz
parents:
230
diff
changeset
|
469 def __ne__(self, other): |
d6c58473a9d0
Fix the handling of namespace context for match templates.
cmlenz
parents:
230
diff
changeset
|
470 return not self == other |
d6c58473a9d0
Fix the handling of namespace context for match templates.
cmlenz
parents:
230
diff
changeset
|
471 |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
472 def __eq__(self, other): |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
473 if isinstance(other, Namespace): |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
474 return self.uri == other.uri |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
475 return self.uri == other |
1 | 476 |
477 def __getitem__(self, name): | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
478 return QName(self.uri + u'}' + name) |
1 | 479 __getattr__ = __getitem__ |
480 | |
481 def __repr__(self): | |
482 return '<Namespace "%s">' % self.uri | |
483 | |
484 def __str__(self): | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
485 return self.uri.encode('utf-8') |
1 | 486 |
487 def __unicode__(self): | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
488 return self.uri |
1 | 489 |
490 | |
147
a4a0ca41b6ad
Use `xmlcharrefreplace` when encoding the output in `Stream.render()`, so that encoding the output to legacy encodings such as ASCII or ISO-8859-1 should always work.
cmlenz
parents:
145
diff
changeset
|
491 # The namespace used by attributes such as xml:lang and xml:space |
141
520a5b7dd6d2
* No escaping of `<script>` or `<style>` tags in HTML output (see #24)
cmlenz
parents:
140
diff
changeset
|
492 XML_NAMESPACE = Namespace('http://www.w3.org/XML/1998/namespace') |
520a5b7dd6d2
* No escaping of `<script>` or `<style>` tags in HTML output (see #24)
cmlenz
parents:
140
diff
changeset
|
493 |
520a5b7dd6d2
* No escaping of `<script>` or `<style>` tags in HTML output (see #24)
cmlenz
parents:
140
diff
changeset
|
494 |
1 | 495 class QName(unicode): |
496 """A qualified element or attribute name. | |
497 | |
498 The unicode value of instances of this class contains the qualified name of | |
499 the element or attribute, in the form `{namespace}localname`. The namespace | |
500 URI can be obtained through the additional `namespace` attribute, while the | |
501 local name can be accessed through the `localname` attribute. | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
502 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
503 >>> qname = QName('foo') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
504 >>> qname |
326
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
505 QName(u'foo') |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
506 >>> qname.localname |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
507 u'foo' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
508 >>> qname.namespace |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
509 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
510 >>> qname = QName('http://www.w3.org/1999/xhtml}body') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
511 >>> qname |
326
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
512 QName(u'http://www.w3.org/1999/xhtml}body') |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
513 >>> qname.localname |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
514 u'body' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
515 >>> qname.namespace |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
516 u'http://www.w3.org/1999/xhtml' |
1 | 517 """ |
518 __slots__ = ['namespace', 'localname'] | |
519 | |
520 def __new__(cls, qname): | |
100 | 521 if type(qname) is cls: |
1 | 522 return qname |
523 | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
524 parts = qname.split(u'}', 1) |
100 | 525 if len(parts) > 1: |
136 | 526 self = unicode.__new__(cls, u'{%s' % qname) |
527 self.namespace, self.localname = map(unicode, parts) | |
1 | 528 else: |
529 self = unicode.__new__(cls, qname) | |
136 | 530 self.namespace, self.localname = None, unicode(qname) |
1 | 531 return self |
279
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
532 |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
533 def __getnewargs__(self): |
a99666402b12
Some adjustments to make core data structures picklable (requires protocol 2).
cmlenz
parents:
278
diff
changeset
|
534 return (self.lstrip('{'),) |
326
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
535 |
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
536 def __repr__(self): |
f999da894391
Fixed `__repr__` of the `QName`, `Attrs`, and `Expression` classes so that the output can be used as code to instantiate the object again.
cmlenz
parents:
279
diff
changeset
|
537 return 'QName(%s)' % unicode.__repr__(self.lstrip('{')) |