PK8VEGG-INFO/top_level.txtgenshi PK82EGG-INFO/dependency_links.txt PK8J5EGG-INFO/SOURCES.txtMANIFEST.in README.txt setup.cfg setup.py Genshi.egg-info/PKG-INFO Genshi.egg-info/SOURCES.txt Genshi.egg-info/dependency_links.txt Genshi.egg-info/entry_points.txt Genshi.egg-info/native_libs.txt Genshi.egg-info/requires.txt Genshi.egg-info/top_level.txt Genshi.egg-info/zip-safe genshi/__init__.py genshi/_speedups.c genshi/builder.py genshi/core.py genshi/input.py genshi/output.py genshi/path.py genshi/util.py genshi/filters/__init__.py genshi/filters/html.py genshi/filters/i18n.py genshi/filters/transform.py genshi/template/__init__.py genshi/template/base.py genshi/template/directives.py genshi/template/eval.py genshi/template/interpolation.py genshi/template/loader.py genshi/template/markup.py genshi/template/plugin.py genshi/template/text.pyPK8pĆnnEGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: Genshi Version: 0.5.1 Summary: A toolkit for generation of output for the web Home-page: http://genshi.edgewall.org/ Author: Edgewall Software Author-email: info@edgewall.org License: BSD Download-URL: http://genshi.edgewall.org/wiki/Download Description: Genshi is a Python library that provides an integrated set of components for parsing, generating, and processing HTML, XML or other textual content for output generation on the web. The major feature is a template language, which is heavily inspired by Kid. Keywords: python.templating.engines Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Text Processing :: Markup :: HTML Classifier: Topic :: Text Processing :: Markup :: XML PK8RD//EGG-INFO/requires.txt [i18n] Babel>=0.8 [plugin] setuptools>=0.6a2PK8OOEGG-INFO/entry_points.txt [babel.extractors] genshi = genshi.filters.i18n:extract[i18n] [python.templating.engines] genshi = genshi.template.plugin:MarkupTemplateEnginePlugin[plugin] genshi-markup = genshi.template.plugin:MarkupTemplateEnginePlugin[plugin] genshi-text = genshi.template.plugin:TextTemplateEnginePlugin[plugin] PK82EGG-INFO/zip-safe PK8̧QEGG-INFO/native_libs.txtgenshi/_speedups.so PK$6>>genshi/input.py# -*- coding: utf-8 -*- # # Copyright (C) 2006-2007 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://genshi.edgewall.org/wiki/License. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://genshi.edgewall.org/log/. """Support for constructing markup streams from files, strings, or other sources. """ from itertools import chain from xml.parsers import expat try: frozenset except NameError: from sets import ImmutableSet as frozenset import HTMLParser as html import htmlentitydefs from StringIO import StringIO from genshi.core import Attrs, QName, Stream, stripentities from genshi.core import START, END, XML_DECL, DOCTYPE, TEXT, START_NS, END_NS, \ START_CDATA, END_CDATA, PI, COMMENT __all__ = ['ET', 'ParseError', 'XMLParser', 'XML', 'HTMLParser', 'HTML'] __docformat__ = 'restructuredtext en' def ET(element): """Convert a given ElementTree element to a markup stream. :param element: an ElementTree element :return: a markup stream """ tag_name = QName(element.tag.lstrip('{')) attrs = Attrs([(QName(attr.lstrip('{')), value) for attr, value in element.items()]) yield START, (tag_name, attrs), (None, -1, -1) if element.text: yield TEXT, element.text, (None, -1, -1) for child in element.getchildren(): for item in ET(child): yield item yield END, tag_name, (None, -1, -1) if element.tail: yield TEXT, element.tail, (None, -1, -1) class ParseError(Exception): """Exception raised when fatal syntax errors are found in the input being parsed. """ def __init__(self, message, filename=None, lineno=-1, offset=-1): """Exception initializer. :param message: the error message from the parser :param filename: the path to the file that was parsed :param lineno: the number of the line on which the error was encountered :param offset: the column number where the error was encountered """ self.msg = message if filename: message += ', in ' + filename Exception.__init__(self, message) self.filename = filename or '' self.lineno = lineno self.offset = offset class XMLParser(object): """Generator-based XML parser based on roughly equivalent code in Kid/ElementTree. The parsing is initiated by iterating over the parser object: >>> parser = XMLParser(StringIO('Foo')) >>> for kind, data, pos in parser: ... print kind, data START (QName(u'root'), Attrs([(QName(u'id'), u'2')])) START (QName(u'child'), Attrs()) TEXT Foo END child END root """ _entitydefs = ['' % (name, value) for name, value in htmlentitydefs.name2codepoint.items()] _external_dtd = '\n'.join(_entitydefs) def __init__(self, source, filename=None, encoding=None): """Initialize the parser for the given XML input. :param source: the XML text as a file-like object :param filename: the name of the file, if appropriate :param encoding: the encoding of the file; if not specified, the encoding is assumed to be ASCII, UTF-8, or UTF-16, or whatever the encoding specified in the XML declaration (if any) """ self.source = source self.filename = filename # Setup the Expat parser parser = expat.ParserCreate(encoding, '}') parser.buffer_text = True parser.returns_unicode = True parser.ordered_attributes = True parser.StartElementHandler = self._handle_start parser.EndElementHandler = self._handle_end parser.CharacterDataHandler = self._handle_data parser.StartDoctypeDeclHandler = self._handle_doctype parser.StartNamespaceDeclHandler = self._handle_start_ns parser.EndNamespaceDeclHandler = self._handle_end_ns parser.StartCdataSectionHandler = self._handle_start_cdata parser.EndCdataSectionHandler = self._handle_end_cdata parser.ProcessingInstructionHandler = self._handle_pi parser.XmlDeclHandler = self._handle_xml_decl parser.CommentHandler = self._handle_comment # Tell Expat that we'll handle non-XML entities ourselves # (in _handle_other) parser.DefaultHandler = self._handle_other parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) parser.UseForeignDTD() parser.ExternalEntityRefHandler = self._build_foreign # Location reporting is only support in Python >= 2.4 if not hasattr(parser, 'CurrentLineNumber'): self._getpos = self._getpos_unknown self.expat = parser self._queue = [] def parse(self): """Generator that parses the XML source, yielding markup events. :return: a markup event stream :raises ParseError: if the XML text is not well formed """ def _generate(): try: bufsize = 4 * 1024 # 4K done = False while 1: while not done and len(self._queue) == 0: data = self.source.read(bufsize) if data == '': # end of data if hasattr(self, 'expat'): self.expat.Parse('', True) del self.expat # get rid of circular references done = True else: if isinstance(data, unicode): data = data.encode('utf-8') self.expat.Parse(data, False) for event in self._queue: yield event self._queue = [] if done: break except expat.ExpatError, e: msg = str(e) raise ParseError(msg, self.filename, e.lineno, e.offset) return Stream(_generate()).filter(_coalesce) def __iter__(self): return iter(self.parse()) def _build_foreign(self, context, base, sysid, pubid): parser = self.expat.ExternalEntityParserCreate(context) parser.ParseFile(StringIO(self._external_dtd)) return 1 def _enqueue(self, kind, data=None, pos=None): if pos is None: pos = self._getpos() if kind is TEXT: # Expat reports the *end* of the text event as current position. We # try to fix that up here as much as possible. Unfortunately, the # offset is only valid for single-line text. For multi-line text, # it is apparently not possible to determine at what offset it # started if '\n' in data: lines = data.splitlines() lineno = pos[1] - len(lines) + 1 offset = -1 else: lineno = pos[1] offset = pos[2] - len(data) pos = (pos[0], lineno, offset) self._queue.append((kind, data, pos)) def _getpos_unknown(self): return (self.filename, -1, -1) def _getpos(self): return (self.filename, self.expat.CurrentLineNumber, self.expat.CurrentColumnNumber) def _handle_start(self, tag, attrib): attrs = Attrs([(QName(name), value) for name, value in zip(*[iter(attrib)] * 2)]) self._enqueue(START, (QName(tag), attrs)) def _handle_end(self, tag): self._enqueue(END, QName(tag)) def _handle_data(self, text): self._enqueue(TEXT, text) def _handle_xml_decl(self, version, encoding, standalone): self._enqueue(XML_DECL, (version, encoding, standalone)) def _handle_doctype(self, name, sysid, pubid, has_internal_subset): self._enqueue(DOCTYPE, (name, pubid, sysid)) def _handle_start_ns(self, prefix, uri): self._enqueue(START_NS, (prefix or '', uri)) def _handle_end_ns(self, prefix): self._enqueue(END_NS, prefix or '') def _handle_start_cdata(self): self._enqueue(START_CDATA) def _handle_end_cdata(self): self._enqueue(END_CDATA) def _handle_pi(self, target, data): self._enqueue(PI, (target, data)) def _handle_comment(self, text): self._enqueue(COMMENT, text) def _handle_other(self, text): if text.startswith('&'): # deal with undefined entities try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) self._enqueue(TEXT, text) except KeyError: filename, lineno, offset = self._getpos() error = expat.error('undefined entity "%s": line %d, column %d' % (text, lineno, offset)) error.code = expat.errors.XML_ERROR_UNDEFINED_ENTITY error.lineno = lineno error.offset = offset raise error def XML(text): """Parse the given XML source and return a markup stream. Unlike with `XMLParser`, the returned stream is reusable, meaning it can be iterated over multiple times: >>> xml = XML('FooBar') >>> print xml FooBar >>> print xml.select('elem') FooBar >>> print xml.select('elem/text()') FooBar :param text: the XML source :return: the parsed XML event stream :raises ParseError: if the XML text is not well-formed """ return Stream(list(XMLParser(StringIO(text)))) class HTMLParser(html.HTMLParser, object): """Parser for HTML input based on the Python `HTMLParser` module. This class provides the same interface for generating stream events as `XMLParser`, and attempts to automatically balance tags. The parsing is initiated by iterating over the parser object: >>> parser = HTMLParser(StringIO('')) >>> for kind, data, pos in parser: ... print kind, data START (QName(u'ul'), Attrs([(QName(u'compact'), u'compact')])) START (QName(u'li'), Attrs()) TEXT Foo END li END ul """ _EMPTY_ELEMS = frozenset(['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param']) def __init__(self, source, filename=None, encoding='utf-8'): """Initialize the parser for the given HTML input. :param source: the HTML text as a file-like object :param filename: the name of the file, if known :param filename: encoding of the file; ignored if the input is unicode """ html.HTMLParser.__init__(self) self.source = source self.filename = filename self.encoding = encoding self._queue = [] self._open_tags = [] def parse(self): """Generator that parses the HTML source, yielding markup events. :return: a markup event stream :raises ParseError: if the HTML text is not well formed """ def _generate(): try: bufsize = 4 * 1024 # 4K done = False while 1: while not done and len(self._queue) == 0: data = self.source.read(bufsize) if data == '': # end of data self.close() done = True else: self.feed(data) for kind, data, pos in self._queue: yield kind, data, pos self._queue = [] if done: open_tags = self._open_tags open_tags.reverse() for tag in open_tags: yield END, QName(tag), pos break except html.HTMLParseError, e: msg = '%s: line %d, column %d' % (e.msg, e.lineno, e.offset) raise ParseError(msg, self.filename, e.lineno, e.offset) return Stream(_generate()).filter(_coalesce) def __iter__(self): return iter(self.parse()) def _enqueue(self, kind, data, pos=None): if pos is None: pos = self._getpos() self._queue.append((kind, data, pos)) def _getpos(self): lineno, column = self.getpos() return (self.filename, lineno, column) def handle_starttag(self, tag, attrib): fixed_attrib = [] for name, value in attrib: # Fixup minimized attributes if value is None: value = unicode(name) elif not isinstance(value, unicode): value = value.decode(self.encoding, 'replace') fixed_attrib.append((QName(name), stripentities(value))) self._enqueue(START, (QName(tag), Attrs(fixed_attrib))) if tag in self._EMPTY_ELEMS: self._enqueue(END, QName(tag)) else: self._open_tags.append(tag) def handle_endtag(self, tag): if tag not in self._EMPTY_ELEMS: while self._open_tags: open_tag = self._open_tags.pop() self._enqueue(END, QName(open_tag)) if open_tag.lower() == tag.lower(): break def handle_data(self, text): if not isinstance(text, unicode): text = text.decode(self.encoding, 'replace') self._enqueue(TEXT, text) def handle_charref(self, name): if name.lower().startswith('x'): text = unichr(int(name[1:], 16)) else: text = unichr(int(name)) self._enqueue(TEXT, text) def handle_entityref(self, name): try: text = unichr(htmlentitydefs.name2codepoint[name]) except KeyError: text = '&%s;' % name self._enqueue(TEXT, text) def handle_pi(self, data): target, data = data.split(None, 1) if data.endswith('?'): data = data[:-1] self._enqueue(PI, (target.strip(), data.strip())) def handle_comment(self, text): self._enqueue(COMMENT, text) def HTML(text, encoding='utf-8'): """Parse the given HTML source and return a markup stream. Unlike with `HTMLParser`, the returned stream is reusable, meaning it can be iterated over multiple times: >>> html = HTML('

Foo

') >>> print html

Foo

>>> print html.select('h1')

Foo

>>> print html.select('h1/text()') Foo :param text: the HTML source :return: the parsed XML event stream :raises ParseError: if the HTML text is not well-formed, and error recovery fails """ return Stream(list(HTMLParser(StringIO(text), encoding=encoding))) def _coalesce(stream): """Coalesces adjacent TEXT events into a single event.""" textbuf = [] textpos = None for kind, data, pos in chain(stream, [(None, None, None)]): if kind is TEXT: textbuf.append(data) if textpos is None: textpos = pos else: if textbuf: yield TEXT, u''.join(textbuf), textpos del textbuf[:] textpos = None if kind: yield kind, data, pos PKbv7AKDDgenshi/util.py# -*- coding: utf-8 -*- # # Copyright (C) 2006-2007 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://genshi.edgewall.org/wiki/License. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://genshi.edgewall.org/log/. """Various utility classes and functions.""" import htmlentitydefs import re try: set except NameError: from sets import ImmutableSet as frozenset from sets import Set as set __docformat__ = 'restructuredtext en' class LRUCache(dict): """A dictionary-like object that stores only a certain number of items, and discards its least recently used item when full. >>> cache = LRUCache(3) >>> cache['A'] = 0 >>> cache['B'] = 1 >>> cache['C'] = 2 >>> len(cache) 3 >>> cache['A'] 0 Adding new items to the cache does not increase its size. Instead, the least recently used item is dropped: >>> cache['D'] = 3 >>> len(cache) 3 >>> 'B' in cache False Iterating over the cache returns the keys, starting with the most recently used: >>> for key in cache: ... print key D A C This code is based on the LRUCache class from ``myghtyutils.util``, written by Mike Bayer and released under the MIT license. See: http://svn.myghty.org/myghtyutils/trunk/lib/myghtyutils/util.py """ class _Item(object): def __init__(self, key, value): self.previous = self.next = None self.key = key self.value = value def __repr__(self): return repr(self.value) def __init__(self, capacity): self._dict = dict() self.capacity = capacity self.head = None self.tail = None def __contains__(self, key): return key in self._dict def __iter__(self): cur = self.head while cur: yield cur.key cur = cur.next def __len__(self): return len(self._dict) def __getitem__(self, key): item = self._dict[key] self._update_item(item) return item.value def __setitem__(self, key, value): item = self._dict.get(key) if item is None: item = self._Item(key, value) self._dict[key] = item self._insert_item(item) else: item.value = value self._update_item(item) self._manage_size() def __repr__(self): return repr(self._dict) def _insert_item(self, item): item.previous = None item.next = self.head if self.head is not None: self.head.previous = item else: self.tail = item self.head = item self._manage_size() def _manage_size(self): while len(self._dict) > self.capacity: olditem = self._dict[self.tail.key] del self._dict[self.tail.key] if self.tail != self.head: self.tail = self.tail.previous self.tail.next = None else: self.head = self.tail = None def _update_item(self, item): if self.head == item: return previous = item.previous previous.next = item.next if item.next is not None: item.next.previous = previous else: self.tail = previous item.previous = None item.next = self.head self.head.previous = self.head = item def flatten(items): """Flattens a potentially nested sequence into a flat list. :param items: the sequence to flatten >>> flatten((1, 2)) [1, 2] >>> flatten([1, (2, 3), 4]) [1, 2, 3, 4] >>> flatten([1, (2, [3, 4]), 5]) [1, 2, 3, 4, 5] """ retval = [] for item in items: if isinstance(item, (frozenset, list, set, tuple)): retval += flatten(item) else: retval.append(item) return retval def plaintext(text, keeplinebreaks=True): """Returns the text as a `unicode` string with all entities and tags removed. >>> plaintext('1 < 2') u'1 < 2' The `keeplinebreaks` parameter can be set to ``False`` to replace any line breaks by simple spaces: >>> plaintext('''1 ... < ... 2''', keeplinebreaks=False) u'1 < 2' :param text: the text to convert to plain text :param keeplinebreaks: whether line breaks in the text should be kept intact :return: the text with tags and entities removed """ text = stripentities(striptags(text)) if not keeplinebreaks: text = text.replace(u'\n', u' ') return text _STRIPENTITIES_RE = re.compile(r'&(?:#((?:\d+)|(?:[xX][0-9a-fA-F]+));?|(\w+);)') def stripentities(text, keepxmlentities=False): """Return a copy of the given text with any character or numeric entities replaced by the equivalent UTF-8 characters. >>> stripentities('1 < 2') u'1 < 2' >>> stripentities('more …') u'more \u2026' >>> stripentities('…') u'\u2026' >>> stripentities('…') u'\u2026' If the `keepxmlentities` parameter is provided and is a truth value, the core XML entities (&, ', >, < and ") are left intact. >>> stripentities('1 < 2 …', keepxmlentities=True) u'1 < 2 \u2026' """ def _replace_entity(match): if match.group(1): # numeric entity ref = match.group(1) if ref.startswith('x'): ref = int(ref[1:], 16) else: ref = int(ref, 10) return unichr(ref) else: # character entity ref = match.group(2) if keepxmlentities and ref in ('amp', 'apos', 'gt', 'lt', 'quot'): return u'&%s;' % ref try: return unichr(htmlentitydefs.name2codepoint[ref]) except KeyError: if keepxmlentities: return u'&%s;' % ref else: return ref return _STRIPENTITIES_RE.sub(_replace_entity, text) _STRIPTAGS_RE = re.compile(r'(|<[^>]*>)') def striptags(text): """Return a copy of the text with any XML/HTML tags removed. >>> striptags('Foo bar') 'Foo bar' >>> striptags('Foo') 'Foo' >>> striptags('Foo
') 'Foo' HTML/XML comments are stripped, too: >>> striptags('test') 'test' :param text: the string to remove tags from :return: the text with tags removed """ return _STRIPTAGS_RE.sub('', text) PK8>,,genshi/_speedups.pyc; q,uHc@sdatdS(cCsGdk}dk}dk}|itdabb|ittdS(Ns _speedups.so( ssyss pkg_resourcessimpsresource_filenames__name__s__file__s __bootstrap__s __loader__s load_dynamic(s pkg_resourcesssyssimp((s0build/bdist.linux-x86_64/egg/genshi/_speedups.pys __bootstrap__s N(s __bootstrap__(((s0build/bdist.linux-x86_64/egg/genshi/_speedups.pys?s PK8dbwwgenshi/output.pyc; LHc@sdZdklZyeWn ej odklZnXdkZdkl Z l Z l Z l Z l Z lZdklZlZlZlZlZlZlZlZlZlZlZlZdddd d d d gZd ZddedZddZde fdYZ!d e fdYZ"d e"fdYZ#d e#fdYZ$d e fdYZ%de fdYZ&e&i'Z'de fdYZ(de fdYZ)de fdYZ*dS(sUThis module provides different kinds of serialization methods for XML event streams. (schain(s ImmutableSetN(sescapesAttrssMarkups NamespacesQNamesStreamEventKind( sSTARTsENDsTEXTsXML_DECLsDOCTYPEsSTART_NSsEND_NSs START_CDATAs END_CDATAsPIsCOMMENTs XML_NAMESPACEsencodesget_serializersDocTypes XMLSerializersXHTMLSerializersHTMLSerializersTextSerializersrestructuredtext ensxmlsutf-8cstj oAd|djot|t o dnd}n d}|tjo|dit |Snx!|D]}|i ||qWdS(sEncode serializer output into a string. :param iterator: the iterator returned from serializing a stream (basically any iterator that yields unicode objects) :param method: the serialization method; determines how characters not representable in the specified encoding are treated :param encoding: how the output string should be encoded; if set to `None`, this method returns a `unicode` object :param out: a file-like object that the output should be written to instead of being returned as one big string; note that if this is a file or socket (or similar), the `encoding` must not be `None` (that is, the output must be encoded) :return: a `str` or `unicode` object (depending on the `encoding` parameter), or `None` if the `out` parameter is provided :since: version 0.4.1 :note: Changed in 0.5: added the `out` parameter sreplacestextsxmlcharrefreplacecs|iS(N(sstringsencodesencodingserrors(sstring(serrorssencoding(s-build/bdist.linux-x86_64/egg/genshi/output.pys8scCs|S(N(sstring(sstring((s-build/bdist.linux-x86_64/egg/genshi/output.pys:suN( sencodingsNoneserrorssmethods isinstancesTextSerializers_encodesoutsjoinslistsiteratorschunkswrite(siteratorsmethodsencodingsoutserrorsschunks_encode((sencodingserrorss-build/bdist.linux-x86_64/egg/genshi/output.pysencode!s    cKsVt|to8hdt<dt<dt<dt<|i}n||SdS(sReturn a serializer object for the given method. :param method: the serialization method; can be either "xml", "xhtml", "html", "text", or a custom serializer class Any additional keyword arguments are passed to the serializer, and thus depend on the `method` parameter value. :see: `XMLSerializer`, `XHTMLSerializer`, `HTMLSerializer`, `TextSerializer` :since: version 0.4.1 sxmlsxhtmlshtmlstextN( s isinstancesmethods basestrings XMLSerializersXHTMLSerializersHTMLSerializersTextSerializerslowerskwargs(smethodskwargs((s-build/bdist.linux-x86_64/egg/genshi/output.pysget_serializer@s 8cBstZdZdddfZdddfZdddfZeZdeefZddd fZ dd d fZ dd d fZ e Z dddfZ dddfZdddfZdddfZeZdZeeZRS(sDDefines a number of commonly used DOCTYPE declarations as constants.shtmls-//W3C//DTD HTML 4.01//ENs%http://www.w3.org/TR/html4/strict.dtds&-//W3C//DTD HTML 4.01 Transitional//ENs$http://www.w3.org/TR/html4/loose.dtds"-//W3C//DTD HTML 4.01 Frameset//ENs'http://www.w3.org/TR/html4/frameset.dtds -//W3C//DTD XHTML 1.0 Strict//ENs1http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtds&-//W3C//DTD XHTML 1.0 Transitional//ENs7http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtds"-//W3C//DTD XHTML 1.0 Frameset//ENs3http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtds-//W3C//DTD XHTML 1.1//ENs,http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtdssvgs-//W3C//DTD SVG 1.1//ENs0http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtds-//W3C//DTD SVG Basic 1.1//ENs6http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtds-//W3C//DTD SVG Tiny 1.1//ENs5http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtdcCshd|i<d|i<dti<dti<d|i<d|i<d|i<d|i <d |i <d |i <d |i <d |i <d |i<d|i>> from genshi.builder import tag >>> elem = tag.div(tag.a(href='foo'), tag.br, tag.hr(noshade=True)) >>> print ''.join(XMLSerializer()(elem.generate()))


cCsqtg|_|o|iit|in|iitd||o|iit |ndS(sInitialize the XML serializer. :param doctype: a ``(name, pubid, sysid)`` tuple that represents the DOCTYPE declaration that should be included at the top of the generated output, or the name of a DOCTYPE as defined in `DocType.get` :param strip_whitespace: whether extraneous whitespace should be stripped from the output :note: Changed in 0.4.2: The `doctype` parameter can now be a string. sprefixesN( sEmptyTagFiltersselfsfilterssstrip_whitespacesappendsWhitespaceFilters_PRESERVE_SPACEsNamespaceFlattenersnamespace_prefixessdoctypesDocTypeInserter(sselfsdoctypesstrip_whitespacesnamespace_prefixes((s-build/bdist.linux-x86_64/egg/genshi/output.pys__init__s ccst}} t}x|iD]} | |}qWx|D]\}}}|t jp |t jo|\}}d|g} x3|D]+\}}| d|dt|dg7} qW| i|t jodpdtdi| Vq7|tjotd|Vq7|tjo#|o|Vqt|d tVq7|tjotd |Vq7|tjo| o|\} }}d | g} |o| id |n|d jo)|odpd}| id|n| idtdi| Vt}q7|tjo| o|\} }}dg} |o| idn|o| idn|o| idn| idtdi| t"t#|Vt} q7|t$jotdVt}q7|t%jotdVt}q7|t&jotd|Vq7q7WdS(Nss>ussquotess s s s s ('sFalses have_decls have_doctypesin_cdatasselfsfilterssfilter_sstreamskindsdataspossSTARTsEMPTYstagsattribsbufsattrsvaluesescapesappendsMarkupsjoinsENDsTEXTsCOMMENTsXML_DECLsversionsencodings standalonesTruesDOCTYPEsnamespubidssysidsfiltersNones START_CDATAs END_CDATAsPI(sselfsstreams have_declsencodingspubidsposssysidstagsdatasversionsfilter_sbufsnames have_doctypeskindsattrs standalonesvaluesattribsin_cdata((s-build/bdist.linux-x86_64/egg/genshi/output.pys__call__sl     #!                  ( s__name__s __module__s__doc__s frozensets_PRESERVE_SPACEsNonesTrues__init__s__call__(((s-build/bdist.linux-x86_64/egg/genshi/output.pys XMLSerializers  cBstZdZeddddddddd d d d d g Zeddddddddddddg ZeededededgZee ee dZ dZ RS( sProduces XHTML text from an event stream. >>> from genshi.builder import tag >>> elem = tag.div(tag.a(href='foo'), tag.br, tag.hr(noshade=True)) >>> print ''.join(XHTMLSerializer()(elem.generate()))


sareasbasesbasefontsbrscolsframeshrsimgsinputsisindexslinksmetasparamsselectedscheckedscompactsdeclaresdefersdisabledsismapsmultiplesnohrefsnoresizesnoshadesnowrapspres http://www.w3.org/1999/xhtml}prestextareas%http://www.w3.org/1999/xhtml}textareacCstt|i|ttg|_|o|ii t |i n|ph}d|d<|ii t d||o|ii t|n||_dS(Nsshttp://www.w3.org/1999/xhtmlsprefixes(ssupersXHTMLSerializersselfs__init__sdoctypesFalsesEmptyTagFiltersfilterssstrip_whitespacesappendsWhitespaceFilters_PRESERVE_SPACEsnamespace_prefixessNamespaceFlattenersDocTypeInserters drop_xml_decl(sselfsdoctypesstrip_whitespacesnamespace_prefixess drop_xml_decl((s-build/bdist.linux-x86_64/egg/genshi/output.pys__init__!s  ccs|i} |i} |i} t}}t}x|i D]} | |}q5Wxu|D]m\}}}|tjp |tjo|\}}d|g}x|D]\}}|| jo |}nL|djo d|jo|dt|dg7}n|djoqn|d|dt|dg7}qW|tjo3|| jo|id qx|id |n|id td i|VqR|tjotd |VqR|tjo#|o|Vqt|dtVqR|tjotd|VqR|tjo| o|\}}}dg}|o|idn|o|idn|o|idn|idtd i|t"t#|Vt$}qR|t%jo | o| o|\} }}d| g}|o|id|n|djo)|odpd}|id|n|idtd i|Vt$}qR|t)jotdVt$}qR|t*jotdVt}qR|t+jotd|VqRqRWdS(Ns s s s (,sselfs_BOOLEAN_ATTRSs boolean_attrss _EMPTY_ELEMSs empty_elemss drop_xml_declsFalses have_decls have_doctypesin_cdatasfilterssfilter_sstreamskindsdataspossSTARTsEMPTYstagsattribsbufsattrsvaluesescapesappendsMarkupsjoinsENDsTEXTsCOMMENTsDOCTYPEsnamespubidssysidsfiltersNonesTruesXML_DECLsversionsencodings standalones START_CDATAs END_CDATAsPI(sselfsstreams have_declsencodingspubidsposssysidstagsdatas drop_xml_declsversionsfilter_s empty_elemss boolean_attrssbufsnames have_doctypeskindsattrs standalonesvaluesattribsin_cdata((s-build/bdist.linux-x86_64/egg/genshi/output.pys__call__.s           #                     ( s__name__s __module__s__doc__s frozensets _EMPTY_ELEMSs_BOOLEAN_ATTRSsQNames_PRESERVE_SPACEsNonesTrues__init__s__call__(((s-build/bdist.linux-x86_64/egg/genshi/output.pysXHTMLSerializer s 300 cBsVtZdZeededededgZeedZdZ RS(s Produces HTML text from an event stream. >>> from genshi.builder import tag >>> elem = tag.div(tag.a(href='foo'), tag.br, tag.hr(noshade=True)) >>> print ''.join(HTMLSerializer()(elem.generate()))


sscripts#http://www.w3.org/1999/xhtml}scriptsstyles"http://www.w3.org/1999/xhtml}stylecCstt|i|ttg|_|o#|ii t |i |i n|ii t dhdd<|o|ii t|ndS(sInitialize the HTML serializer. :param doctype: a ``(name, pubid, sysid)`` tuple that represents the DOCTYPE declaration that should be included at the top of the generated output :param strip_whitespace: whether extraneous whitespace should be stripped from the output sprefixesshttp://www.w3.org/1999/xhtmlsN(ssupersHTMLSerializersselfs__init__sdoctypesFalsesEmptyTagFiltersfilterssstrip_whitespacesappendsWhitespaceFilters_PRESERVE_SPACEs_NOESCAPE_ELEMSsNamespaceFlattenersDocTypeInserter(sselfsdoctypesstrip_whitespace((s-build/bdist.linux-x86_64/egg/genshi/output.pys__init__s"ccs|i} |i} |i}t} t}x|i D]}||}q1Wx|D]\}}}|tjp |tjoA|\}}d|g} x|D]\}}|| jo|o| d|g7} qFqd|jo;|djo d|jo| dt|dg7} qFq|djo#| d|d t|dg7} qqW| id |tjo&|| jo| id |qntd i| V||jo t}qqN|tjotd |Vt}qN|tjo#|o|Vqt|d tVqN|tjotd|VqN|tjo| o|\} }}dg} |o| idn|o| idn|o| idn| idtd i| t#t$|Vt} qN|t%jotd|VqNqNWdS(Ns s (&sselfs_BOOLEAN_ATTRSs boolean_attrss _EMPTY_ELEMSs empty_elemss_NOESCAPE_ELEMSsnoescape_elemssFalses have_doctypesnoescapesfilterssfilter_sstreamskindsdataspossSTARTsEMPTYstagsattribsbufsattrsvaluesescapesappendsMarkupsjoinsTruesENDsTEXTsCOMMENTsDOCTYPEsnamespubidssysidsfiltersNonesPI(sselfsstreamspubidsposssysidstagsnoescape_elemssdatasfilter_s empty_elemss boolean_attrssbufsnames have_doctypeskindsattrsnoescapesvaluesattrib((s-build/bdist.linux-x86_64/egg/genshi/output.pys__call__sj         ! '             ( s__name__s __module__s__doc__s frozensetsQNames_NOESCAPE_ELEMSsNonesTrues__init__s__call__(((s-build/bdist.linux-x86_64/egg/genshi/output.pysHTMLSerializer~s 0cBs#tZdZedZdZRS(sProduces plain text from an event stream. Only text events are included in the output. Unlike the other serializer, special XML characters are not escaped: >>> from genshi.builder import tag >>> elem = tag.div(tag.a('', href='foo'), tag.br) >>> print elem >>> print ''.join(TextSerializer()(elem.generate())) If text events contain literal markup (instances of the `Markup` class), that markup is by default passed through unchanged: >>> elem = tag.div(Markup('Hello & Bye!
')) >>> print elem.generate().render(TextSerializer) Hello & Bye!
You can use the ``strip_markup`` to change this behavior, so that tags and entities are stripped from the output (or in the case of entities, replaced with the equivalent character): >>> print elem.generate().render(TextSerializer, strip_markup=True) Hello & Bye! cCs ||_dS(sCreate the serializer. :param strip_markup: whether markup (tags and encoded characters) found in the text should be removed N(s strip_markupsself(sselfs strip_markup((s-build/bdist.linux-x86_64/egg/genshi/output.pys__init__sccsw|i}xg|D]_}|dtjoH|d}|ot|tjo|ii }nt |VqqWdS(Nii( sselfs strip_markupsstreamseventsTEXTsdatastypesMarkups striptagss stripentitiessunicode(sselfsstreams strip_markupsdatasevent((s-build/bdist.linux-x86_64/egg/genshi/output.pys__call__s  (s__name__s __module__s__doc__sFalses__init__s__call__(((s-build/bdist.linux-x86_64/egg/genshi/output.pysTextSerializers  sEmptyTagFiltercBs#tZdZedZdZRS(scCombines `START` and `STOP` events into `EMPTY` events for elements that have no contents. sEMPTYccstttf}xy|D]q}|dtjo;|dtjo"t|d|df}|Vqqh|Vn|dtj o|Vn|}qWdS(Niii(sNonesprevsstreamsevsSTARTsENDsEMPTY(sselfsstreamsevsprev((s-build/bdist.linux-x86_64/egg/genshi/output.pys__call__s(s__name__s __module__s__doc__sStreamEventKindsEMPTYs__call__(((s-build/bdist.linux-x86_64/egg/genshi/output.pysEmptyTagFilter s  sNamespaceFlattenercBs#tZdZedZdZRS(siOutput stream filter that removes namespace information from the stream, instead adding namespace attributes and prefixes as needed. :param prefixes: optional mapping of namespace URIs to prefixes >>> from genshi.input import XML >>> xml = XML(''' ... ... ''') >>> for kind, data, pos in NamespaceFlattener()(xml): ... print kind, repr(data) START (u'doc', Attrs([(u'xmlns', u'NS1'), (u'xmlns:two', u'NS2')])) TEXT u'\n ' START (u'two:item', Attrs()) END u'two:item' TEXT u'\n' END u'doc' cCs:htid<|_|tj o|ii|ndS(Nsxml(s XML_NAMESPACEsurisselfsprefixessNonesupdate(sselfsprefixes((s-build/bdist.linux-x86_64/egg/genshi/output.pys__init__8s c#stgi}|iiD]\}}|||gfq~hti dg<d} g}|i} d}d}|i}x0|D](\}}}|tjp |tjoV|\}}|i}|i}|o[|jo-|d}|od||f}qBqF| d|f| d|ng} x|D]\}}|i}|i}|oh|jo.|}| ||| d ||fn|d}|od||f}qn| i||fqSW||t#|| f|fV|2q|t$joW|i}|i}|o-|d}|od||f}qon|||fVq|t%joZ|\}}|jo0i&||gd}| |||n| ||q|t'jo|joi&|} | i)}| o |=n|| jp|| djo+|}|i)| o |=qxn|o1|||}||jo|i+|qqqq|||fVqWdS( Nsxmlcs6i|gi|i|gi|dS(N(s namespacess setdefaultsurisappendsprefixsprefixes(sprefixsuri(sprefixess namespaces(s-build/bdist.linux-x86_64/egg/genshi/output.pys_push_ns@scCs$d|od|pd|fSdS(Nuxmlns%ss:%ss(sprefixsuri(sprefixsuri((s-build/bdist.linux-x86_64/egg/genshi/output.pys _make_ns_attrFsccs+d}xno|d7}d|VqWdS(Niisns%d(sval(sval((s-build/bdist.linux-x86_64/egg/genshi/output.pys _gen_prefixIs  iu%s:%suxmlnsssxmlns:%s(,sdictsappends_[1]sselfsprefixessitemssksvs XML_NAMESPACEsuris namespacess_push_nssns_attrss _push_ns_attrs _make_ns_attrs _gen_prefixsnextsstreamskindsdataspossSTARTsEMPTYstagsattrss localnamestagnames namespacestagnssprefixs new_attrssattrsvaluesattrnamesattrnssAttrssENDsSTART_NSsgetsEND_NSsurisspops uri_prefixessremove(sselfsstreams _make_ns_attrspossurisprefixstagsattrss uri_prefixess_push_nssprefixess _push_ns_attrsuriss new_attrssattrnames namespacessdatasattrskinds _gen_prefixskstagnssattrnssvalues_[1]sns_attrsstagnamesv((sprefixess namespacess-build/bdist.linux-x86_64/egg/genshi/output.pys__call__=sE                           (s__name__s __module__s__doc__sNones__init__s__call__(((s-build/bdist.linux-x86_64/egg/genshi/output.pysNamespaceFlattener$s  sWhitespaceFiltercBsNtZdZeedZeedeidieididZ RS(sPA filter that removes extraneous ignorable white space from the stream. cCsP|tjo g}nt||_|tjo g}nt||_dS(sInitialize the filter. :param preserve: a set or sequence of tag names for which white-space should be preserved :param noescape: a set or sequence of tag names for which text content should not be escaped The `noescape` set is expected to refer to elements that cannot contain further child elements (such as ``