cmlenz@1: # -*- coding: utf-8 -*-
cmlenz@1: #
cmlenz@719: # Copyright (C) 2006-2008 Edgewall Software
cmlenz@1: # All rights reserved.
cmlenz@1: #
cmlenz@1: # This software is licensed as described in the file COPYING, which
cmlenz@1: # you should have received as part of this distribution. The terms
cmlenz@230: # are also available at http://genshi.edgewall.org/wiki/License.
cmlenz@1: #
cmlenz@1: # This software consists of voluntary contributions made by many
cmlenz@1: # individuals. For the exact contribution history, see the revision
cmlenz@230: # history and logs, available at http://genshi.edgewall.org/log/.
cmlenz@1:
cmlenz@1: """Core classes for markup processing."""
cmlenz@1:
cmlenz@792: try:
cmlenz@792: from functools import reduce
cmlenz@792: except ImportError:
cmlenz@792: pass # builtin in Python <= 2.5
cmlenz@634: from itertools import chain
cmlenz@204: import operator
cmlenz@397:
cmlenz@397: from genshi.util import plaintext, stripentities, striptags
cmlenz@1:
cmlenz@377: __all__ = ['Stream', 'Markup', 'escape', 'unescape', 'Attrs', 'Namespace',
cmlenz@377: 'QName']
cmlenz@425: __docformat__ = 'restructuredtext en'
cmlenz@1:
cmlenz@1:
cmlenz@17: class StreamEventKind(str):
cmlenz@397: """A kind of event on a markup stream."""
cmlenz@279: __slots__ = []
cmlenz@279: _instances = {}
cmlenz@279:
cmlenz@279: def __new__(cls, val):
cmlenz@279: return cls._instances.setdefault(val, str.__new__(cls, val))
cmlenz@1:
cmlenz@1:
cmlenz@1: class Stream(object):
cmlenz@1: """Represents a stream of markup events.
cmlenz@1:
cmlenz@1: This class is basically an iterator over the events.
cmlenz@1:
cmlenz@425: Stream events are tuples of the form::
cmlenz@397:
cmlenz@397: (kind, data, position)
cmlenz@397:
cmlenz@425: where ``kind`` is the event kind (such as `START`, `END`, `TEXT`, etc),
cmlenz@425: ``data`` depends on the kind of event, and ``position`` is a
cmlenz@425: ``(filename, line, offset)`` tuple that contains the location of the
cmlenz@425: original element or text in the input. If the original location is unknown,
cmlenz@425: ``position`` is ``(None, -1, -1)``.
cmlenz@397:
cmlenz@1: Also provided are ways to serialize the stream to text. The `serialize()`
cmlenz@1: method will return an iterator over generated strings, while `render()`
cmlenz@1: returns the complete generated text at once. Both accept various parameters
cmlenz@1: that impact the way the stream is serialized.
cmlenz@1: """
cmlenz@605: __slots__ = ['events', 'serializer']
cmlenz@1:
cmlenz@427: START = StreamEventKind('START') #: a start tag
cmlenz@427: END = StreamEventKind('END') #: an end tag
cmlenz@427: TEXT = StreamEventKind('TEXT') #: literal text
cmlenz@460: XML_DECL = StreamEventKind('XML_DECL') #: XML declaration
cmlenz@427: DOCTYPE = StreamEventKind('DOCTYPE') #: doctype declaration
cmlenz@427: START_NS = StreamEventKind('START_NS') #: start namespace mapping
cmlenz@427: END_NS = StreamEventKind('END_NS') #: end namespace mapping
cmlenz@427: START_CDATA = StreamEventKind('START_CDATA') #: start CDATA section
cmlenz@427: END_CDATA = StreamEventKind('END_CDATA') #: end CDATA section
cmlenz@427: PI = StreamEventKind('PI') #: processing instruction
cmlenz@427: COMMENT = StreamEventKind('COMMENT') #: comment
cmlenz@1:
cmlenz@605: def __init__(self, events, serializer=None):
cmlenz@1: """Initialize the stream with a sequence of markup events.
cmlenz@1:
cmlenz@425: :param events: a sequence or iterable providing the events
cmlenz@605: :param serializer: the default serialization method to use for this
cmlenz@605: stream
cmlenz@605:
cmlenz@605: :note: Changed in 0.5: added the `serializer` argument
cmlenz@1: """
cmlenz@498: self.events = events #: The underlying iterable producing the events
cmlenz@605: self.serializer = serializer #: The default serializion method
cmlenz@1:
cmlenz@1: def __iter__(self):
cmlenz@1: return iter(self.events)
cmlenz@1:
cmlenz@204: def __or__(self, function):
cmlenz@204: """Override the "bitwise or" operator to apply filters or serializers
cmlenz@204: to the stream, providing a syntax similar to pipes on Unix shells.
cmlenz@204:
cmlenz@204: Assume the following stream produced by the `HTML` function:
cmlenz@204:
cmlenz@230: >>> from genshi.input import HTML
cmlenz@204: >>> html = HTML('''
Hello, world!
''')
cmlenz@204: >>> print html
cmlenz@204: Hello, world!
cmlenz@204:
cmlenz@204: A filter such as the HTML sanitizer can be applied to that stream using
cmlenz@204: the pipe notation as follows:
cmlenz@204:
cmlenz@230: >>> from genshi.filters import HTMLSanitizer
cmlenz@204: >>> sanitizer = HTMLSanitizer()
cmlenz@204: >>> print html | sanitizer
cmlenz@204: Hello, world!
cmlenz@204:
cmlenz@204: Filters can be any function that accepts and produces a stream (where
cmlenz@397: a stream is anything that iterates over events):
cmlenz@204:
cmlenz@204: >>> def uppercase(stream):
cmlenz@204: ... for kind, data, pos in stream:
cmlenz@204: ... if kind is TEXT:
cmlenz@204: ... data = data.upper()
cmlenz@204: ... yield kind, data, pos
cmlenz@204: >>> print html | sanitizer | uppercase
cmlenz@204: HELLO, WORLD!
cmlenz@204:
cmlenz@204: Serializers can also be used with this notation:
cmlenz@204:
cmlenz@230: >>> from genshi.output import TextSerializer
cmlenz@204: >>> output = TextSerializer()
cmlenz@204: >>> print html | sanitizer | uppercase | output
cmlenz@204: HELLO, WORLD!
cmlenz@204:
cmlenz@204: Commonly, serializers should be used at the end of the "pipeline";
cmlenz@204: using them somewhere in the middle may produce unexpected results.
cmlenz@498:
cmlenz@498: :param function: the callable object that should be applied as a filter
cmlenz@498: :return: the filtered stream
cmlenz@498: :rtype: `Stream`
cmlenz@204: """
cmlenz@605: return Stream(_ensure(function(self)), serializer=self.serializer)
cmlenz@204:
cmlenz@123: def filter(self, *filters):
cmlenz@123: """Apply filters to the stream.
cmlenz@113:
cmlenz@123: This method returns a new stream with the given filters applied. The
cmlenz@123: filters must be callables that accept the stream object as parameter,
cmlenz@123: and return the filtered stream.
cmlenz@204:
cmlenz@425: The call::
cmlenz@204:
cmlenz@204: stream.filter(filter1, filter2)
cmlenz@204:
cmlenz@425: is equivalent to::
cmlenz@204:
cmlenz@204: stream | filter1 | filter2
cmlenz@498:
cmlenz@498: :param filters: one or more callable objects that should be applied as
cmlenz@498: filters
cmlenz@498: :return: the filtered stream
cmlenz@498: :rtype: `Stream`
cmlenz@113: """
cmlenz@204: return reduce(operator.or_, (self,) + filters)
cmlenz@113:
cmlenz@688: def render(self, method=None, encoding='utf-8', out=None, **kwargs):
cmlenz@1: """Return a string representation of the stream.
cmlenz@1:
cmlenz@498: Any additional keyword arguments are passed to the serializer, and thus
cmlenz@498: depend on the `method` parameter value.
cmlenz@498:
cmlenz@425: :param method: determines how the stream is serialized; can be either
cmlenz@200: "xml", "xhtml", "html", "text", or a custom serializer
cmlenz@605: class; if `None`, the default serialization method of
cmlenz@605: the stream is used
cmlenz@425: :param encoding: how the output string should be encoded; if set to
cmlenz@1: `None`, this method returns a `unicode` object
cmlenz@688: :param out: a file-like object that the output should be written to
cmlenz@688: instead of being returned as one big string; note that if
cmlenz@688: this is a file or socket (or similar), the `encoding` must
cmlenz@688: not be `None` (that is, the output must be encoded)
cmlenz@688: :return: a `str` or `unicode` object (depending on the `encoding`
cmlenz@688: parameter), or `None` if the `out` parameter is provided
cmlenz@498: :rtype: `basestring`
cmlenz@688:
cmlenz@498: :see: XMLSerializer, XHTMLSerializer, HTMLSerializer, TextSerializer
cmlenz@688: :note: Changed in 0.5: added the `out` parameter
cmlenz@1: """
cmlenz@462: from genshi.output import encode
cmlenz@605: if method is None:
cmlenz@605: method = self.serializer or 'xml'
cmlenz@123: generator = self.serialize(method=method, **kwargs)
cmlenz@688: return encode(generator, method=method, encoding=encoding, out=out)
cmlenz@1:
cmlenz@278: def select(self, path, namespaces=None, variables=None):
cmlenz@1: """Return a new stream that contains the events matching the given
cmlenz@1: XPath expression.
cmlenz@1:
cmlenz@576: >>> from genshi import HTML
cmlenz@576: >>> stream = HTML('foobar')
cmlenz@576: >>> print stream.select('elem')
cmlenz@576: foobar
cmlenz@576: >>> print stream.select('elem/text()')
cmlenz@576: foobar
cmlenz@576:
cmlenz@576: Note that the outermost element of the stream becomes the *context
cmlenz@576: node* for the XPath test. That means that the expression "doc" would
cmlenz@576: not match anything in the example above, because it only tests against
cmlenz@576: child elements of the outermost element:
cmlenz@576:
cmlenz@576: >>> print stream.select('doc')
cmlenz@576:
cmlenz@576:
cmlenz@576: You can use the "." expression to match the context node itself
cmlenz@576: (although that usually makes little sense):
cmlenz@576:
cmlenz@576: >>> print stream.select('.')
cmlenz@576: foobar
cmlenz@576:
cmlenz@425: :param path: a string containing the XPath expression
cmlenz@435: :param namespaces: mapping of namespace prefixes used in the path
cmlenz@435: :param variables: mapping of variable names to values
cmlenz@435: :return: the selected substream
cmlenz@498: :rtype: `Stream`
cmlenz@435: :raises PathSyntaxError: if the given path expression is invalid or not
cmlenz@435: supported
cmlenz@1: """
cmlenz@230: from genshi.path import Path
cmlenz@278: return Path(path).select(self, namespaces, variables)
cmlenz@1:
cmlenz@123: def serialize(self, method='xml', **kwargs):
cmlenz@1: """Generate strings corresponding to a specific serialization of the
cmlenz@1: stream.
cmlenz@1:
cmlenz@18: Unlike the `render()` method, this method is a generator that returns
cmlenz@1: the serialized output incrementally, as opposed to returning a single
cmlenz@1: string.
cmlenz@1:
cmlenz@498: Any additional keyword arguments are passed to the serializer, and thus
cmlenz@498: depend on the `method` parameter value.
cmlenz@498:
cmlenz@425: :param method: determines how the stream is serialized; can be either
cmlenz@200: "xml", "xhtml", "html", "text", or a custom serializer
cmlenz@605: class; if `None`, the default serialization method of
cmlenz@605: the stream is used
cmlenz@498: :return: an iterator over the serialization results (`Markup` or
cmlenz@498: `unicode` objects, depending on the serialization method)
cmlenz@498: :rtype: ``iterator``
cmlenz@498: :see: XMLSerializer, XHTMLSerializer, HTMLSerializer, TextSerializer
cmlenz@1: """
cmlenz@462: from genshi.output import get_serializer
cmlenz@605: if method is None:
cmlenz@605: method = self.serializer or 'xml'
cmlenz@462: return get_serializer(method, **kwargs)(_ensure(self))
cmlenz@1:
cmlenz@1: def __str__(self):
cmlenz@1: return self.render()
cmlenz@1:
cmlenz@1: def __unicode__(self):
cmlenz@1: return self.render(encoding=None)
cmlenz@1:
cmlenz@737: def __html__(self):
cmlenz@737: return self
cmlenz@737:
cmlenz@1:
cmlenz@69: START = Stream.START
cmlenz@69: END = Stream.END
cmlenz@69: TEXT = Stream.TEXT
cmlenz@460: XML_DECL = Stream.XML_DECL
cmlenz@69: DOCTYPE = Stream.DOCTYPE
cmlenz@69: START_NS = Stream.START_NS
cmlenz@69: END_NS = Stream.END_NS
cmlenz@143: START_CDATA = Stream.START_CDATA
cmlenz@143: END_CDATA = Stream.END_CDATA
cmlenz@69: PI = Stream.PI
cmlenz@69: COMMENT = Stream.COMMENT
cmlenz@69:
cmlenz@111: def _ensure(stream):
cmlenz@111: """Ensure that every item on the stream is actually a markup event."""
cmlenz@634: stream = iter(stream)
cmlenz@634: event = stream.next()
cmlenz@634:
cmlenz@634: # Check whether the iterable is a real markup event stream by examining the
cmlenz@634: # first item it yields; if it's not we'll need to do some conversion
cmlenz@634: if type(event) is not tuple or len(event) != 3:
cmlenz@634: for event in chain([event], stream):
cmlenz@145: if hasattr(event, 'totuple'):
cmlenz@145: event = event.totuple()
cmlenz@145: else:
cmlenz@145: event = TEXT, unicode(event), (None, -1, -1)
cmlenz@634: yield event
cmlenz@634: return
cmlenz@634:
cmlenz@634: # This looks like a markup event stream, so we'll just pass it through
cmlenz@634: # unchanged
cmlenz@634: yield event
cmlenz@634: for event in stream:
cmlenz@145: yield event
cmlenz@111:
cmlenz@69:
cmlenz@345: class Attrs(tuple):
cmlenz@345: """Immutable sequence type that stores the attributes of an element.
cmlenz@18:
cmlenz@434: Ordering of the attributes is preserved, while access by name is also
cmlenz@345: supported.
cmlenz@18:
cmlenz@182: >>> attrs = Attrs([('href', '#'), ('title', 'Foo')])
cmlenz@18: >>> attrs
cmlenz@403: Attrs([('href', '#'), ('title', 'Foo')])
cmlenz@18:
cmlenz@18: >>> 'href' in attrs
cmlenz@18: True
cmlenz@18: >>> 'tabindex' in attrs
cmlenz@18: False
cmlenz@403: >>> attrs.get('title')
cmlenz@18: 'Foo'
cmlenz@345:
cmlenz@425: Instances may not be manipulated directly. Instead, the operators ``|`` and
cmlenz@425: ``-`` can be used to produce new instances that have specific attributes
cmlenz@345: added, replaced or removed.
cmlenz@345:
cmlenz@425: To remove an attribute, use the ``-`` operator. The right hand side can be
cmlenz@345: either a string or a set/sequence of strings, identifying the name(s) of
cmlenz@345: the attribute(s) to remove:
cmlenz@345:
cmlenz@345: >>> attrs - 'title'
cmlenz@403: Attrs([('href', '#')])
cmlenz@345: >>> attrs - ('title', 'href')
cmlenz@345: Attrs()
cmlenz@345:
cmlenz@345: The original instance is not modified, but the operator can of course be
cmlenz@345: used with an assignment:
cmlenz@345:
cmlenz@18: >>> attrs
cmlenz@403: Attrs([('href', '#'), ('title', 'Foo')])
cmlenz@345: >>> attrs -= 'title'
cmlenz@18: >>> attrs
cmlenz@403: Attrs([('href', '#')])
cmlenz@18:
cmlenz@425: To add a new attribute, use the ``|`` operator, where the right hand value
cmlenz@425: is a sequence of ``(name, value)`` tuples (which includes `Attrs`
cmlenz@425: instances):
cmlenz@170:
cmlenz@403: >>> attrs | [('title', 'Bar')]
cmlenz@403: Attrs([('href', '#'), ('title', 'Bar')])
cmlenz@171:
cmlenz@345: If the attributes already contain an attribute with a given name, the value
cmlenz@345: of that attribute is replaced:
cmlenz@171:
cmlenz@403: >>> attrs | [('href', 'http://example.org/')]
cmlenz@403: Attrs([('href', 'http://example.org/')])
cmlenz@18: """
cmlenz@18: __slots__ = []
cmlenz@1:
cmlenz@1: def __contains__(self, name):
cmlenz@18: """Return whether the list includes an attribute with the specified
cmlenz@18: name.
cmlenz@498:
cmlenz@498: :return: `True` if the list includes the attribute
cmlenz@498: :rtype: `bool`
cmlenz@18: """
cmlenz@133: for attr, _ in self:
cmlenz@133: if attr == name:
cmlenz@133: return True
cmlenz@1:
cmlenz@345: def __getslice__(self, i, j):
cmlenz@593: """Return a slice of the attributes list.
cmlenz@593:
cmlenz@593: >>> attrs = Attrs([('href', '#'), ('title', 'Foo')])
cmlenz@593: >>> attrs[1:]
cmlenz@593: Attrs([('title', 'Foo')])
cmlenz@593: """
cmlenz@345: return Attrs(tuple.__getslice__(self, i, j))
cmlenz@345:
cmlenz@345: def __or__(self, attrs):
cmlenz@345: """Return a new instance that contains the attributes in `attrs` in
cmlenz@345: addition to any already existing attributes.
cmlenz@498:
cmlenz@498: :return: a new instance with the merged attributes
cmlenz@498: :rtype: `Attrs`
cmlenz@345: """
cmlenz@345: repl = dict([(an, av) for an, av in attrs if an in self])
cmlenz@345: return Attrs([(sn, repl.get(sn, sv)) for sn, sv in self] +
cmlenz@345: [(an, av) for an, av in attrs if an not in self])
cmlenz@345:
cmlenz@326: def __repr__(self):
cmlenz@326: if not self:
cmlenz@326: return 'Attrs()'
cmlenz@345: return 'Attrs([%s])' % ', '.join([repr(item) for item in self])
cmlenz@345:
cmlenz@345: def __sub__(self, names):
cmlenz@345: """Return a new instance with all attributes with a name in `names` are
cmlenz@345: removed.
cmlenz@498:
cmlenz@498: :param names: the names of the attributes to remove
cmlenz@498: :return: a new instance with the attribute removed
cmlenz@498: :rtype: `Attrs`
cmlenz@345: """
cmlenz@345: if isinstance(names, basestring):
cmlenz@345: names = (names,)
cmlenz@345: return Attrs([(name, val) for name, val in self if name not in names])
cmlenz@326:
cmlenz@1: def get(self, name, default=None):
cmlenz@18: """Return the value of the attribute with the specified name, or the
cmlenz@18: value of the `default` parameter if no such attribute is found.
cmlenz@435:
cmlenz@435: :param name: the name of the attribute
cmlenz@435: :param default: the value to return when the attribute does not exist
cmlenz@435: :return: the attribute value, or the `default` value if that attribute
cmlenz@435: does not exist
cmlenz@498: :rtype: `object`
cmlenz@18: """
cmlenz@1: for attr, value in self:
cmlenz@1: if attr == name:
cmlenz@1: return value
cmlenz@1: return default
cmlenz@1:
cmlenz@77: def totuple(self):
cmlenz@161: """Return the attributes as a markup event.
cmlenz@161:
cmlenz@425: The returned event is a `TEXT` event, the data is the value of all
cmlenz@161: attributes joined together.
cmlenz@434:
cmlenz@434: >>> Attrs([('href', '#'), ('title', 'Foo')]).totuple()
cmlenz@434: ('TEXT', u'#Foo', (None, -1, -1))
cmlenz@498:
cmlenz@498: :return: a `TEXT` event
cmlenz@498: :rtype: `tuple`
cmlenz@161: """
cmlenz@77: return TEXT, u''.join([x[1] for x in self]), (None, -1, -1)
cmlenz@77:
cmlenz@1:
cmlenz@1: class Markup(unicode):
cmlenz@1: """Marks a string as being safe for inclusion in HTML/XML output without
cmlenz@1: needing to be escaped.
cmlenz@1: """
cmlenz@18: __slots__ = []
cmlenz@18:
cmlenz@1: def __add__(self, other):
cmlenz@204: return Markup(unicode(self) + unicode(escape(other)))
cmlenz@204:
cmlenz@204: def __radd__(self, other):
cmlenz@204: return Markup(unicode(escape(other)) + unicode(self))
cmlenz@1:
cmlenz@1: def __mod__(self, args):
cmlenz@713: if isinstance(args, dict):
cmlenz@713: args = dict(zip(args.keys(), map(escape, args.values())))
cmlenz@713: elif isinstance(args, (list, tuple)):
cmlenz@713: args = tuple(map(escape, args))
cmlenz@713: else:
cmlenz@713: args = escape(args)
cmlenz@713: return Markup(unicode.__mod__(self, args))
cmlenz@1:
cmlenz@1: def __mul__(self, num):
cmlenz@1: return Markup(unicode(self) * num)
cmlenz@1:
cmlenz@204: def __rmul__(self, num):
cmlenz@204: return Markup(num * unicode(self))
cmlenz@204:
cmlenz@17: def __repr__(self):
cmlenz@382: return '<%s %r>' % (self.__class__.__name__, unicode(self))
cmlenz@17:
cmlenz@54: def join(self, seq, escape_quotes=True):
cmlenz@434: """Return a `Markup` object which is the concatenation of the strings
cmlenz@434: in the given sequence, where this `Markup` object is the separator
cmlenz@434: between the joined elements.
cmlenz@434:
cmlenz@434: Any element in the sequence that is not a `Markup` instance is
cmlenz@434: automatically escaped.
cmlenz@434:
cmlenz@434: :param seq: the sequence of strings to join
cmlenz@434: :param escape_quotes: whether double quote characters in the elements
cmlenz@434: should be escaped
cmlenz@434: :return: the joined `Markup` object
cmlenz@498: :rtype: `Markup`
cmlenz@434: :see: `escape`
cmlenz@434: """
cmlenz@54: return Markup(unicode(self).join([escape(item, quotes=escape_quotes)
mgood@34: for item in seq]))
cmlenz@1:
cmlenz@1: def escape(cls, text, quotes=True):
cmlenz@1: """Create a Markup instance from a string and escape special characters
cmlenz@1: it may contain (<, >, & and \").
cmlenz@1:
cmlenz@434: >>> escape('"1 < 2"')
cmlenz@434:
cmlenz@434:
cmlenz@1: If the `quotes` parameter is set to `False`, the \" character is left
cmlenz@1: as is. Escaping quotes is generally only required for strings that are
cmlenz@1: to be used in attribute values.
cmlenz@434:
cmlenz@434: >>> escape('"1 < 2"', quotes=False)
cmlenz@434:
cmlenz@434:
cmlenz@434: :param text: the text to escape
cmlenz@434: :param quotes: if ``True``, double quote characters are escaped in
cmlenz@434: addition to the other special characters
cmlenz@434: :return: the escaped `Markup` string
cmlenz@498: :rtype: `Markup`
cmlenz@1: """
cmlenz@73: if not text:
cmlenz@73: return cls()
cmlenz@73: if type(text) is cls:
cmlenz@1: return text
cmlenz@737: if hasattr(text, '__html__'):
cmlenz@737: return Markup(text.__html__())
cmlenz@737:
cmlenz@73: text = unicode(text).replace('&', '&') \
cmlenz@73: .replace('<', '<') \
cmlenz@73: .replace('>', '>')
cmlenz@1: if quotes:
cmlenz@1: text = text.replace('"', '"')
cmlenz@1: return cls(text)
cmlenz@1: escape = classmethod(escape)
cmlenz@1:
cmlenz@1: def unescape(self):
cmlenz@434: """Reverse-escapes &, <, >, and \" and returns a `unicode` object.
cmlenz@434:
cmlenz@434: >>> Markup('1 < 2').unescape()
cmlenz@434: u'1 < 2'
cmlenz@434:
cmlenz@498: :return: the unescaped string
cmlenz@498: :rtype: `unicode`
cmlenz@434: :see: `genshi.core.unescape`
cmlenz@434: """
cmlenz@1: if not self:
cmlenz@18: return u''
cmlenz@1: return unicode(self).replace('"', '"') \
cmlenz@1: .replace('>', '>') \
cmlenz@1: .replace('<', '<') \
cmlenz@1: .replace('&', '&')
cmlenz@1:
cmlenz@116: def stripentities(self, keepxmlentities=False):
cmlenz@116: """Return a copy of the text with any character or numeric entities
cmlenz@116: replaced by the equivalent UTF-8 characters.
cmlenz@116:
cmlenz@116: If the `keepxmlentities` parameter is provided and evaluates to `True`,
cmlenz@434: the core XML entities (``&``, ``'``, ``>``, ``<`` and
cmlenz@434: ``"``) are not stripped.
cmlenz@434:
cmlenz@498: :return: a `Markup` instance with entities removed
cmlenz@498: :rtype: `Markup`
cmlenz@434: :see: `genshi.util.stripentities`
cmlenz@6: """
cmlenz@116: return Markup(stripentities(self, keepxmlentities=keepxmlentities))
cmlenz@116:
cmlenz@116: def striptags(self):
cmlenz@434: """Return a copy of the text with all XML/HTML tags removed.
cmlenz@434:
cmlenz@498: :return: a `Markup` instance with all tags removed
cmlenz@498: :rtype: `Markup`
cmlenz@434: :see: `genshi.util.striptags`
cmlenz@434: """
cmlenz@116: return Markup(striptags(self))
cmlenz@1:
cmlenz@1:
cmlenz@541: try:
cmlenz@541: from genshi._speedups import Markup
cmlenz@541: except ImportError:
cmlenz@541: pass # just use the Python implementation
cmlenz@541:
cmlenz@1: escape = Markup.escape
cmlenz@1:
cmlenz@1: def unescape(text):
cmlenz@434: """Reverse-escapes &, <, >, and \" and returns a `unicode` object.
cmlenz@434:
cmlenz@434: >>> unescape(Markup('1 < 2'))
cmlenz@434: u'1 < 2'
cmlenz@434:
cmlenz@498: If the provided `text` object is not a `Markup` instance, it is returned
cmlenz@498: unchanged.
cmlenz@434:
cmlenz@434: >>> unescape('1 < 2')
cmlenz@434: '1 < 2'
cmlenz@434:
cmlenz@434: :param text: the text to unescape
cmlenz@498: :return: the unescsaped string
cmlenz@498: :rtype: `unicode`
cmlenz@434: """
cmlenz@1: if not isinstance(text, Markup):
cmlenz@1: return text
cmlenz@1: return text.unescape()
cmlenz@1:
cmlenz@1:
cmlenz@1: class Namespace(object):
cmlenz@18: """Utility class creating and testing elements with a namespace.
cmlenz@18:
cmlenz@18: Internally, namespace URIs are encoded in the `QName` of any element or
cmlenz@18: attribute, the namespace URI being enclosed in curly braces. This class
cmlenz@18: helps create and test these strings.
cmlenz@18:
cmlenz@18: A `Namespace` object is instantiated with the namespace URI.
cmlenz@18:
cmlenz@18: >>> html = Namespace('http://www.w3.org/1999/xhtml')
cmlenz@18: >>> html
cmlenz@18:
cmlenz@18: >>> html.uri
cmlenz@18: u'http://www.w3.org/1999/xhtml'
cmlenz@18:
cmlenz@18: The `Namespace` object can than be used to generate `QName` objects with
cmlenz@18: that namespace:
cmlenz@18:
cmlenz@18: >>> html.body
cmlenz@326: QName(u'http://www.w3.org/1999/xhtml}body')
cmlenz@18: >>> html.body.localname
cmlenz@18: u'body'
cmlenz@18: >>> html.body.namespace
cmlenz@18: u'http://www.w3.org/1999/xhtml'
cmlenz@18:
cmlenz@18: The same works using item access notation, which is useful for element or
cmlenz@18: attribute names that are not valid Python identifiers:
cmlenz@18:
cmlenz@18: >>> html['body']
cmlenz@326: QName(u'http://www.w3.org/1999/xhtml}body')
cmlenz@18:
cmlenz@18: A `Namespace` object can also be used to test whether a specific `QName`
cmlenz@425: belongs to that namespace using the ``in`` operator:
cmlenz@18:
cmlenz@18: >>> qname = html.body
cmlenz@18: >>> qname in html
cmlenz@18: True
cmlenz@18: >>> qname in Namespace('http://www.w3.org/2002/06/xhtml2')
cmlenz@18: False
cmlenz@18: """
cmlenz@224: def __new__(cls, uri):
cmlenz@224: if type(uri) is cls:
cmlenz@224: return uri
cmlenz@685: return object.__new__(cls)
cmlenz@224:
cmlenz@279: def __getnewargs__(self):
cmlenz@279: return (self.uri,)
cmlenz@279:
cmlenz@279: def __getstate__(self):
cmlenz@279: return self.uri
cmlenz@279:
cmlenz@279: def __setstate__(self, uri):
cmlenz@279: self.uri = uri
cmlenz@279:
cmlenz@18: def __init__(self, uri):
cmlenz@18: self.uri = unicode(uri)
cmlenz@1:
cmlenz@18: def __contains__(self, qname):
cmlenz@18: return qname.namespace == self.uri
cmlenz@18:
cmlenz@278: def __ne__(self, other):
cmlenz@278: return not self == other
cmlenz@278:
cmlenz@18: def __eq__(self, other):
cmlenz@18: if isinstance(other, Namespace):
cmlenz@18: return self.uri == other.uri
cmlenz@18: return self.uri == other
cmlenz@1:
cmlenz@1: def __getitem__(self, name):
cmlenz@18: return QName(self.uri + u'}' + name)
cmlenz@1: __getattr__ = __getitem__
cmlenz@1:
cmlenz@793: def __hash__(self):
cmlenz@793: return hash(self.uri)
cmlenz@793:
cmlenz@1: def __repr__(self):
cmlenz@1: return '' % self.uri
cmlenz@1:
cmlenz@1: def __str__(self):
cmlenz@18: return self.uri.encode('utf-8')
cmlenz@1:
cmlenz@1: def __unicode__(self):
cmlenz@18: return self.uri
cmlenz@1:
cmlenz@1:
cmlenz@147: # The namespace used by attributes such as xml:lang and xml:space
cmlenz@141: XML_NAMESPACE = Namespace('http://www.w3.org/XML/1998/namespace')
cmlenz@141:
cmlenz@141:
cmlenz@1: class QName(unicode):
cmlenz@1: """A qualified element or attribute name.
cmlenz@1:
cmlenz@1: The unicode value of instances of this class contains the qualified name of
cmlenz@666: the element or attribute, in the form ``{namespace-uri}local-name``. The
cmlenz@666: namespace URI can be obtained through the additional `namespace` attribute,
cmlenz@666: while the local name can be accessed through the `localname` attribute.
cmlenz@18:
cmlenz@18: >>> qname = QName('foo')
cmlenz@18: >>> qname
cmlenz@326: QName(u'foo')
cmlenz@18: >>> qname.localname
cmlenz@18: u'foo'
cmlenz@18: >>> qname.namespace
cmlenz@18:
cmlenz@18: >>> qname = QName('http://www.w3.org/1999/xhtml}body')
cmlenz@18: >>> qname
cmlenz@326: QName(u'http://www.w3.org/1999/xhtml}body')
cmlenz@18: >>> qname.localname
cmlenz@18: u'body'
cmlenz@18: >>> qname.namespace
cmlenz@18: u'http://www.w3.org/1999/xhtml'
cmlenz@1: """
cmlenz@1: __slots__ = ['namespace', 'localname']
cmlenz@1:
cmlenz@1: def __new__(cls, qname):
cmlenz@666: """Create the `QName` instance.
cmlenz@666:
cmlenz@666: :param qname: the qualified name as a string of the form
cmlenz@666: ``{namespace-uri}local-name``, where the leading curly
cmlenz@666: brace is optional
cmlenz@666: """
cmlenz@100: if type(qname) is cls:
cmlenz@1: return qname
cmlenz@1:
cmlenz@666: parts = qname.lstrip(u'{').split(u'}', 1)
cmlenz@100: if len(parts) > 1:
cmlenz@136: self = unicode.__new__(cls, u'{%s' % qname)
cmlenz@136: self.namespace, self.localname = map(unicode, parts)
cmlenz@1: else:
cmlenz@1: self = unicode.__new__(cls, qname)
cmlenz@136: self.namespace, self.localname = None, unicode(qname)
cmlenz@1: return self
cmlenz@279:
cmlenz@279: def __getnewargs__(self):
cmlenz@279: return (self.lstrip('{'),)
cmlenz@326:
cmlenz@326: def __repr__(self):
cmlenz@326: return 'QName(%s)' % unicode.__repr__(self.lstrip('{'))