Mercurial > genshi > mirror
annotate markup/core.py @ 85:4938c310d904 trunk
Improve handling of DOCTYPE declarations.
author | cmlenz |
---|---|
date | Sun, 16 Jul 2006 11:07:34 +0000 |
parents | f5ec6d4a61e4 |
children | a71a58df6bf5 |
rev | line source |
---|---|
1 | 1 # -*- coding: utf-8 -*- |
2 # | |
66
59eb24184e9c
Switch copyright to Edgewall and URLs to markup.edgewall.org.
cmlenz
parents:
54
diff
changeset
|
3 # Copyright (C) 2006 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 | |
66
59eb24184e9c
Switch copyright to Edgewall and URLs to markup.edgewall.org.
cmlenz
parents:
54
diff
changeset
|
8 # are also available at http://markup.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 | |
66
59eb24184e9c
Switch copyright to Edgewall and URLs to markup.edgewall.org.
cmlenz
parents:
54
diff
changeset
|
12 # history and logs, available at http://markup.edgewall.org/log/. |
1 | 13 |
14 """Core classes for markup processing.""" | |
15 | |
16 import htmlentitydefs | |
17 import re | |
18 from StringIO import StringIO | |
19 | |
20 __all__ = ['Stream', 'Markup', 'escape', 'unescape', 'Namespace', 'QName'] | |
21 | |
22 | |
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
|
23 class StreamEventKind(str): |
1 | 24 """A kind of event on an XML stream.""" |
25 | |
26 | |
27 class Stream(object): | |
28 """Represents a stream of markup events. | |
29 | |
30 This class is basically an iterator over the events. | |
31 | |
32 Also provided are ways to serialize the stream to text. The `serialize()` | |
33 method will return an iterator over generated strings, while `render()` | |
34 returns the complete generated text at once. Both accept various parameters | |
35 that impact the way the stream is serialized. | |
36 | |
37 Stream events are tuples of the form: | |
38 | |
39 (kind, data, position) | |
40 | |
41 where `kind` is the event kind (such as `START`, `END`, `TEXT`, etc), `data` | |
42 depends on the kind of event, and `position` is a `(line, offset)` tuple | |
43 that contains the location of the original element or text in the input. | |
44 """ | |
45 __slots__ = ['events'] | |
46 | |
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
|
47 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
|
48 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
|
49 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
|
50 PROLOG = StreamEventKind('PROLOG') # XML prolog |
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
|
51 DOCTYPE = StreamEventKind('DOCTYPE') # doctype declaration |
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
|
52 START_NS = StreamEventKind('START-NS') # start namespace mapping |
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
|
53 END_NS = StreamEventKind('END-NS') # end namespace mapping |
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 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
|
55 COMMENT = StreamEventKind('COMMENT') # comment |
1 | 56 |
57 def __init__(self, events): | |
58 """Initialize the stream with a sequence of markup events. | |
59 | |
27 | 60 @param events: a sequence or iterable providing the events |
1 | 61 """ |
62 self.events = events | |
63 | |
64 def __iter__(self): | |
65 return iter(self.events) | |
66 | |
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
|
67 def render(self, method='xml', encoding='utf-8', filters=None, **kwargs): |
1 | 68 """Return a string representation of the stream. |
69 | |
70 @param method: determines how the stream is serialized; can be either | |
71 'xml' or 'html', or a custom `Serializer` subclass | |
72 @param encoding: how the output string should be encoded; if set to | |
73 `None`, this method returns a `unicode` object | |
74 | |
75 Any additional keyword arguments are passed to the serializer, and thus | |
76 depend on the `method` parameter value. | |
77 """ | |
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
|
78 generator = self.serialize(method=method, filters=filters, **kwargs) |
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
|
79 output = u''.join(list(generator)) |
1 | 80 if encoding is not None: |
9
5dc4bfe67c20
Actually use the specified encoding in `Stream.render()`.
cmlenz
parents:
8
diff
changeset
|
81 return output.encode(encoding) |
8
3710e3d0d4a2
`Stream.render()` was masking `TypeError`s (fix based on suggestion by Matt Good).
cmlenz
parents:
6
diff
changeset
|
82 return output |
1 | 83 |
84 def select(self, path): | |
85 """Return a new stream that contains the events matching the given | |
86 XPath expression. | |
87 | |
88 @param path: a string containing the XPath expression | |
89 """ | |
90 from markup.path import Path | |
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
|
91 return Path(path).select(self) |
1 | 92 |
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
|
93 def serialize(self, method='xml', filters=None, **kwargs): |
1 | 94 """Generate strings corresponding to a specific serialization of the |
95 stream. | |
96 | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
97 Unlike the `render()` method, this method is a generator that returns |
1 | 98 the serialized output incrementally, as opposed to returning a single |
99 string. | |
100 | |
101 @param method: determines how the stream is serialized; can be either | |
102 'xml' or 'html', or a custom `Serializer` subclass | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
103 @param filters: list of filters to apply to the stream before |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
104 serialization. The default is to apply whitespace |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
105 reduction using `markup.filters.WhitespaceFilter`. |
1 | 106 """ |
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
|
107 from markup.filters import WhitespaceFilter |
1 | 108 from markup import output |
109 cls = method | |
110 if isinstance(method, basestring): | |
111 cls = {'xml': output.XMLSerializer, | |
112 'html': output.HTMLSerializer}[method] | |
113 else: | |
27 | 114 assert issubclass(cls, output.Serializer) |
1 | 115 serializer = cls(**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
|
116 |
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
|
117 stream = self |
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
|
118 if filters is None: |
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
|
119 filters = [WhitespaceFilter()] |
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
|
120 for filter_ in filters: |
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
|
121 stream = filter_(iter(stream)) |
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
|
122 |
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
|
123 return serializer.serialize(stream) |
1 | 124 |
125 def __str__(self): | |
126 return self.render() | |
127 | |
128 def __unicode__(self): | |
129 return self.render(encoding=None) | |
130 | |
131 | |
69 | 132 START = Stream.START |
133 END = Stream.END | |
134 TEXT = Stream.TEXT | |
135 PROLOG = Stream.PROLOG | |
136 DOCTYPE = Stream.DOCTYPE | |
137 START_NS = Stream.START_NS | |
138 END_NS = Stream.END_NS | |
139 PI = Stream.PI | |
140 COMMENT = Stream.COMMENT | |
141 | |
142 | |
1 | 143 class Attributes(list): |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
144 """Sequence type that stores the attributes of an element. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
145 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
146 The order of the attributes is preserved, while accessing and manipulating |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
147 attributes by name is also supported. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
148 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
149 >>> attrs = Attributes([('href', '#'), ('title', 'Foo')]) |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
150 >>> attrs |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
151 [(u'href', '#'), (u'title', 'Foo')] |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
152 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
153 >>> 'href' in attrs |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
154 True |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
155 >>> 'tabindex' in attrs |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
156 False |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
157 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
158 >>> attrs.get(u'title') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
159 'Foo' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
160 >>> attrs.set(u'title', 'Bar') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
161 >>> attrs |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
162 [(u'href', '#'), (u'title', 'Bar')] |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
163 >>> attrs.remove(u'title') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
164 >>> attrs |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
165 [(u'href', '#')] |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
166 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
167 New attributes added using the `set()` method are appended to the end of |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
168 the list: |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
169 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
170 >>> attrs.set(u'accesskey', 'k') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
171 >>> attrs |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
172 [(u'href', '#'), (u'accesskey', 'k')] |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
173 """ |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
174 __slots__ = [] |
1 | 175 |
176 def __init__(self, attrib=None): | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
177 """Create the `Attributes` instance. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
178 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
179 If the `attrib` parameter is provided, it is expected to be a sequence |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
180 of `(name, value)` tuples. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
181 """ |
27 | 182 if attrib is None: |
183 attrib = [] | |
184 list.__init__(self, [(QName(name), value) for name, value in attrib]) | |
1 | 185 |
186 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
|
187 """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
|
188 name. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
189 """ |
27 | 190 return name in [attr for attr, _ in self] |
1 | 191 |
192 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
|
193 """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
|
194 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
|
195 """ |
1 | 196 for attr, value in self: |
197 if attr == name: | |
198 return value | |
199 return default | |
200 | |
5
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
201 def remove(self, name): |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
202 """Removes the attribute with the specified name. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
203 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
204 If no such attribute is found, this method does nothing. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
205 """ |
5
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
206 for idx, (attr, _) in enumerate(self): |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
207 if attr == name: |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
208 del self[idx] |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
209 break |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
210 |
1 | 211 def set(self, name, value): |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
212 """Sets the specified attribute to the given value. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
213 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
214 If an attribute with the specified name is already in the list, the |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
215 value of the existing entry is updated. Otherwise, a new attribute is |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
216 appended to the end of the list. |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
217 """ |
1 | 218 for idx, (attr, _) in enumerate(self): |
219 if attr == name: | |
220 self[idx] = (attr, value) | |
221 break | |
222 else: | |
223 self.append((QName(name), value)) | |
224 | |
77
f5ec6d4a61e4
* Simplify implementation of the individual XPath tests (use closures instead of callable classes)
cmlenz
parents:
73
diff
changeset
|
225 def totuple(self): |
f5ec6d4a61e4
* Simplify implementation of the individual XPath tests (use closures instead of callable classes)
cmlenz
parents:
73
diff
changeset
|
226 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
|
227 |
1 | 228 |
229 class Markup(unicode): | |
230 """Marks a string as being safe for inclusion in HTML/XML output without | |
231 needing to be escaped. | |
232 """ | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
233 __slots__ = [] |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
234 |
27 | 235 def __new__(cls, text='', *args): |
1 | 236 if args: |
237 text %= tuple([escape(arg) for arg in args]) | |
27 | 238 return unicode.__new__(cls, text) |
1 | 239 |
240 def __add__(self, other): | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
241 return Markup(unicode(self) + escape(other)) |
1 | 242 |
243 def __mod__(self, args): | |
244 if not isinstance(args, (list, tuple)): | |
245 args = [args] | |
246 return Markup(unicode.__mod__(self, | |
247 tuple([escape(arg) for arg in args]))) | |
248 | |
249 def __mul__(self, num): | |
250 return Markup(unicode(self) * num) | |
251 | |
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
|
252 def __repr__(self): |
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
|
253 return '<%s "%s">' % (self.__class__.__name__, self) |
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
|
254 |
54 | 255 def join(self, seq, escape_quotes=True): |
256 return Markup(unicode(self).join([escape(item, quotes=escape_quotes) | |
34 | 257 for item in seq])) |
1 | 258 |
259 def stripentities(self, keepxmlentities=False): | |
260 """Return a copy of the text with any character or numeric entities | |
261 replaced by the equivalent UTF-8 characters. | |
262 | |
263 If the `keepxmlentities` parameter is provided and evaluates to `True`, | |
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
|
264 the core XML entities (&, ', >, < and ") are not |
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
|
265 stripped. |
1 | 266 """ |
267 def _replace_entity(match): | |
268 if match.group(1): # numeric entity | |
269 ref = match.group(1) | |
270 if ref.startswith('x'): | |
271 ref = int(ref[1:], 16) | |
272 else: | |
273 ref = int(ref, 10) | |
274 return unichr(ref) | |
275 else: # character entity | |
276 ref = match.group(2) | |
27 | 277 if keepxmlentities and ref in ('amp', 'apos', 'gt', 'lt', |
278 'quot'): | |
1 | 279 return '&%s;' % ref |
280 try: | |
281 codepoint = htmlentitydefs.name2codepoint[ref] | |
282 return unichr(codepoint) | |
283 except KeyError: | |
284 if keepxmlentities: | |
285 return '&%s;' % ref | |
286 else: | |
287 return ref | |
288 return Markup(re.sub(r'&(?:#((?:\d+)|(?:[xX][0-9a-fA-F]+));?|(\w+);)', | |
289 _replace_entity, self)) | |
290 | |
291 def striptags(self): | |
292 """Return a copy of the text with all XML/HTML tags removed.""" | |
293 return Markup(re.sub(r'<[^>]*?>', '', self)) | |
294 | |
295 def escape(cls, text, quotes=True): | |
296 """Create a Markup instance from a string and escape special characters | |
297 it may contain (<, >, & and \"). | |
298 | |
299 If the `quotes` parameter is set to `False`, the \" character is left | |
300 as is. Escaping quotes is generally only required for strings that are | |
301 to be used in attribute values. | |
302 """ | |
73 | 303 if not text: |
304 return cls() | |
305 if type(text) is cls: | |
1 | 306 return text |
73 | 307 text = unicode(text).replace('&', '&') \ |
308 .replace('<', '<') \ | |
309 .replace('>', '>') | |
1 | 310 if quotes: |
311 text = text.replace('"', '"') | |
312 return cls(text) | |
313 escape = classmethod(escape) | |
314 | |
315 def unescape(self): | |
316 """Reverse-escapes &, <, > and \" and returns a `unicode` object.""" | |
317 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
|
318 return u'' |
1 | 319 return unicode(self).replace('"', '"') \ |
320 .replace('>', '>') \ | |
321 .replace('<', '<') \ | |
322 .replace('&', '&') | |
323 | |
324 def plaintext(self, keeplinebreaks=True): | |
6 | 325 """Returns the text as a `unicode` string with all entities and tags |
326 removed. | |
327 """ | |
1 | 328 text = unicode(self.striptags().stripentities()) |
329 if not keeplinebreaks: | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
330 text = text.replace(u'\n', u' ') |
1 | 331 return text |
332 | |
333 def sanitize(self): | |
334 from markup.filters import HTMLSanitizer | |
335 from markup.input import HTMLParser | |
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
|
336 text = StringIO(self.stripentities(keepxmlentities=True)) |
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
|
337 return Stream(HTMLSanitizer()(HTMLParser(text))) |
1 | 338 |
339 | |
340 escape = Markup.escape | |
341 | |
342 def unescape(text): | |
343 """Reverse-escapes &, <, > and \" and returns a `unicode` object.""" | |
344 if not isinstance(text, Markup): | |
345 return text | |
346 return text.unescape() | |
347 | |
348 | |
349 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
|
350 """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
|
351 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
352 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
|
353 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
|
354 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
|
355 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
356 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
|
357 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
358 >>> 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
|
359 >>> html |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
360 <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
|
361 >>> html.uri |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
362 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
|
363 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
364 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
|
365 that namespace: |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
366 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
367 >>> html.body |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
368 u'{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
|
369 >>> html.body.localname |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
370 u'body' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
371 >>> html.body.namespace |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
372 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
|
373 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
374 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
|
375 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
|
376 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
377 >>> html['body'] |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
378 u'{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
|
379 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
380 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
|
381 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
|
382 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
383 >>> qname = html.body |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
384 >>> qname in html |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
385 True |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
386 >>> 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
|
387 False |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
388 """ |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
389 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
|
390 self.uri = unicode(uri) |
1 | 391 |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
392 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
|
393 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
|
394 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
395 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
|
396 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
|
397 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
|
398 return self.uri == other |
1 | 399 |
400 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
|
401 return QName(self.uri + u'}' + name) |
1 | 402 __getattr__ = __getitem__ |
403 | |
404 def __repr__(self): | |
405 return '<Namespace "%s">' % self.uri | |
406 | |
407 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
|
408 return self.uri.encode('utf-8') |
1 | 409 |
410 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
|
411 return self.uri |
1 | 412 |
413 | |
414 class QName(unicode): | |
415 """A qualified element or attribute name. | |
416 | |
417 The unicode value of instances of this class contains the qualified name of | |
418 the element or attribute, in the form `{namespace}localname`. The namespace | |
419 URI can be obtained through the additional `namespace` attribute, while the | |
420 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
|
421 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
422 >>> qname = QName('foo') |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
423 >>> qname |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
424 u'foo' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
425 >>> qname.localname |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
426 u'foo' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
427 >>> qname.namespace |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
428 |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
429 >>> 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
|
430 >>> qname |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
431 u'{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
|
432 >>> qname.localname |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
433 u'body' |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
434 >>> qname.namespace |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
435 u'http://www.w3.org/1999/xhtml' |
1 | 436 """ |
437 __slots__ = ['namespace', 'localname'] | |
438 | |
439 def __new__(cls, qname): | |
440 if isinstance(qname, QName): | |
441 return qname | |
442 | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
443 parts = qname.split(u'}', 1) |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
444 if qname.find(u'}') > 0: |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
445 self = unicode.__new__(cls, u'{' + qname) |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
446 self.namespace = unicode(parts[0]) |
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
447 self.localname = unicode(parts[1]) |
1 | 448 else: |
449 self = unicode.__new__(cls, qname) | |
450 self.namespace = None | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
451 self.localname = unicode(qname) |
1 | 452 return self |