code
stringlengths
1
1.72M
language
stringclasses
1 value
# $Id: parts.py 6073 2009-08-06 12:21:10Z milde $ # Authors: David Goodger <goodger@python.org>; Ueli Schlaepfer; Dmitry Jemerov # Copyright: This module has been placed in the public domain. """ Transforms related to document parts. """ __docformat__ = 'reStructuredText' import re import sys from docutils import nodes, utils from docutils.transforms import TransformError, Transform class SectNum(Transform): """ Automatically assigns numbers to the titles of document sections. It is possible to limit the maximum section level for which the numbers are added. For those sections that are auto-numbered, the "autonum" attribute is set, informing the contents table generator that a different form of the TOC should be used. """ default_priority = 710 """Should be applied before `Contents`.""" def apply(self): self.maxdepth = self.startnode.details.get('depth', None) self.startvalue = self.startnode.details.get('start', 1) self.prefix = self.startnode.details.get('prefix', '') self.suffix = self.startnode.details.get('suffix', '') self.startnode.parent.remove(self.startnode) if self.document.settings.sectnum_xform: if self.maxdepth is None: self.maxdepth = sys.maxint self.update_section_numbers(self.document) else: # store details for eventual section numbering by the writer self.document.settings.sectnum_depth = self.maxdepth self.document.settings.sectnum_start = self.startvalue self.document.settings.sectnum_prefix = self.prefix self.document.settings.sectnum_suffix = self.suffix def update_section_numbers(self, node, prefix=(), depth=0): depth += 1 if prefix: sectnum = 1 else: sectnum = self.startvalue for child in node: if isinstance(child, nodes.section): numbers = prefix + (str(sectnum),) title = child[0] # Use &nbsp; for spacing: generated = nodes.generated( '', (self.prefix + '.'.join(numbers) + self.suffix + u'\u00a0' * 3), classes=['sectnum']) title.insert(0, generated) title['auto'] = 1 if depth < self.maxdepth: self.update_section_numbers(child, numbers, depth) sectnum += 1 class Contents(Transform): """ This transform generates a table of contents from the entire document tree or from a single branch. It locates "section" elements and builds them into a nested bullet list, which is placed within a "topic" created by the contents directive. A title is either explicitly specified, taken from the appropriate language module, or omitted (local table of contents). The depth may be specified. Two-way references between the table of contents and section titles are generated (requires Writer support). This transform requires a startnode, which contains generation options and provides the location for the generated table of contents (the startnode is replaced by the table of contents "topic"). """ default_priority = 720 def apply(self): try: # let the writer (or output software) build the contents list? toc_by_writer = self.document.settings.use_latex_toc except AttributeError: toc_by_writer = False details = self.startnode.details if 'local' in details: startnode = self.startnode.parent.parent while not (isinstance(startnode, nodes.section) or isinstance(startnode, nodes.document)): # find the ToC root: a direct ancestor of startnode startnode = startnode.parent else: startnode = self.document self.toc_id = self.startnode.parent['ids'][0] if 'backlinks' in details: self.backlinks = details['backlinks'] else: self.backlinks = self.document.settings.toc_backlinks if toc_by_writer: # move customization settings to the parent node self.startnode.parent.attributes.update(details) self.startnode.parent.remove(self.startnode) else: contents = self.build_contents(startnode) if len(contents): self.startnode.replace_self(contents) else: self.startnode.parent.parent.remove(self.startnode.parent) def build_contents(self, node, level=0): level += 1 sections = [sect for sect in node if isinstance(sect, nodes.section)] entries = [] autonum = 0 depth = self.startnode.details.get('depth', sys.maxint) for section in sections: title = section[0] auto = title.get('auto') # May be set by SectNum. entrytext = self.copy_and_filter(title) reference = nodes.reference('', '', refid=section['ids'][0], *entrytext) ref_id = self.document.set_id(reference) entry = nodes.paragraph('', '', reference) item = nodes.list_item('', entry) if ( self.backlinks in ('entry', 'top') and title.next_node(nodes.reference) is None): if self.backlinks == 'entry': title['refid'] = ref_id elif self.backlinks == 'top': title['refid'] = self.toc_id if level < depth: subsects = self.build_contents(section, level) item += subsects entries.append(item) if entries: contents = nodes.bullet_list('', *entries) if auto: contents['classes'].append('auto-toc') return contents else: return [] def copy_and_filter(self, node): """Return a copy of a title, with references, images, etc. removed.""" visitor = ContentsFilter(self.document) node.walkabout(visitor) return visitor.get_entry_text() class ContentsFilter(nodes.TreeCopyVisitor): def get_entry_text(self): return self.get_tree_copy().children def visit_citation_reference(self, node): raise nodes.SkipNode def visit_footnote_reference(self, node): raise nodes.SkipNode def visit_image(self, node): if node.hasattr('alt'): self.parent.append(nodes.Text(node['alt'])) raise nodes.SkipNode def ignore_node_but_process_children(self, node): raise nodes.SkipDeparture visit_interpreted = ignore_node_but_process_children visit_problematic = ignore_node_but_process_children visit_reference = ignore_node_but_process_children visit_target = ignore_node_but_process_children
Python
# $Id: universal.py 6112 2009-09-03 07:27:59Z milde $ # Authors: David Goodger <goodger@python.org>; Ueli Schlaepfer # Copyright: This module has been placed in the public domain. """ Transforms needed by most or all documents: - `Decorations`: Generate a document's header & footer. - `Messages`: Placement of system messages stored in `nodes.document.transform_messages`. - `TestMessages`: Like `Messages`, used on test runs. - `FinalReferences`: Resolve remaining references. """ __docformat__ = 'reStructuredText' import re import sys import time from docutils import nodes, utils from docutils.transforms import TransformError, Transform class Decorations(Transform): """ Populate a document's decoration element (header, footer). """ default_priority = 820 def apply(self): header_nodes = self.generate_header() if header_nodes: decoration = self.document.get_decoration() header = decoration.get_header() header.extend(header_nodes) footer_nodes = self.generate_footer() if footer_nodes: decoration = self.document.get_decoration() footer = decoration.get_footer() footer.extend(footer_nodes) def generate_header(self): return None def generate_footer(self): # @@@ Text is hard-coded for now. # Should be made dynamic (language-dependent). settings = self.document.settings if settings.generator or settings.datestamp or settings.source_link \ or settings.source_url: text = [] if settings.source_link and settings._source \ or settings.source_url: if settings.source_url: source = settings.source_url else: source = utils.relative_path(settings._destination, settings._source) text.extend([ nodes.reference('', 'View document source', refuri=source), nodes.Text('.\n')]) if settings.datestamp: datestamp = time.strftime(settings.datestamp, time.gmtime()) text.append(nodes.Text('Generated on: ' + datestamp + '.\n')) if settings.generator: text.extend([ nodes.Text('Generated by '), nodes.reference('', 'Docutils', refuri= 'http://docutils.sourceforge.net/'), nodes.Text(' from '), nodes.reference('', 'reStructuredText', refuri='http://' 'docutils.sourceforge.net/rst.html'), nodes.Text(' source.\n')]) return [nodes.paragraph('', '', *text)] else: return None class ExposeInternals(Transform): """ Expose internal attributes if ``expose_internals`` setting is set. """ default_priority = 840 def not_Text(self, node): return not isinstance(node, nodes.Text) def apply(self): if self.document.settings.expose_internals: for node in self.document.traverse(self.not_Text): for att in self.document.settings.expose_internals: value = getattr(node, att, None) if value is not None: node['internal:' + att] = value class Messages(Transform): """ Place any system messages generated after parsing into a dedicated section of the document. """ default_priority = 860 def apply(self): unfiltered = self.document.transform_messages threshold = self.document.reporter.report_level messages = [] for msg in unfiltered: if msg['level'] >= threshold and not msg.parent: messages.append(msg) if messages: section = nodes.section(classes=['system-messages']) # @@@ get this from the language module? section += nodes.title('', 'Docutils System Messages') section += messages self.document.transform_messages[:] = [] self.document += section class FilterMessages(Transform): """ Remove system messages below verbosity threshold. """ default_priority = 870 def apply(self): for node in self.document.traverse(nodes.system_message): if node['level'] < self.document.reporter.report_level: node.parent.remove(node) class TestMessages(Transform): """ Append all post-parse system messages to the end of the document. Used for testing purposes. """ default_priority = 880 def apply(self): for msg in self.document.transform_messages: if not msg.parent: self.document += msg class StripComments(Transform): """ Remove comment elements from the document tree (only if the ``strip_comments`` setting is enabled). """ default_priority = 740 def apply(self): if self.document.settings.strip_comments: for node in self.document.traverse(nodes.comment): node.parent.remove(node) class StripClassesAndElements(Transform): """ Remove from the document tree all elements with classes in `self.document.settings.strip_elements_with_classes` and all "classes" attribute values in `self.document.settings.strip_classes`. """ default_priority = 420 def apply(self): if not (self.document.settings.strip_elements_with_classes or self.document.settings.strip_classes): return # prepare dicts for lookup (not sets, for Python 2.2 compatibility): self.strip_elements = dict( [(key, None) for key in (self.document.settings.strip_elements_with_classes or [])]) self.strip_classes = dict( [(key, None) for key in (self.document.settings.strip_classes or [])]) for node in self.document.traverse(self.check_classes): node.parent.remove(node) def check_classes(self, node): if isinstance(node, nodes.Element): for class_value in node['classes'][:]: if class_value in self.strip_classes: node['classes'].remove(class_value) if class_value in self.strip_elements: return 1
Python
# $Id: writer_aux.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Auxiliary transforms mainly to be used by Writer components. This module is called "writer_aux" because otherwise there would be conflicting imports like this one:: from docutils import writers from docutils.transforms import writers """ __docformat__ = 'reStructuredText' from docutils import nodes, utils, languages from docutils.transforms import Transform class Compound(Transform): """ Flatten all compound paragraphs. For example, transform :: <compound> <paragraph> <literal_block> <paragraph> into :: <paragraph> <literal_block classes="continued"> <paragraph classes="continued"> """ default_priority = 910 def apply(self): for compound in self.document.traverse(nodes.compound): first_child = 1 for child in compound: if first_child: if not isinstance(child, nodes.Invisible): first_child = 0 else: child['classes'].append('continued') # Substitute children for compound. compound.replace_self(compound[:]) class Admonitions(Transform): """ Transform specific admonitions, like this: <note> <paragraph> Note contents ... into generic admonitions, like this:: <admonition classes="note"> <title> Note <paragraph> Note contents ... The admonition title is localized. """ default_priority = 920 def apply(self): lcode = self.document.settings.language_code language = languages.get_language(lcode) for node in self.document.traverse(nodes.Admonition): node_name = node.__class__.__name__ # Set class, so that we know what node this admonition came from. node['classes'].append(node_name) if not isinstance(node, nodes.admonition): # Specific admonition. Transform into a generic admonition. admonition = nodes.admonition(node.rawsource, *node.children, **node.attributes) title = nodes.title('', language.labels[node_name]) admonition.insert(0, title) node.replace_self(admonition)
Python
# $Id: references.py 6167 2009-10-11 14:51:42Z grubert $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Transforms for resolving references. """ __docformat__ = 'reStructuredText' import sys import re from docutils import nodes, utils from docutils.transforms import TransformError, Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.traverse(nodes.target): # Only block-level targets without reference (like ".. target:"): if (isinstance(target.parent, nodes.TextElement) or (target.hasattr('refid') or target.hasattr('refuri') or target.hasattr('refname'))): continue assert len(target) == 0, 'error: block-level target has children' next_node = target.next_node(ascend=1) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while 1: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if 'refid' in target: del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if target['refname'] in self.document.nameids: self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in utils.uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.traverse(nodes.target): if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.traverse(nodes.target): if not target.hasattr('refuri') and not target.hasattr('refid'): self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ for name in target['names']: refid = self.document.nameids[name] reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star u'\u2020', # dagger &dagger; u'\u2021', # double dagger &Dagger; u'\u00A7', # section mark &sect; u'\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. u'\u2660', # spade suit &spades; u'\u2665', # heart suit &hearts; u'\u2666', # diamond suit &diams; u'\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while 1: label = str(startnum) startnum += 1 if label not in self.document.nameids: break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if label in self.document.footnote_refs: reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if label in self.document.citation_refs: reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class CircularSubstitutionDefinitionError(Exception): pass class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.traverse(nodes.substitution_reference) nested = {} for ref in subreflist: refname = ref['refname'] key = None if refname in defs: key = refname else: normed_name = refname.lower() if normed_name in normed: key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if ('ltrim' in subdef.attributes or 'trim' in subdef.attributes): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if ('rtrim' in subdef.attributes or 'trim' in subdef.attributes): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) subdef_copy = subdef.deepcopy() try: # Take care of nested substitution references: for nested_ref in subdef_copy.traverse( nodes.substitution_reference): nested_name = normed[nested_ref['refname'].lower()] if nested_name in nested.setdefault(nested_name, []): raise CircularSubstitutionDefinitionError else: nested[nested_name].append(key) subreflist.append(nested_ref) except CircularSubstitutionDefinitionError: parent = ref.parent if isinstance(parent, nodes.substitution_definition): msg = self.document.reporter.error( 'Circular substitution definition detected:', nodes.literal_block(parent.rawsource, parent.rawsource), line=parent.line, base_node=parent) parent.replace_self(msg) else: msg = self.document.reporter.error( 'Circular substitution definition referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: ref.replace_self(subdef_copy.children) # register refname of the replacment node(s) # (needed for resolution of references) for node in subdef_copy.children: if isinstance(node, nodes.Referential): # HACK: verify refname attribute exists. # Test with docs/dev/todo.txt, see. |donate| if 'refname' in node: self.document.note_refname(node) class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def __init__(self, document, startnode): Transform.__init__(self, document, startnode=startnode) self.classes = startnode.details.get('class', []) def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if target['refuri'] not in notes: notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if ref['refuri'] not in notes: notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist) def make_target_footnote(self, refuri, refs, notes): if refuri in notes: # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference( refname=footnote_name, auto=1) refnode['classes'] += self.classes self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): if self.classes: reflist.insert(0, nodes.inline(text=' ', Classes=self.classes)) else: reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote class DanglingReferences(Transform): """ Check for dangling references (incl. footnote & citation) and for unreferenced targets. """ default_priority = 850 def apply(self): visitor = DanglingReferencesVisitor( self.document, self.document.transformer.unknown_reference_resolvers) self.document.walk(visitor) # *After* resolving all references, check for unreferenced # targets: for target in self.document.traverse(nodes.target): if not target.referenced: if target.get('anonymous'): # If we have unreferenced anonymous targets, there # is already an error message about anonymous # hyperlink mismatch; no need to generate another # message. continue if target['names']: naming = target['names'][0] elif target['ids']: naming = target['ids'][0] else: # Hack: Propagated targets always have their refid # attribute set. naming = target['refid'] self.document.reporter.info( 'Hyperlink target "%s" is not referenced.' % naming, base_node=target) class DanglingReferencesVisitor(nodes.SparseNodeVisitor): def __init__(self, document, unknown_reference_resolvers): nodes.SparseNodeVisitor.__init__(self, document) self.document = document self.unknown_reference_resolvers = unknown_reference_resolvers def unknown_visit(self, node): pass def visit_reference(self, node): if node.resolved or not node.hasattr('refname'): return refname = node['refname'] id = self.document.nameids.get(refname) if id is None: for resolver_function in self.unknown_reference_resolvers: if resolver_function(node): break else: if refname in self.document.nameids: msg = self.document.reporter.error( 'Duplicate target name, cannot be used as a unique ' 'reference: "%s".' % (node['refname']), base_node=node) else: msg = self.document.reporter.error( 'Unknown target name: "%s".' % (node['refname']), base_node=node) msgid = self.document.set_id(msg) prb = nodes.problematic( node.rawsource, node.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) node.replace_self(prb) else: del node['refname'] node['refid'] = id self.document.ids[id].note_referenced_by(id=id) node.resolved = 1 visit_footnote_reference = visit_citation_reference = visit_reference
Python
# $Id: peps.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils, languages from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d' pep_cvs_url = ('http://svn.python.org/view/*checkout*' '/peps/trunk/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.replace_self(mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
Python
# $Id: components.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Docutils component-related transforms. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError class Filter(Transform): """ Include or exclude elements which depend on a specific Docutils component. For use with `nodes.pending` elements. A "pending" element's dictionary attribute ``details`` must contain the keys "component" and "format". The value of ``details['component']`` must match the type name of the component the elements depend on (e.g. "writer"). The value of ``details['format']`` is the name of a specific format or context of that component (e.g. "html"). If the matching Docutils component supports that format or context, the "pending" element is replaced by the contents of ``details['nodes']`` (a list of nodes); otherwise, the "pending" element is removed. For example, the reStructuredText "meta" directive creates a "pending" element containing a "meta" element (in ``pending.details['nodes']``). Only writers (``pending.details['component'] == 'writer'``) supporting the "html" format (``pending.details['format'] == 'html'``) will include the "meta" element; it will be deleted from the output of all other writers. """ default_priority = 780 def apply(self): pending = self.startnode component_type = pending.details['component'] # 'reader' or 'writer' format = pending.details['format'] component = self.document.transformer.components[component_type] if component.supports(format): pending.replace_self(pending.details['nodes']) else: pending.parent.remove(pending)
Python
# $Id: __init__.py 4975 2007-03-01 18:08:32Z wiemann $ # Authors: David Goodger <goodger@python.org>; Ueli Schlaepfer # Copyright: This module has been placed in the public domain. """ This package contains modules for standard tree transforms available to Docutils components. Tree transforms serve a variety of purposes: - To tie up certain syntax-specific "loose ends" that remain after the initial parsing of the input plaintext. These transforms are used to supplement a limited syntax. - To automate the internal linking of the document tree (hyperlink references, footnote references, etc.). - To extract useful information from the document tree. These transforms may be used to construct (for example) indexes and tables of contents. Each transform is an optional step that a Docutils component may choose to perform on the parsed document. """ __docformat__ = 'reStructuredText' from docutils import languages, ApplicationError, TransformSpec class TransformError(ApplicationError): pass class Transform: """ Docutils transform component abstract base class. """ default_priority = None """Numerical priority of this transform, 0 through 999 (override).""" def __init__(self, document, startnode=None): """ Initial setup for in-place document transforms. """ self.document = document """The document tree to transform.""" self.startnode = startnode """Node from which to begin the transform. For many transforms which apply to the document as a whole, `startnode` is not set (i.e. its value is `None`).""" self.language = languages.get_language( document.settings.language_code) """Language module local to this document.""" def apply(self, **kwargs): """Override to apply the transform to the document tree.""" raise NotImplementedError('subclass must override this method') class Transformer(TransformSpec): """ Stores transforms (`Transform` classes) and applies them to document trees. Also keeps track of components by component type name. """ def __init__(self, document): self.transforms = [] """List of transforms to apply. Each item is a 3-tuple: ``(priority string, transform class, pending node or None)``.""" self.unknown_reference_resolvers = [] """List of hook functions which assist in resolving references""" self.document = document """The `nodes.document` object this Transformer is attached to.""" self.applied = [] """Transforms already applied, in order.""" self.sorted = 0 """Boolean: is `self.tranforms` sorted?""" self.components = {} """Mapping of component type name to component object. Set by `self.populate_from_components()`.""" self.serialno = 0 """Internal serial number to keep track of the add order of transforms.""" def add_transform(self, transform_class, priority=None, **kwargs): """ Store a single transform. Use `priority` to override the default. `kwargs` is a dictionary whose contents are passed as keyword arguments to the `apply` method of the transform. This can be used to pass application-specific data to the transform instance. """ if priority is None: priority = transform_class.default_priority priority_string = self.get_priority_string(priority) self.transforms.append( (priority_string, transform_class, None, kwargs)) self.sorted = 0 def add_transforms(self, transform_list): """Store multiple transforms, with default priorities.""" for transform_class in transform_list: priority_string = self.get_priority_string( transform_class.default_priority) self.transforms.append( (priority_string, transform_class, None, {})) self.sorted = 0 def add_pending(self, pending, priority=None): """Store a transform with an associated `pending` node.""" transform_class = pending.transform if priority is None: priority = transform_class.default_priority priority_string = self.get_priority_string(priority) self.transforms.append( (priority_string, transform_class, pending, {})) self.sorted = 0 def get_priority_string(self, priority): """ Return a string, `priority` combined with `self.serialno`. This ensures FIFO order on transforms with identical priority. """ self.serialno += 1 return '%03d-%03d' % (priority, self.serialno) def populate_from_components(self, components): """ Store each component's default transforms, with default priorities. Also, store components by type name in a mapping for later lookup. """ for component in components: if component is None: continue self.add_transforms(component.get_transforms()) self.components[component.component_type] = component self.sorted = 0 # Set up all of the reference resolvers for this transformer. Each # component of this transformer is able to register its own helper # functions to help resolve references. unknown_reference_resolvers = [] for i in components: unknown_reference_resolvers.extend(i.unknown_reference_resolvers) decorated_list = [(f.priority, f) for f in unknown_reference_resolvers] decorated_list.sort() self.unknown_reference_resolvers.extend([f[1] for f in decorated_list]) def apply_transforms(self): """Apply all of the stored transforms, in priority order.""" self.document.reporter.attach_observer( self.document.note_transform_message) while self.transforms: if not self.sorted: # Unsorted initially, and whenever a transform is added. self.transforms.sort() self.transforms.reverse() self.sorted = 1 priority, transform_class, pending, kwargs = self.transforms.pop() transform = transform_class(self.document, startnode=pending) transform.apply(**kwargs) self.applied.append((priority, transform_class, pending, kwargs))
Python
# $Id: frontmatter.py 5618 2008-07-28 08:37:32Z strank $ # Author: David Goodger, Ueli Schlaepfer <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Transforms related to the front matter of a document or a section (information found before the main text): - `DocTitle`: Used to transform a lone top level section's title to the document title, promote a remaining lone top-level section's title to the document subtitle, and determine the document's title metadata (document['title']) based on the document title and/or the "title" setting. - `SectionSubTitle`: Used to transform a lone subsection into a subtitle. - `DocInfo`: Used to transform a bibliographic field list into docinfo elements. """ __docformat__ = 'reStructuredText' import re from docutils import nodes, utils from docutils.transforms import TransformError, Transform class TitlePromoter(Transform): """ Abstract base class for DocTitle and SectionSubTitle transforms. """ def promote_title(self, node): """ Transform the following tree:: <node> <section> <title> ... into :: <node> <title> ... `node` is normally a document. """ # `node` must not have a title yet. assert not (len(node) and isinstance(node[0], nodes.title)) section, index = self.candidate_index(node) if index is None: return None # Transfer the section's attributes to the node: node.attributes.update(section.attributes) # setup_child is called automatically for all nodes. node[:] = (section[:1] # section title + node[:index] # everything that was in the # node before the section + section[1:]) # everything that was in the section assert isinstance(node[0], nodes.title) return 1 def promote_subtitle(self, node): """ Transform the following node tree:: <node> <title> <section> <title> ... into :: <node> <title> <subtitle> ... """ subsection, index = self.candidate_index(node) if index is None: return None subtitle = nodes.subtitle() # Transfer the subsection's attributes to the new subtitle: # This causes trouble with list attributes! To do: Write a # test case which catches direct access to the `attributes` # dictionary and/or write a test case which shows problems in # this particular case. subtitle.attributes.update(subsection.attributes) # We're losing the subtitle's attributes here! To do: Write a # test case which shows this behavior. # Transfer the contents of the subsection's title to the # subtitle: subtitle[:] = subsection[0][:] node[:] = (node[:1] # title + [subtitle] # everything that was before the section: + node[1:index] # everything that was in the subsection: + subsection[1:]) return 1 def candidate_index(self, node): """ Find and return the promotion candidate and its index. Return (None, None) if no valid candidate was found. """ index = node.first_child_not_matching_class( nodes.PreBibliographic) if index is None or len(node) > (index + 1) or \ not isinstance(node[index], nodes.section): return None, None else: return node[index], index class DocTitle(TitlePromoter): """ In reStructuredText_, there is no way to specify a document title and subtitle explicitly. Instead, we can supply the document title (and possibly the subtitle as well) implicitly, and use this two-step transform to "raise" or "promote" the title(s) (and their corresponding section contents) to the document level. 1. If the document contains a single top-level section as its first non-comment element, the top-level section's title becomes the document's title, and the top-level section's contents become the document's immediate contents. The lone top-level section header must be the first non-comment element in the document. For example, take this input text:: ================= Top-Level Title ================= A paragraph. Once parsed, it looks like this:: <document> <section names="top-level title"> <title> Top-Level Title <paragraph> A paragraph. After running the DocTitle transform, we have:: <document names="top-level title"> <title> Top-Level Title <paragraph> A paragraph. 2. If step 1 successfully determines the document title, we continue by checking for a subtitle. If the lone top-level section itself contains a single second-level section as its first non-comment element, that section's title is promoted to the document's subtitle, and that section's contents become the document's immediate contents. Given this input text:: ================= Top-Level Title ================= Second-Level Title ~~~~~~~~~~~~~~~~~~ A paragraph. After parsing and running the Section Promotion transform, the result is:: <document names="top-level title"> <title> Top-Level Title <subtitle names="second-level title"> Second-Level Title <paragraph> A paragraph. (Note that the implicit hyperlink target generated by the "Second-Level Title" is preserved on the "subtitle" element itself.) Any comment elements occurring before the document title or subtitle are accumulated and inserted as the first body elements after the title(s). This transform also sets the document's metadata title (document['title']). .. _reStructuredText: http://docutils.sf.net/rst.html """ default_priority = 320 def set_metadata(self): """ Set document['title'] metadata title from the following sources, listed in order of priority: * Existing document['title'] attribute. * "title" setting. * Document title node (as promoted by promote_title). """ if not self.document.hasattr('title'): if self.document.settings.title is not None: self.document['title'] = self.document.settings.title elif len(self.document) and isinstance(self.document[0], nodes.title): self.document['title'] = self.document[0].astext() def apply(self): if getattr(self.document.settings, 'doctitle_xform', 1): # promote_(sub)title defined in TitlePromoter base class. if self.promote_title(self.document): # If a title has been promoted, also try to promote a # subtitle. self.promote_subtitle(self.document) # Set document['title']. self.set_metadata() class SectionSubTitle(TitlePromoter): """ This works like document subtitles, but for sections. For example, :: <section> <title> Title <section> <title> Subtitle ... is transformed into :: <section> <title> Title <subtitle> Subtitle ... For details refer to the docstring of DocTitle. """ default_priority = 350 def apply(self): if not getattr(self.document.settings, 'sectsubtitle_xform', 1): return for section in self.document.traverse(nodes.section): # On our way through the node tree, we are deleting # sections, but we call self.promote_subtitle for those # sections nonetheless. To do: Write a test case which # shows the problem and discuss on Docutils-develop. self.promote_subtitle(section) class DocInfo(Transform): """ This transform is specific to the reStructuredText_ markup syntax; see "Bibliographic Fields" in the `reStructuredText Markup Specification`_ for a high-level description. This transform should be run *after* the `DocTitle` transform. Given a field list as the first non-comment element after the document title and subtitle (if present), registered bibliographic field names are transformed to the corresponding DTD elements, becoming child elements of the "docinfo" element (except for a dedication and/or an abstract, which become "topic" elements after "docinfo"). For example, given this document fragment after parsing:: <document> <title> Document Title <field_list> <field> <field_name> Author <field_body> <paragraph> A. Name <field> <field_name> Status <field_body> <paragraph> $RCSfile$ ... After running the bibliographic field list transform, the resulting document tree would look like this:: <document> <title> Document Title <docinfo> <author> A. Name <status> frontmatter.py ... The "Status" field contained an expanded RCS keyword, which is normally (but optionally) cleaned up by the transform. The sole contents of the field body must be a paragraph containing an expanded RCS keyword of the form "$keyword: expansion text $". Any RCS keyword can be processed in any bibliographic field. The dollar signs and leading RCS keyword name are removed. Extra processing is done for the following RCS keywords: - "RCSfile" expands to the name of the file in the RCS or CVS repository, which is the name of the source file with a ",v" suffix appended. The transform will remove the ",v" suffix. - "Date" expands to the format "YYYY/MM/DD hh:mm:ss" (in the UTC time zone). The RCS Keywords transform will extract just the date itself and transform it to an ISO 8601 format date, as in "2000-12-31". (Since the source file for this text is itself stored under CVS, we can't show an example of the "Date" RCS keyword because we can't prevent any RCS keywords used in this explanation from being expanded. Only the "RCSfile" keyword is stable; its expansion text changes only if the file name changes.) .. _reStructuredText: http://docutils.sf.net/rst.html .. _reStructuredText Markup Specification: http://docutils.sf.net/docs/ref/rst/restructuredtext.html """ default_priority = 340 biblio_nodes = { 'author': nodes.author, 'authors': nodes.authors, 'organization': nodes.organization, 'address': nodes.address, 'contact': nodes.contact, 'version': nodes.version, 'revision': nodes.revision, 'status': nodes.status, 'date': nodes.date, 'copyright': nodes.copyright, 'dedication': nodes.topic, 'abstract': nodes.topic} """Canonical field name (lowcased) to node class name mapping for bibliographic fields (field_list).""" def apply(self): if not getattr(self.document.settings, 'docinfo_xform', 1): return document = self.document index = document.first_child_not_matching_class( nodes.PreBibliographic) if index is None: return candidate = document[index] if isinstance(candidate, nodes.field_list): biblioindex = document.first_child_not_matching_class( (nodes.Titular, nodes.Decorative)) nodelist = self.extract_bibliographic(candidate) del document[index] # untransformed field list (candidate) document[biblioindex:biblioindex] = nodelist def extract_bibliographic(self, field_list): docinfo = nodes.docinfo() bibliofields = self.language.bibliographic_fields labels = self.language.labels topics = {'dedication': None, 'abstract': None} for field in field_list: try: name = field[0][0].astext() normedname = nodes.fully_normalize_name(name) if not (len(field) == 2 and normedname in bibliofields and self.check_empty_biblio_field(field, name)): raise TransformError canonical = bibliofields[normedname] biblioclass = self.biblio_nodes[canonical] if issubclass(biblioclass, nodes.TextElement): if not self.check_compound_biblio_field(field, name): raise TransformError utils.clean_rcs_keywords( field[1][0], self.rcs_keyword_substitutions) docinfo.append(biblioclass('', '', *field[1][0])) elif issubclass(biblioclass, nodes.authors): self.extract_authors(field, name, docinfo) elif issubclass(biblioclass, nodes.topic): if topics[canonical]: field[-1] += self.document.reporter.warning( 'There can only be one "%s" field.' % name, base_node=field) raise TransformError title = nodes.title(name, labels[canonical]) topics[canonical] = biblioclass( '', title, classes=[canonical], *field[1].children) else: docinfo.append(biblioclass('', *field[1].children)) except TransformError: if len(field[-1]) == 1 \ and isinstance(field[-1][0], nodes.paragraph): utils.clean_rcs_keywords( field[-1][0], self.rcs_keyword_substitutions) docinfo.append(field) nodelist = [] if len(docinfo) != 0: nodelist.append(docinfo) for name in ('dedication', 'abstract'): if topics[name]: nodelist.append(topics[name]) return nodelist def check_empty_biblio_field(self, field, name): if len(field[-1]) < 1: field[-1] += self.document.reporter.warning( 'Cannot extract empty bibliographic field "%s".' % name, base_node=field) return None return 1 def check_compound_biblio_field(self, field, name): if len(field[-1]) > 1: field[-1] += self.document.reporter.warning( 'Cannot extract compound bibliographic field "%s".' % name, base_node=field) return None if not isinstance(field[-1][0], nodes.paragraph): field[-1] += self.document.reporter.warning( 'Cannot extract bibliographic field "%s" containing ' 'anything other than a single paragraph.' % name, base_node=field) return None return 1 rcs_keyword_substitutions = [ (re.compile(r'\$' r'Date: (\d\d\d\d)[-/](\d\d)[-/](\d\d)[ T][\d:]+' r'[^$]* \$', re.IGNORECASE), r'\1-\2-\3'), (re.compile(r'\$' r'RCSfile: (.+),v \$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$'), r'\1'),] def extract_authors(self, field, name, docinfo): try: if len(field[1]) == 1: if isinstance(field[1][0], nodes.paragraph): authors = self.authors_from_one_paragraph(field) elif isinstance(field[1][0], nodes.bullet_list): authors = self.authors_from_bullet_list(field) else: raise TransformError else: authors = self.authors_from_paragraphs(field) authornodes = [nodes.author('', '', *author) for author in authors if author] if len(authornodes) >= 1: docinfo.append(nodes.authors('', *authornodes)) else: raise TransformError except TransformError: field[-1] += self.document.reporter.warning( 'Bibliographic field "%s" incompatible with extraction: ' 'it must contain either a single paragraph (with authors ' 'separated by one of "%s"), multiple paragraphs (one per ' 'author), or a bullet list with one paragraph (one author) ' 'per item.' % (name, ''.join(self.language.author_separators)), base_node=field) raise def authors_from_one_paragraph(self, field): text = field[1][0].astext().strip() if not text: raise TransformError for authorsep in self.language.author_separators: authornames = text.split(authorsep) if len(authornames) > 1: break authornames = [author.strip() for author in authornames] authors = [[nodes.Text(author)] for author in authornames if author] return authors def authors_from_bullet_list(self, field): authors = [] for item in field[1][0]: if len(item) != 1 or not isinstance(item[0], nodes.paragraph): raise TransformError authors.append(item[0].children) if not authors: raise TransformError return authors def authors_from_paragraphs(self, field): for item in field[1]: if not isinstance(item, nodes.paragraph): raise TransformError authors = [item.children for item in field[1]] return authors
Python
# $Id: misc.py 6314 2010-04-26 10:04:17Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Miscellaneous transforms. """ __docformat__ = 'reStructuredText' from docutils import nodes from docutils.transforms import Transform, TransformError class CallBack(Transform): """ Inserts a callback into a document. The callback is called when the transform is applied, which is determined by its priority. For use with `nodes.pending` elements. Requires a ``details['callback']`` entry, a bound method or function which takes one parameter: the pending node. Other data can be stored in the ``details`` attribute or in the object hosting the callback method. """ default_priority = 990 def apply(self): pending = self.startnode pending.details['callback'](pending) pending.parent.remove(pending) class ClassAttribute(Transform): """ Move the "class" attribute specified in the "pending" node into the immediately following non-comment element. """ default_priority = 210 def apply(self): pending = self.startnode parent = pending.parent child = pending while parent: # Check for appropriate following siblings: for index in range(parent.index(child) + 1, len(parent)): element = parent[index] if (isinstance(element, nodes.Invisible) or isinstance(element, nodes.system_message)): continue element['classes'] += pending.details['class'] pending.parent.remove(pending) return else: # At end of section or container; apply to sibling child = parent parent = parent.parent error = self.document.reporter.error( 'No suitable element following "%s" directive' % pending.details['directive'], nodes.literal_block(pending.rawsource, pending.rawsource), line=pending.line) pending.replace_self(error) class Transitions(Transform): """ Move transitions at the end of sections up the tree. Complain on transitions after a title, at the beginning or end of the document, and after another transition. For example, transform this:: <section> ... <transition> <section> ... into this:: <section> ... <transition> <section> ... """ default_priority = 830 def apply(self): for node in self.document.traverse(nodes.transition): self.visit_transition(node) def visit_transition(self, node): index = node.parent.index(node) error = None if (index == 0 or isinstance(node.parent[0], nodes.title) and (index == 1 or isinstance(node.parent[1], nodes.subtitle) and index == 2)): assert (isinstance(node.parent, nodes.document) or isinstance(node.parent, nodes.section)) error = self.document.reporter.error( 'Document or section may not begin with a transition.', source=node.source, line=node.line) elif isinstance(node.parent[index - 1], nodes.transition): error = self.document.reporter.error( 'At least one body element must separate transitions; ' 'adjacent transitions are not allowed.', source=node.source, line=node.line) if error: # Insert before node and update index. node.parent.insert(index, error) index += 1 assert index < len(node.parent) if index != len(node.parent) - 1: # No need to move the node. return # Node behind which the transition is to be moved. sibling = node # While sibling is the last node of its parent. while index == len(sibling.parent) - 1: sibling = sibling.parent # If sibling is the whole document (i.e. it has no parent). if sibling.parent is None: # Transition at the end of document. Do not move the # transition up, and place an error behind. error = self.document.reporter.error( 'Document may not end with a transition.', line=node.line) node.parent.insert(node.parent.index(node) + 1, error) return index = sibling.parent.index(sibling) # Remove the original transition node. node.parent.remove(node) # Insert the transition after the sibling. sibling.parent.insert(index + 1, node)
Python
# $Id: pt_br.py 5567 2008-06-03 01:11:03Z goodger $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Brazilian Portuguese-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'Autor', 'authors': u'Autores', 'organization': u'Organiza\u00E7\u00E3o', 'address': u'Endere\u00E7o', 'contact': u'Contato', 'version': u'Vers\u00E3o', 'revision': u'Revis\u00E3o', 'status': u'Estado', 'date': u'Data', 'copyright': u'Copyright', 'dedication': u'Dedicat\u00F3ria', 'abstract': u'Resumo', 'attention': u'Aten\u00E7\u00E3o!', 'caution': u'Cuidado!', 'danger': u'PERIGO!', 'error': u'Erro', 'hint': u'Sugest\u00E3o', 'important': u'Importante', 'note': u'Nota', 'tip': u'Dica', 'warning': u'Aviso', 'contents': u'Sum\u00E1rio'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'autor': 'author', u'autores': 'authors', u'organiza\u00E7\u00E3o': 'organization', u'endere\u00E7o': 'address', u'contato': 'contact', u'vers\u00E3o': 'version', u'revis\u00E3o': 'revision', u'estado': 'status', u'data': 'date', u'copyright': 'copyright', u'dedicat\u00F3ria': 'dedication', u'resumo': 'abstract'} """Brazilian Portuguese (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# -*- coding: utf-8 -*- # $Id: zh_cn.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Pan Junyong <panjy@zopechina.com> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Simplified Chinese language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'作者', 'authors': u'作者群', 'organization': u'组织', 'address': u'地址', 'contact': u'联系', 'version': u'版本', 'revision': u'修订', 'status': u'状态', 'date': u'日期', 'copyright': u'版权', 'dedication': u'献辞', 'abstract': u'摘要', 'attention': u'注意', 'caution': u'小心', 'danger': u'危险', 'error': u'错误', 'hint': u'提示', 'important': u'重要', 'note': u'注解', 'tip': u'技巧', 'warning': u'警告', 'contents': u'目录', } """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'作者': 'author', u'作者群': 'authors', u'组织': 'organization', u'地址': 'address', u'联系': 'contact', u'版本': 'version', u'修订': 'revision', u'状态': 'status', u'时间': 'date', u'版权': 'copyright', u'献辞': 'dedication', u'摘要': 'abstract'} """Simplified Chinese to canonical name mapping for bibliographic fields.""" author_separators = [';', ',', u'\uff1b', # ';' u'\uff0c', # ',' u'\u3001', # '、' ] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: sv.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Adam Chodorowski <chodorowski@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Swedish language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { 'author': u'F\u00f6rfattare', 'authors': u'F\u00f6rfattare', 'organization': u'Organisation', 'address': u'Adress', 'contact': u'Kontakt', 'version': u'Version', 'revision': u'Revision', 'status': u'Status', 'date': u'Datum', 'copyright': u'Copyright', 'dedication': u'Dedikation', 'abstract': u'Sammanfattning', 'attention': u'Observera!', 'caution': u'Varning!', 'danger': u'FARA!', 'error': u'Fel', 'hint': u'V\u00e4gledning', 'important': u'Viktigt', 'note': u'Notera', 'tip': u'Tips', 'warning': u'Varning', 'contents': u'Inneh\u00e5ll' } """Mapping of node class name to label text.""" bibliographic_fields = { # 'Author' and 'Authors' identical in Swedish; assume the plural: u'f\u00f6rfattare': 'authors', u' n/a': 'author', u'organisation': 'organization', u'adress': 'address', u'kontakt': 'contact', u'version': 'version', u'revision': 'revision', u'status': 'status', u'datum': 'date', u'copyright': 'copyright', u'dedikation': 'dedication', u'sammanfattning': 'abstract' } """Swedish (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: it.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Nicola Larosa <docutils@tekNico.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Italian-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { 'author': 'Autore', 'authors': 'Autori', 'organization': 'Organizzazione', 'address': 'Indirizzo', 'contact': 'Contatti', 'version': 'Versione', 'revision': 'Revisione', 'status': 'Status', 'date': 'Data', 'copyright': 'Copyright', 'dedication': 'Dedica', 'abstract': 'Riassunto', 'attention': 'Attenzione!', 'caution': 'Cautela!', 'danger': '!PERICOLO!', 'error': 'Errore', 'hint': 'Suggerimento', 'important': 'Importante', 'note': 'Nota', 'tip': 'Consiglio', 'warning': 'Avvertenza', 'contents': 'Indice'} """Mapping of node class name to label text.""" bibliographic_fields = { 'autore': 'author', 'autori': 'authors', 'organizzazione': 'organization', 'indirizzo': 'address', 'contatto': 'contact', 'versione': 'version', 'revisione': 'revision', 'status': 'status', 'data': 'date', 'copyright': 'copyright', 'dedica': 'dedication', 'riassunto': 'abstract'} """Italian (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# -*- coding: utf-8 -*- # Author: David Goodger # Contact: goodger@users.sourceforge.net # Revision: $Revision: 2224 $ # Date: $Date: 2004-06-05 21:40:46 +0200 (Sat, 05 Jun 2004) $ # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Galician-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'Autor', 'authors': u'Autores', 'organization': u'Organizaci\u00f3n', 'address': u'Enderezo', 'contact': u'Contacto', 'version': u'Versi\u00f3n', 'revision': u'Revisi\u00f3n', 'status': u'Estado', 'date': u'Data', 'copyright': u'Dereitos de copia', 'dedication': u'Dedicatoria', 'abstract': u'Abstract', 'attention': u'Atenci\u00f3n!', 'caution': u'Advertencia!', 'danger': u'PERIGO!', 'error': u'Erro', 'hint': u'Consello', 'important': u'Importante', 'note': u'Nota', 'tip': u'Suxesti\u00f3n', 'warning': u'Aviso', 'contents': u'Contido'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'autor': 'author', u'autores': 'authors', u'organizaci\u00f3n': 'organization', u'enderezo': 'address', u'contacto': 'contact', u'versi\u00f3n': 'version', u'revisi\u00f3n': 'revision', u'estado': 'status', u'data': 'date', u'dereitos de copia': 'copyright', u'dedicatoria': 'dedication', u'abstract': 'abstract'} """Galician (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# -*- coding: utf-8 -*- # $Id: es.py 4572 2006-05-25 20:48:37Z richieadler $ # Author: Marcelo Huerta San Martín <richieadler@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Spanish-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { 'author': u'Autor', 'authors': u'Autores', 'organization': u'Organizaci\u00f3n', 'address': u'Direcci\u00f3n', 'contact': u'Contacto', 'version': u'Versi\u00f3n', 'revision': u'Revisi\u00f3n', 'status': u'Estado', 'date': u'Fecha', 'copyright': u'Copyright', 'dedication': u'Dedicatoria', 'abstract': u'Resumen', 'attention': u'\u00a1Atenci\u00f3n!', 'caution': u'\u00a1Precauci\u00f3n!', 'danger': u'\u00a1PELIGRO!', 'error': u'Error', 'hint': u'Sugerencia', 'important': u'Importante', 'note': u'Nota', 'tip': u'Consejo', 'warning': u'Advertencia', 'contents': u'Contenido'} """Mapping of node class name to label text.""" bibliographic_fields = { u'autor': 'author', u'autores': 'authors', u'organizaci\u00f3n': 'organization', u'direcci\u00f3n': 'address', u'contacto': 'contact', u'versi\u00f3n': 'version', u'revisi\u00f3n': 'revision', u'estado': 'status', u'fecha': 'date', u'copyright': 'copyright', u'dedicatoria': 'dedication', u'resumen': 'abstract'} """Spanish (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# -*- coding: utf-8 -*- # $Id: ja.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Hisashi Morita <hisashim@kt.rim.or.jp> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Japanese-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'著者', 'authors': u'著者', 'organization': u'組織', 'address': u'住所', 'contact': u'連絡先', 'version': u'バージョン', 'revision': u'リビジョン', 'status': u'ステータス', 'date': u'日付', 'copyright': u'著作権', 'dedication': u'献辞', 'abstract': u'概要', 'attention': u'注目!', 'caution': u'注意!', 'danger': u'!危険!', 'error': u'エラー', 'hint': u'ヒント', 'important': u'重要', 'note': u'備考', 'tip': u'通報', 'warning': u'警告', 'contents': u'目次'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'著者': 'author', u' n/a': 'authors', u'組織': 'organization', u'住所': 'address', u'連絡先': 'contact', u'バージョン': 'version', u'リビジョン': 'revision', u'ステータス': 'status', u'日付': 'date', u'著作権': 'copyright', u'献辞': 'dedication', u'概要': 'abstract'} """Japanese (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: ca.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Ivan Vilata i Balaguer <ivan@selidor.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Catalan-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'Autor', 'authors': u'Autors', 'organization': u'Organitzaci\u00F3', 'address': u'Adre\u00E7a', 'contact': u'Contacte', 'version': u'Versi\u00F3', 'revision': u'Revisi\u00F3', 'status': u'Estat', 'date': u'Data', 'copyright': u'Copyright', 'dedication': u'Dedicat\u00F2ria', 'abstract': u'Resum', 'attention': u'Atenci\u00F3!', 'caution': u'Compte!', 'danger': u'PERILL!', 'error': u'Error', 'hint': u'Suggeriment', 'important': u'Important', 'note': u'Nota', 'tip': u'Consell', 'warning': u'Av\u00EDs', 'contents': u'Contingut'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'autor': 'author', u'autors': 'authors', u'organitzaci\u00F3': 'organization', u'adre\u00E7a': 'address', u'contacte': 'contact', u'versi\u00F3': 'version', u'revisi\u00F3': 'revision', u'estat': 'status', u'data': 'date', u'copyright': 'copyright', u'dedicat\u00F2ria': 'dedication', u'resum': 'abstract'} """Catalan (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: cs.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Marek Blaha <mb@dat.cz> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Czech-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'Autor', 'authors': u'Auto\u0159i', 'organization': u'Organizace', 'address': u'Adresa', 'contact': u'Kontakt', 'version': u'Verze', 'revision': u'Revize', 'status': u'Stav', 'date': u'Datum', 'copyright': u'Copyright', 'dedication': u'V\u011Bnov\u00E1n\u00ED', 'abstract': u'Abstrakt', 'attention': u'Pozor!', 'caution': u'Opatrn\u011B!', 'danger': u'!NEBEZPE\u010C\u00CD!', 'error': u'Chyba', 'hint': u'Rada', 'important': u'D\u016Fle\u017Eit\u00E9', 'note': u'Pozn\u00E1mka', 'tip': u'Tip', 'warning': u'Varov\u00E1n\u00ED', 'contents': u'Obsah'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'autor': 'author', u'auto\u0159i': 'authors', u'organizace': 'organization', u'adresa': 'address', u'kontakt': 'contact', u'verze': 'version', u'revize': 'revision', u'stav': 'status', u'datum': 'date', u'copyright': 'copyright', u'v\u011Bnov\u00E1n\u00ED': 'dedication', u'abstrakt': 'abstract'} """Czech (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: af.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Jannie Hofmeyr <jhsh@sun.ac.za> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Afrikaans-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { 'author': 'Auteur', 'authors': 'Auteurs', 'organization': 'Organisasie', 'address': 'Adres', 'contact': 'Kontak', 'version': 'Weergawe', 'revision': 'Revisie', 'status': 'Status', 'date': 'Datum', 'copyright': 'Kopiereg', 'dedication': 'Opdrag', 'abstract': 'Opsomming', 'attention': 'Aandag!', 'caution': 'Wees versigtig!', 'danger': '!GEVAAR!', 'error': 'Fout', 'hint': 'Wenk', 'important': 'Belangrik', 'note': 'Nota', 'tip': 'Tip', # hint and tip both have the same translation: wenk 'warning': 'Waarskuwing', 'contents': 'Inhoud'} """Mapping of node class name to label text.""" bibliographic_fields = { 'auteur': 'author', 'auteurs': 'authors', 'organisasie': 'organization', 'adres': 'address', 'kontak': 'contact', 'weergawe': 'version', 'revisie': 'revision', 'status': 'status', 'datum': 'date', 'kopiereg': 'copyright', 'opdrag': 'dedication', 'opsomming': 'abstract'} """Afrikaans (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: sk.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Miroslav Vasko <zemiak@zoznam.sk> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Slovak-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { 'author': u'Autor', 'authors': u'Autori', 'organization': u'Organiz\u00E1cia', 'address': u'Adresa', 'contact': u'Kontakt', 'version': u'Verzia', 'revision': u'Rev\u00EDzia', 'status': u'Stav', 'date': u'D\u00E1tum', 'copyright': u'Copyright', 'dedication': u'Venovanie', 'abstract': u'Abstraktne', 'attention': u'Pozor!', 'caution': u'Opatrne!', 'danger': u'!NEBEZPE\u010cENSTVO!', 'error': u'Chyba', 'hint': u'Rada', 'important': u'D\u00F4le\u017Eit\u00E9', 'note': u'Pozn\u00E1mka', 'tip': u'Tip', 'warning': u'Varovanie', 'contents': u'Obsah'} """Mapping of node class name to label text.""" bibliographic_fields = { u'autor': 'author', u'autori': 'authors', u'organiz\u00E1cia': 'organization', u'adresa': 'address', u'kontakt': 'contact', u'verzia': 'version', u'rev\u00EDzia': 'revision', u'stav': 'status', u'd\u00E1tum': 'date', u'copyright': 'copyright', u'venovanie': 'dedication', u'abstraktne': 'abstract'} """Slovak (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id$ # Author: Robert Wojciechowicz <rw@smsnet.pl> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Polish-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'Autor', 'authors': u'Autorzy', 'organization': u'Organizacja', 'address': u'Adres', 'contact': u'Kontakt', 'version': u'Wersja', 'revision': u'Korekta', 'status': u'Status', 'date': u'Data', 'copyright': u'Copyright', 'dedication': u'Dedykacja', 'abstract': u'Streszczenie', 'attention': u'Uwaga!', 'caution': u'Ostro\u017cnie!', 'danger': u'!Niebezpiecze\u0144stwo!', 'error': u'B\u0142\u0105d', 'hint': u'Wskaz\u00f3wka', 'important': u'Wa\u017cne', 'note': u'Przypis', 'tip': u'Rada', 'warning': u'Ostrze\u017cenie', 'contents': u'Tre\u015b\u0107'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'autor': 'author', u'autorzy': 'authors', u'organizacja': 'organization', u'adres': 'address', u'kontakt': 'contact', u'wersja': 'version', u'korekta': 'revision', u'status': 'status', u'data': 'date', u'copyright': 'copyright', u'dedykacja': 'dedication', u'streszczenie': 'abstract'} """Polish (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: ru.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Roman Suzi <rnd@onego.ru> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Russian-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { u'abstract': u'\u0410\u043d\u043d\u043e\u0442\u0430\u0446\u0438\u044f', u'address': u'\u0410\u0434\u0440\u0435\u0441', u'attention': u'\u0412\u043d\u0438\u043c\u0430\u043d\u0438\u0435!', u'author': u'\u0410\u0432\u0442\u043e\u0440', u'authors': u'\u0410\u0432\u0442\u043e\u0440\u044b', u'caution': u'\u041e\u0441\u0442\u043e\u0440\u043e\u0436\u043d\u043e!', u'contact': u'\u041a\u043e\u043d\u0442\u0430\u043a\u0442', u'contents': u'\u0421\u043e\u0434\u0435\u0440\u0436\u0430\u043d\u0438\u0435', u'copyright': u'\u041f\u0440\u0430\u0432\u0430 ' u'\u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f', u'danger': u'\u041e\u041f\u0410\u0421\u041d\u041e!', u'date': u'\u0414\u0430\u0442\u0430', u'dedication': u'\u041f\u043e\u0441\u0432\u044f\u0449\u0435\u043d\u0438\u0435', u'error': u'\u041e\u0448\u0438\u0431\u043a\u0430', u'hint': u'\u0421\u043e\u0432\u0435\u0442', u'important': u'\u0412\u0430\u0436\u043d\u043e', u'note': u'\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435', u'organization': u'\u041e\u0440\u0433\u0430\u043d\u0438\u0437\u0430\u0446\u0438\u044f', u'revision': u'\u0420\u0435\u0434\u0430\u043a\u0446\u0438\u044f', u'status': u'\u0421\u0442\u0430\u0442\u0443\u0441', u'tip': u'\u041f\u043e\u0434\u0441\u043a\u0430\u0437\u043a\u0430', u'version': u'\u0412\u0435\u0440\u0441\u0438\u044f', u'warning': u'\u041f\u0440\u0435\u0434\u0443\u043f\u0440\u0435\u0436' u'\u0434\u0435\u043d\u0438\u0435'} """Mapping of node class name to label text.""" bibliographic_fields = { u'\u0430\u043d\u043d\u043e\u0442\u0430\u0446\u0438\u044f': u'abstract', u'\u0430\u0434\u0440\u0435\u0441': u'address', u'\u0430\u0432\u0442\u043e\u0440': u'author', u'\u0430\u0432\u0442\u043e\u0440\u044b': u'authors', u'\u043a\u043e\u043d\u0442\u0430\u043a\u0442': u'contact', u'\u043f\u0440\u0430\u0432\u0430 \u043a\u043e\u043f\u0438\u0440\u043e' u'\u0432\u0430\u043d\u0438\u044f': u'copyright', u'\u0434\u0430\u0442\u0430': u'date', u'\u043f\u043e\u0441\u0432\u044f\u0449\u0435\u043d\u0438\u0435': u'dedication', u'\u043e\u0440\u0433\u0430\u043d\u0438\u0437\u0430\u0446\u0438\u044f': u'organization', u'\u0440\u0435\u0434\u0430\u043a\u0446\u0438\u044f': u'revision', u'\u0441\u0442\u0430\u0442\u0443\u0441': u'status', u'\u0432\u0435\u0440\u0441\u0438\u044f': u'version'} """Russian (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: de.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Gunnar Schwant <g.schwant@gmx.de> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ German language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { 'author': 'Autor', 'authors': 'Autoren', 'organization': 'Organisation', 'address': 'Adresse', 'contact': 'Kontakt', 'version': 'Version', 'revision': 'Revision', 'status': 'Status', 'date': 'Datum', 'dedication': 'Widmung', 'copyright': 'Copyright', 'abstract': 'Zusammenfassung', 'attention': 'Achtung!', 'caution': 'Vorsicht!', 'danger': '!GEFAHR!', 'error': 'Fehler', 'hint': 'Hinweis', 'important': 'Wichtig', 'note': 'Bemerkung', 'tip': 'Tipp', 'warning': 'Warnung', 'contents': 'Inhalt'} """Mapping of node class name to label text.""" bibliographic_fields = { 'autor': 'author', 'autoren': 'authors', 'organisation': 'organization', 'adresse': 'address', 'kontakt': 'contact', 'version': 'version', 'revision': 'revision', 'status': 'status', 'datum': 'date', 'copyright': 'copyright', 'widmung': 'dedication', 'zusammenfassung': 'abstract'} """German (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: en.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ English-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': 'Author', 'authors': 'Authors', 'organization': 'Organization', 'address': 'Address', 'contact': 'Contact', 'version': 'Version', 'revision': 'Revision', 'status': 'Status', 'date': 'Date', 'copyright': 'Copyright', 'dedication': 'Dedication', 'abstract': 'Abstract', 'attention': 'Attention!', 'caution': 'Caution!', 'danger': '!DANGER!', 'error': 'Error', 'hint': 'Hint', 'important': 'Important', 'note': 'Note', 'tip': 'Tip', 'warning': 'Warning', 'contents': 'Contents'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed 'author': 'author', 'authors': 'authors', 'organization': 'organization', 'address': 'address', 'contact': 'contact', 'version': 'version', 'revision': 'revision', 'status': 'status', 'date': 'date', 'copyright': 'copyright', 'dedication': 'dedication', 'abstract': 'abstract'} """English (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: fi.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Asko Soukka <asko.soukka@iki.fi> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Finnish-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent u'author': u'Tekij\u00e4', u'authors': u'Tekij\u00e4t', u'organization': u'Yhteis\u00f6', u'address': u'Osoite', u'contact': u'Yhteystiedot', u'version': u'Versio', u'revision': u'Vedos', u'status': u'Tila', u'date': u'P\u00e4iv\u00e4ys', u'copyright': u'Tekij\u00e4noikeudet', u'dedication': u'Omistuskirjoitus', u'abstract': u'Tiivistelm\u00e4', u'attention': u'Huomio!', u'caution': u'Varo!', u'danger': u'!VAARA!', u'error': u'Virhe', u'hint': u'Vihje', u'important': u'T\u00e4rke\u00e4\u00e4', u'note': u'Huomautus', u'tip': u'Neuvo', u'warning': u'Varoitus', u'contents': u'Sis\u00e4llys'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'tekij\u00e4': u'author', u'tekij\u00e4t': u'authors', u'yhteis\u00f6': u'organization', u'osoite': u'address', u'yhteystiedot': u'contact', u'versio': u'version', u'vedos': u'revision', u'tila': u'status', u'p\u00e4iv\u00e4ys': u'date', u'tekij\u00e4noikeudet': u'copyright', u'omistuskirjoitus': u'dedication', u'tiivistelm\u00e4': u'abstract'} """Finnish (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# Author: Meir Kriheli # Id: $Id: he.py 4837 2006-12-26 09:59:41Z sfcben $ # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Hebrew-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'\u05de\u05d7\u05d1\u05e8', 'authors': u'\u05de\u05d7\u05d1\u05e8\u05d9', 'organization': u'\u05d0\u05e8\u05d2\u05d5\u05df', 'address': u'\u05db\u05ea\u05d5\u05d1\u05ea', 'contact': u'\u05d0\u05d9\u05e9 \u05e7\u05e9\u05e8', 'version': u'\u05d2\u05e8\u05e1\u05d4', 'revision': u'\u05de\u05d4\u05d3\u05d5\u05e8\u05d4', 'status': u'\u05e1\u05d8\u05d8\u05d5\u05e1', 'date': u'\u05ea\u05d0\u05e8\u05d9\u05da', 'copyright': u'\u05d6\u05db\u05d5\u05d9\u05d5\u05ea \u05e9\u05de\u05d5\u05e8\u05d5\u05ea', 'dedication': u'\u05d4\u05e7\u05d3\u05e9\u05d4', 'abstract': u'\u05ea\u05e7\u05e6\u05d9\u05e8', 'attention': u'\u05ea\u05e9\u05d5\u05de\u05ea \u05dc\u05d1', 'caution': u'\u05d6\u05d4\u05d9\u05e8\u05d5\u05ea', 'danger': u'\u05e1\u05db\u05e0\u05d4', 'error': u'\u05e9\u05d2\u05d9\u05d0\u05d4' , 'hint': u'\u05e8\u05de\u05d6', 'important': u'\u05d7\u05e9\u05d5\u05d1', 'note': u'\u05d4\u05e2\u05e8\u05d4', 'tip': u'\u05d8\u05d9\u05e4', 'warning': u'\u05d0\u05d6\u05d4\u05e8\u05d4', 'contents': u'\u05ea\u05d5\u05db\u05df'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed u'\u05de\u05d7\u05d1\u05e8': 'author', u'\u05de\u05d7\u05d1\u05e8\u05d9': 'authors', u'\u05d0\u05e8\u05d2\u05d5\u05df': 'organization', u'\u05db\u05ea\u05d5\u05d1\u05ea': 'address', u'\u05d0\u05d9\u05e9 \u05e7\u05e9\u05e8': 'contact', u'\u05d2\u05e8\u05e1\u05d4': 'version', u'\u05de\u05d4\u05d3\u05d5\u05e8\u05d4': 'revision', u'\u05e1\u05d8\u05d8\u05d5\u05e1': 'status', u'\u05ea\u05d0\u05e8\u05d9\u05da': 'date', u'\u05d6\u05db\u05d5\u05d9\u05d5\u05ea \u05e9\u05de\u05d5\u05e8\u05d5\u05ea': 'copyright', u'\u05d4\u05e7\u05d3\u05e9\u05d4': 'dedication', u'\u05ea\u05e7\u05e6\u05d9\u05e8': 'abstract'} """Hebrew to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: fr.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Stefane Fermigier <sf@fermigier.com> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ French-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { u'author': u'Auteur', u'authors': u'Auteurs', u'organization': u'Organisation', u'address': u'Adresse', u'contact': u'Contact', u'version': u'Version', u'revision': u'R\u00e9vision', u'status': u'Statut', u'date': u'Date', u'copyright': u'Copyright', u'dedication': u'D\u00e9dicace', u'abstract': u'R\u00e9sum\u00e9', u'attention': u'Attention!', u'caution': u'Avertissement!', u'danger': u'!DANGER!', u'error': u'Erreur', u'hint': u'Indication', u'important': u'Important', u'note': u'Note', u'tip': u'Astuce', u'warning': u'Avis', u'contents': u'Sommaire'} """Mapping of node class name to label text.""" bibliographic_fields = { u'auteur': u'author', u'auteurs': u'authors', u'organisation': u'organization', u'adresse': u'address', u'contact': u'contact', u'version': u'version', u'r\u00e9vision': u'revision', u'statut': u'status', u'date': u'date', u'copyright': u'copyright', u'd\u00e9dicace': u'dedication', u'r\u00e9sum\u00e9': u'abstract'} """French (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: nl.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Martijn Pieters <mjpieters@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Dutch-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': 'Auteur', 'authors': 'Auteurs', 'organization': 'Organisatie', 'address': 'Adres', 'contact': 'Contact', 'version': 'Versie', 'revision': 'Revisie', 'status': 'Status', 'date': 'Datum', 'copyright': 'Copyright', 'dedication': 'Toewijding', 'abstract': 'Samenvatting', 'attention': 'Attentie!', 'caution': 'Let op!', 'danger': '!GEVAAR!', 'error': 'Fout', 'hint': 'Hint', 'important': 'Belangrijk', 'note': 'Opmerking', 'tip': 'Tip', 'warning': 'Waarschuwing', 'contents': 'Inhoud'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed 'auteur': 'author', 'auteurs': 'authors', 'organisatie': 'organization', 'adres': 'address', 'contact': 'contact', 'versie': 'version', 'revisie': 'revision', 'status': 'status', 'datum': 'date', 'copyright': 'copyright', 'toewijding': 'dedication', 'samenvatting': 'abstract'} """Dutch (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# -*- coding: utf-8 -*- # $Id: zh_tw.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Joe YS Jaw <joeysj@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Traditional Chinese language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'\u4f5c\u8005', # '作者' <-- Chinese word 'authors': u'\u4f5c\u8005\u7fa4', # '作者群', 'organization': u'\u7d44\u7e54', # '組織', 'address': u'\u5730\u5740', # '地址', 'contact': u'\u9023\u7d61', # '連絡', 'version': u'\u7248\u672c', # '版本', 'revision': u'\u4fee\u8a02', # '修訂', 'status': u'\u72c0\u614b', # '狀態', 'date': u'\u65e5\u671f', # '日期', 'copyright': u'\u7248\u6b0a', # '版權', 'dedication': u'\u984c\u737b', # '題獻', 'abstract': u'\u6458\u8981', # '摘要', 'attention': u'\u6ce8\u610f\uff01', # '注意!', 'caution': u'\u5c0f\u5fc3\uff01', # '小心!', 'danger': u'\uff01\u5371\u96aa\uff01', # '!危險!', 'error': u'\u932f\u8aa4', # '錯誤', 'hint': u'\u63d0\u793a', # '提示', 'important': u'\u91cd\u8981', # '注意!', 'note': u'\u8a3b\u91cb', # '註釋', 'tip': u'\u79d8\u8a23', # '秘訣', 'warning': u'\u8b66\u544a', # '警告', 'contents': u'\u76ee\u9304' # '目錄' } """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed 'author (translation required)': 'author', 'authors (translation required)': 'authors', 'organization (translation required)': 'organization', 'address (translation required)': 'address', 'contact (translation required)': 'contact', 'version (translation required)': 'version', 'revision (translation required)': 'revision', 'status (translation required)': 'status', 'date (translation required)': 'date', 'copyright (translation required)': 'copyright', 'dedication (translation required)': 'dedication', 'abstract (translation required)': 'abstract'} """Traditional Chinese to canonical name mapping for bibliographic fields.""" author_separators = [';', ',', u'\uff1b', # ';' u'\uff0c', # ',' u'\u3001', # '、' ] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: eo.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Marcelo Huerta San Martin <richieadler@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Esperanto-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': u'A\u016dtoro', 'authors': u'A\u016dtoroj', 'organization': u'Organizo', 'address': u'Adreso', 'contact': u'Kontakto', 'version': u'Versio', 'revision': u'Revido', 'status': u'Stato', 'date': u'Dato', # 'copyright': u'Kopirajto', 'copyright': u'A\u016dtorrajto', 'dedication': u'Dedi\u0109o', 'abstract': u'Resumo', 'attention': u'Atentu!', 'caution': u'Zorgu!', 'danger': u'DAN\u011cERO!', 'error': u'Eraro', 'hint': u'Spuro', 'important': u'Grava', 'note': u'Noto', 'tip': u'Helpeto', 'warning': u'Averto', 'contents': u'Enhavo'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed 'a\u016dtoro': 'author', 'a\u016dtoroj': 'authors', 'organizo': 'organization', 'adreso': 'address', 'kontakto': 'contact', 'versio': 'version', 'revido': 'revision', 'stato': 'status', 'dato': 'date', 'a\u016dtorrajto': 'copyright', 'dedi\u0109o': 'dedication', 'resumo': 'abstract'} """Esperanto (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
Python
# $Id: __init__.py 5618 2008-07-28 08:37:32Z strank $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # Internationalization details are documented in # <http://docutils.sf.net/docs/howto/i18n.html>. """ This package contains modules for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' _languages = {} def get_language(language_code): if language_code in _languages: return _languages[language_code] module = __import__(language_code, globals(), locals()) _languages[language_code] = module return module
Python
# $Id: io.py 6269 2010-03-18 22:27:53Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ I/O classes provide a uniform API for low-level input and output. Subclasses will exist for a variety of input/output mechanisms. """ __docformat__ = 'reStructuredText' import sys try: import locale except: pass import re import codecs from docutils import TransformSpec from docutils._compat import b class Input(TransformSpec): """ Abstract base class for input wrappers. """ component_type = 'input' default_source_path = None def __init__(self, source=None, source_path=None, encoding=None, error_handler='strict'): self.encoding = encoding """Text encoding for the input source.""" self.error_handler = error_handler """Text decoding error handler.""" self.source = source """The source of input data.""" self.source_path = source_path """A text reference to the source.""" if not source_path: self.source_path = self.default_source_path self.successful_encoding = None """The encoding that successfully decoded the source data.""" def __repr__(self): return '%s: source=%r, source_path=%r' % (self.__class__, self.source, self.source_path) def read(self): raise NotImplementedError def decode(self, data): """ Decode a string, `data`, heuristically. Raise UnicodeError if unsuccessful. The client application should call ``locale.setlocale`` at the beginning of processing:: locale.setlocale(locale.LC_ALL, '') """ if self.encoding and self.encoding.lower() == 'unicode': assert isinstance(data, unicode), ( 'input encoding is "unicode" ' 'but input is not a unicode object') if isinstance(data, unicode): # Accept unicode even if self.encoding != 'unicode'. return data if self.encoding: # We believe the user/application when the encoding is # explicitly given. encodings = [self.encoding] else: data_encoding = self.determine_encoding_from_data(data) if data_encoding: # If the data declares its encoding (explicitly or via a BOM), # we believe it. encodings = [data_encoding] else: # Apply heuristics only if no encoding is explicitly given and # no BOM found. Start with UTF-8, because that only matches # data that *IS* UTF-8: encodings = ['utf-8'] try: encodings.append(locale.getlocale()[1]) except: pass try: encodings.append(locale.getdefaultlocale()[1]) except: pass # fallback encoding: encodings.append('latin-1') error = None error_details = '' for enc in encodings: if not enc: continue try: decoded = unicode(data, enc, self.error_handler) self.successful_encoding = enc # Return decoded, removing BOMs. return decoded.replace(u'\ufeff', u'') except (UnicodeError, LookupError), tmperror: error = tmperror # working around Python 3 deleting the # error variable after the except clause if error is not None: error_details = '\n(%s: %s)' % (error.__class__.__name__, error) raise UnicodeError( 'Unable to decode input data. Tried the following encodings: ' '%s.%s' % (', '.join([repr(enc) for enc in encodings if enc]), error_details)) coding_slug = re.compile(b("coding[:=]\s*([-\w.]+)")) """Encoding declaration pattern.""" byte_order_marks = ((codecs.BOM_UTF8, 'utf-8'), # actually 'utf-8-sig' (codecs.BOM_UTF16_BE, 'utf-16-be'), (codecs.BOM_UTF16_LE, 'utf-16-le'),) """Sequence of (start_bytes, encoding) tuples for encoding detection. The first bytes of input data are checked against the start_bytes strings. A match indicates the given encoding.""" def determine_encoding_from_data(self, data): """ Try to determine the encoding of `data` by looking *in* `data`. Check for a byte order mark (BOM) or an encoding declaration. """ # check for a byte order mark: for start_bytes, encoding in self.byte_order_marks: if data.startswith(start_bytes): return encoding # check for an encoding declaration pattern in first 2 lines of file: for line in data.splitlines()[:2]: match = self.coding_slug.search(line) if match: return match.group(1).decode('ascii') return None class Output(TransformSpec): """ Abstract base class for output wrappers. """ component_type = 'output' default_destination_path = None def __init__(self, destination=None, destination_path=None, encoding=None, error_handler='strict'): self.encoding = encoding """Text encoding for the output destination.""" self.error_handler = error_handler or 'strict' """Text encoding error handler.""" self.destination = destination """The destination for output data.""" self.destination_path = destination_path """A text reference to the destination.""" if not destination_path: self.destination_path = self.default_destination_path def __repr__(self): return ('%s: destination=%r, destination_path=%r' % (self.__class__, self.destination, self.destination_path)) def write(self, data): """`data` is a Unicode string, to be encoded by `self.encode`.""" raise NotImplementedError def encode(self, data): if self.encoding and self.encoding.lower() == 'unicode': assert isinstance(data, unicode), ( 'the encoding given is "unicode" but the output is not ' 'a Unicode string') return data if not isinstance(data, unicode): # Non-unicode (e.g. binary) output. return data else: return data.encode(self.encoding, self.error_handler) class FileInput(Input): """ Input for single, simple file-like objects. """ def __init__(self, source=None, source_path=None, encoding=None, error_handler='strict', autoclose=1, handle_io_errors=1, mode='rU'): """ :Parameters: - `source`: either a file-like object (which is read directly), or `None` (which implies `sys.stdin` if no `source_path` given). - `source_path`: a path to a file, which is opened and then read. - `encoding`: the expected text encoding of the input file. - `error_handler`: the encoding error handler to use. - `autoclose`: close automatically after read (boolean); always false if `sys.stdin` is the source. - `handle_io_errors`: summarize I/O errors here, and exit? - `mode`: how the file is to be opened (see standard function `open`). The default 'rU' provides universal newline support for text files. """ Input.__init__(self, source, source_path, encoding, error_handler) self.autoclose = autoclose self.handle_io_errors = handle_io_errors if source is None: if source_path: # Specify encoding in Python 3 if sys.version_info >= (3,0): kwargs = {'encoding': self.encoding, 'errors': self.error_handler} else: kwargs = {} try: self.source = open(source_path, mode, **kwargs) except IOError, error: if not handle_io_errors: raise print >>sys.stderr, '%s: %s' % (error.__class__.__name__, error) print >>sys.stderr, ('Unable to open source file for ' "reading ('%s'). Exiting." % source_path) sys.exit(1) else: self.source = sys.stdin self.autoclose = None if not source_path: try: self.source_path = self.source.name except AttributeError: pass def read(self): """ Read and decode a single file and return the data (Unicode string). """ try: data = self.source.read() finally: if self.autoclose: self.close() return self.decode(data) def readlines(self): """ Return lines of a single file as list of Unicode strings. """ try: lines = self.source.readlines() finally: if self.autoclose: self.close() return [self.decode(line) for line in lines] def close(self): self.source.close() class FileOutput(Output): """ Output for single, simple file-like objects. """ def __init__(self, destination=None, destination_path=None, encoding=None, error_handler='strict', autoclose=1, handle_io_errors=1): """ :Parameters: - `destination`: either a file-like object (which is written directly) or `None` (which implies `sys.stdout` if no `destination_path` given). - `destination_path`: a path to a file, which is opened and then written. - `autoclose`: close automatically after write (boolean); always false if `sys.stdout` is the destination. """ Output.__init__(self, destination, destination_path, encoding, error_handler) self.opened = 1 self.autoclose = autoclose self.handle_io_errors = handle_io_errors if destination is None: if destination_path: self.opened = None else: self.destination = sys.stdout self.autoclose = None if not destination_path: try: self.destination_path = self.destination.name except AttributeError: pass def open(self): # Specify encoding in Python 3. # (Do not use binary mode ('wb') as this prevents the # conversion of newlines to the system specific default.) if sys.version_info >= (3,0): kwargs = {'encoding': self.encoding, 'errors': self.error_handler} else: kwargs = {} try: self.destination = open(self.destination_path, 'w', **kwargs) except IOError, error: if not self.handle_io_errors: raise print >>sys.stderr, '%s: %s' % (error.__class__.__name__, error) print >>sys.stderr, ('Unable to open destination file for writing' " ('%s'). Exiting." % self.destination_path) sys.exit(1) self.opened = 1 def write(self, data): """Encode `data`, write it to a single file, and return it. In Python 3, a (unicode) String is returned. """ if sys.version_info >= (3,0): output = data # in py3k, write expects a (Unicode) string else: output = self.encode(data) if not self.opened: self.open() try: self.destination.write(output) finally: if self.autoclose: self.close() return output def close(self): self.destination.close() self.opened = None class BinaryFileOutput(FileOutput): """ A version of docutils.io.FileOutput which writes to a binary file. """ def open(self): try: self.destination = open(self.destination_path, 'wb') except IOError, error: if not self.handle_io_errors: raise print >>sys.stderr, '%s: %s' % (error.__class__.__name__, error) print >>sys.stderr, ('Unable to open destination file for writing ' "('%s'). Exiting." % self.destination_path) sys.exit(1) self.opened = 1 class StringInput(Input): """ Direct string input. """ default_source_path = '<string>' def read(self): """Decode and return the source string.""" return self.decode(self.source) class StringOutput(Output): """ Direct string output. """ default_destination_path = '<string>' def write(self, data): """Encode `data`, store it in `self.destination`, and return it.""" self.destination = self.encode(data) return self.destination class NullInput(Input): """ Degenerate input: read nothing. """ default_source_path = 'null input' def read(self): """Return a null string.""" return u'' class NullOutput(Output): """ Degenerate output: write nothing. """ default_destination_path = 'null output' def write(self, data): """Do nothing ([don't even] send data to the bit bucket).""" pass class DocTreeInput(Input): """ Adapter for document tree input. The document tree must be passed in the ``source`` parameter. """ default_source_path = 'doctree input' def read(self): """Return the document tree.""" return self.source
Python
# $Id: doctree.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Martin Blais <blais@furius.ca> # Copyright: This module has been placed in the public domain. """Reader for existing document trees.""" from docutils import readers, utils, transforms class Reader(readers.ReReader): """ Adapt the Reader API for an existing document tree. The existing document tree must be passed as the ``source`` parameter to the `docutils.core.Publisher` initializer, wrapped in a `docutils.io.DocTreeInput` object:: pub = docutils.core.Publisher( ..., source=docutils.io.DocTreeInput(document), ...) The original document settings are overridden; if you want to use the settings of the original document, pass ``settings=document.settings`` to the Publisher call above. """ supported = ('doctree',) config_section = 'doctree reader' config_section_dependencies = ('readers',) def parse(self): """ No parsing to do; refurbish the document tree instead. Overrides the inherited method. """ self.document = self.input # Create fresh Transformer object, to be populated from Writer # component. self.document.transformer = transforms.Transformer(self.document) # Replace existing settings object with new one. self.document.settings = self.settings # Create fresh Reporter object because it is dependent on # (new) settings. self.document.reporter = utils.new_reporter( self.document.get('source', ''), self.document.settings)
Python
#! /usr/bin/env python # $Id: pynodes.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. from docutils import nodes from docutils.nodes import Element, TextElement, Structural, Inline, Part, \ Text import types # This is the parent class of all the other pynode classes: class PythonStructural(Structural): pass # ===================== # Structural Elements # ===================== class module_section(PythonStructural, Element): pass class class_section(PythonStructural, Element): pass class class_base(PythonStructural, Element): pass class method_section(PythonStructural, Element): pass class attribute(PythonStructural, Element): pass class function_section(PythonStructural, Element): pass class class_attribute_section(PythonStructural, Element): pass class class_attribute(PythonStructural, Element): pass class expression_value(PythonStructural, Element): pass class attribute(PythonStructural, Element): pass # Structural Support Elements # --------------------------- class parameter_list(PythonStructural, Element): pass class parameter_tuple(PythonStructural, Element): pass class parameter_default(PythonStructural, TextElement): pass class import_group(PythonStructural, TextElement): pass class import_from(PythonStructural, TextElement): pass class import_name(PythonStructural, TextElement): pass class import_alias(PythonStructural, TextElement): pass class docstring(PythonStructural, Element): pass # ================= # Inline Elements # ================= # These elements cannot become references until the second # pass. Initially, we'll use "reference" or "name". class object_name(PythonStructural, TextElement): pass class parameter_list(PythonStructural, TextElement): pass class parameter(PythonStructural, TextElement): pass class parameter_default(PythonStructural, TextElement): pass class class_attribute(PythonStructural, TextElement): pass class attribute_tuple(PythonStructural, TextElement): pass # ================= # Unused Elements # ================= # These were part of the model, and maybe should be in the future, but # aren't now. #class package_section(PythonStructural, Element): pass #class module_attribute_section(PythonStructural, Element): pass #class instance_attribute_section(PythonStructural, Element): pass #class module_attribute(PythonStructural, TextElement): pass #class instance_attribute(PythonStructural, TextElement): pass #class exception_class(PythonStructural, TextElement): pass #class warning_class(PythonStructural, TextElement): pass # Collect all the classes we've written above def install_node_class_names(): node_class_names = [] for name, var in globals().items(): if (type(var) is types.ClassType and issubclass(var, PythonStructural) \ and name.lower() == name): node_class_names.append(var.tagname or name) # Register the new node names with GenericNodeVisitor and # SpecificNodeVisitor: nodes._add_node_class_names(node_class_names) install_node_class_names()
Python
# $Id: moduleparser.py 5738 2008-11-30 08:59:04Z grubert $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Parser for Python modules. The `parse_module()` function takes a module's text and file name, runs it through the module parser (using compiler.py and tokenize.py) and produces a parse tree of the source code, using the nodes as found in pynodes.py. For example, given this module (x.py):: # comment '''Docstring''' '''Additional docstring''' __docformat__ = 'reStructuredText' a = 1 '''Attribute docstring''' class C(Super): '''C's docstring''' class_attribute = 1 '''class_attribute's docstring''' def __init__(self, text=None): '''__init__'s docstring''' self.instance_attribute = (text * 7 + ' whaddyaknow') '''instance_attribute's docstring''' def f(x, # parameter x y=a*5, # parameter y *args): # parameter args '''f's docstring''' return [x + item for item in args] f.function_attribute = 1 '''f.function_attribute's docstring''' The module parser will produce this module documentation tree:: <module_section filename="test data"> <docstring> Docstring <docstring lineno="5"> Additional docstring <attribute lineno="7"> <object_name> __docformat__ <expression_value lineno="7"> 'reStructuredText' <attribute lineno="9"> <object_name> a <expression_value lineno="9"> 1 <docstring lineno="10"> Attribute docstring <class_section lineno="12"> <object_name> C <class_base> Super <docstring lineno="12"> C's docstring <attribute lineno="16"> <object_name> class_attribute <expression_value lineno="16"> 1 <docstring lineno="17"> class_attribute's docstring <method_section lineno="19"> <object_name> __init__ <docstring lineno="19"> __init__'s docstring <parameter_list lineno="19"> <parameter lineno="19"> <object_name> self <parameter lineno="19"> <object_name> text <parameter_default lineno="19"> None <attribute lineno="22"> <object_name> self.instance_attribute <expression_value lineno="22"> (text * 7 + ' whaddyaknow') <docstring lineno="24"> instance_attribute's docstring <function_section lineno="27"> <object_name> f <docstring lineno="27"> f's docstring <parameter_list lineno="27"> <parameter lineno="27"> <object_name> x <comment> # parameter x <parameter lineno="27"> <object_name> y <parameter_default lineno="27"> a * 5 <comment> # parameter y <parameter excess_positional="1" lineno="27"> <object_name> args <comment> # parameter args <attribute lineno="33"> <object_name> f.function_attribute <expression_value lineno="33"> 1 <docstring lineno="34"> f.function_attribute's docstring (Comments are not implemented yet.) compiler.parse() provides most of what's needed for this doctree, and "tokenize" can be used to get the rest. We can determine the line number from the compiler.parse() AST, and the TokenParser.rhs(lineno) method provides the rest. The Docutils Python reader component will transform this module doctree into a Python-specific Docutils doctree, and then a "stylist transform" will further transform it into a generic doctree. Namespaces will have to be compiled for each of the scopes, but I'm not certain at what stage of processing. It's very important to keep all docstring processing out of this, so that it's a completely generic and not tool-specific. :: > Why perform all of those transformations? Why not go from the AST to a > generic doctree? Or, even from the AST to the final output? I want the docutils.readers.python.moduleparser.parse_module() function to produce a standard documentation-oriented tree that can be used by any tool. We can develop it together without having to compromise on the rest of our design (i.e., HappyDoc doesn't have to be made to work like Docutils, and vice-versa). It would be a higher-level version of what compiler.py provides. The Python reader component transforms this generic AST into a Python-specific doctree (it knows about modules, classes, functions, etc.), but this is specific to Docutils and cannot be used by HappyDoc or others. The stylist transform does the final layout, converting Python-specific structures ("class" sections, etc.) into a generic doctree using primitives (tables, sections, lists, etc.). This generic doctree does *not* know about Python structures any more. The advantage is that this doctree can be handed off to any of the output writers to create any output format we like. The latter two transforms are separate because I want to be able to have multiple independent layout styles (multiple runtime-selectable "stylist transforms"). Each of the existing tools (HappyDoc, pydoc, epydoc, Crystal, etc.) has its own fixed format. I personally don't like the tables-based format produced by these tools, and I'd like to be able to customize the format easily. That's the goal of stylist transforms, which are independent from the Reader component itself. One stylist transform could produce HappyDoc-like output, another could produce output similar to module docs in the Python library reference manual, and so on. It's for exactly this reason:: >> It's very important to keep all docstring processing out of this, so that >> it's a completely generic and not tool-specific. ... but it goes past docstring processing. It's also important to keep style decisions and tool-specific data transforms out of this module parser. Issues ====== * At what point should namespaces be computed? Should they be part of the basic AST produced by the ASTVisitor walk, or generated by another tree traversal? * At what point should a distinction be made between local variables & instance attributes in __init__ methods? * Docstrings are getting their lineno from their parents. Should the TokenParser find the real line no's? * Comments: include them? How and when? Only full-line comments, or parameter comments too? (See function "f" above for an example.) * Module could use more docstrings & refactoring in places. """ __docformat__ = 'reStructuredText' import sys import compiler import compiler.ast import tokenize import token from compiler.consts import OP_ASSIGN from compiler.visitor import ASTVisitor from docutils.readers.python import pynodes from docutils.nodes import Text def parse_module(module_text, filename): """Return a module documentation tree from `module_text`.""" ast = compiler.parse(module_text) token_parser = TokenParser(module_text) visitor = ModuleVisitor(filename, token_parser) compiler.walk(ast, visitor, walker=visitor) return visitor.module class BaseVisitor(ASTVisitor): def __init__(self, token_parser): ASTVisitor.__init__(self) self.token_parser = token_parser self.context = [] self.documentable = None def default(self, node, *args): self.documentable = None #print 'in default (%s)' % node.__class__.__name__ #ASTVisitor.default(self, node, *args) def default_visit(self, node, *args): #print 'in default_visit (%s)' % node.__class__.__name__ ASTVisitor.default(self, node, *args) class DocstringVisitor(BaseVisitor): def visitDiscard(self, node): if self.documentable: self.visit(node.expr) def visitConst(self, node): if self.documentable: if type(node.value) in (str, unicode): self.documentable.append(make_docstring(node.value, node.lineno)) else: self.documentable = None def visitStmt(self, node): self.default_visit(node) class AssignmentVisitor(DocstringVisitor): def visitAssign(self, node): visitor = AttributeVisitor(self.token_parser) compiler.walk(node, visitor, walker=visitor) if visitor.attributes: self.context[-1].extend(visitor.attributes) if len(visitor.attributes) == 1: self.documentable = visitor.attributes[0] else: self.documentable = None class ModuleVisitor(AssignmentVisitor): def __init__(self, filename, token_parser): AssignmentVisitor.__init__(self, token_parser) self.filename = filename self.module = None def visitModule(self, node): self.module = module = pynodes.module_section() module['filename'] = self.filename append_docstring(module, node.doc, node.lineno) self.context.append(module) self.documentable = module self.visit(node.node) self.context.pop() def visitImport(self, node): self.context[-1] += make_import_group(names=node.names, lineno=node.lineno) self.documentable = None def visitFrom(self, node): self.context[-1].append( make_import_group(names=node.names, from_name=node.modname, lineno=node.lineno)) self.documentable = None def visitFunction(self, node): visitor = FunctionVisitor(self.token_parser, function_class=pynodes.function_section) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.function) def visitClass(self, node): visitor = ClassVisitor(self.token_parser) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.klass) class AttributeVisitor(BaseVisitor): def __init__(self, token_parser): BaseVisitor.__init__(self, token_parser) self.attributes = pynodes.class_attribute_section() def visitAssign(self, node): # Don't visit the expression itself, just the attribute nodes: for child in node.nodes: self.dispatch(child) expression_text = self.token_parser.rhs(node.lineno) expression = pynodes.expression_value() expression.append(Text(expression_text)) for attribute in self.attributes: attribute.append(expression) def visitAssName(self, node): self.attributes.append(make_attribute(node.name, lineno=node.lineno)) def visitAssTuple(self, node): attributes = self.attributes self.attributes = [] self.default_visit(node) n = pynodes.attribute_tuple() n.extend(self.attributes) n['lineno'] = self.attributes[0]['lineno'] attributes.append(n) self.attributes = attributes #self.attributes.append(att_tuple) def visitAssAttr(self, node): self.default_visit(node, node.attrname) def visitGetattr(self, node, suffix): self.default_visit(node, node.attrname + '.' + suffix) def visitName(self, node, suffix): self.attributes.append(make_attribute(node.name + '.' + suffix, lineno=node.lineno)) class FunctionVisitor(DocstringVisitor): in_function = 0 def __init__(self, token_parser, function_class): DocstringVisitor.__init__(self, token_parser) self.function_class = function_class def visitFunction(self, node): if self.in_function: self.documentable = None # Don't bother with nested function definitions. return self.in_function = 1 self.function = function = make_function_like_section( name=node.name, lineno=node.lineno, doc=node.doc, function_class=self.function_class) self.context.append(function) self.documentable = function self.parse_parameter_list(node) self.visit(node.code) self.context.pop() def parse_parameter_list(self, node): parameters = [] special = [] argnames = list(node.argnames) if node.kwargs: special.append(make_parameter(argnames[-1], excess_keyword=1)) argnames.pop() if node.varargs: special.append(make_parameter(argnames[-1], excess_positional=1)) argnames.pop() defaults = list(node.defaults) defaults = [None] * (len(argnames) - len(defaults)) + defaults function_parameters = self.token_parser.function_parameters( node.lineno) #print >>sys.stderr, function_parameters for argname, default in zip(argnames, defaults): if type(argname) is tuple: parameter = pynodes.parameter_tuple() for tuplearg in argname: parameter.append(make_parameter(tuplearg)) argname = normalize_parameter_name(argname) else: parameter = make_parameter(argname) if default: n_default = pynodes.parameter_default() n_default.append(Text(function_parameters[argname])) parameter.append(n_default) parameters.append(parameter) if parameters or special: special.reverse() parameters.extend(special) parameter_list = pynodes.parameter_list() parameter_list.extend(parameters) self.function.append(parameter_list) class ClassVisitor(AssignmentVisitor): in_class = 0 def __init__(self, token_parser): AssignmentVisitor.__init__(self, token_parser) self.bases = [] def visitClass(self, node): if self.in_class: self.documentable = None # Don't bother with nested class definitions. return self.in_class = 1 #import mypdb as pdb #pdb.set_trace() for base in node.bases: self.visit(base) self.klass = klass = make_class_section(node.name, self.bases, doc=node.doc, lineno=node.lineno) self.context.append(klass) self.documentable = klass self.visit(node.code) self.context.pop() def visitGetattr(self, node, suffix=None): if suffix: name = node.attrname + '.' + suffix else: name = node.attrname self.default_visit(node, name) def visitName(self, node, suffix=None): if suffix: name = node.name + '.' + suffix else: name = node.name self.bases.append(name) def visitFunction(self, node): if node.name == '__init__': visitor = InitMethodVisitor(self.token_parser, function_class=pynodes.method_section) compiler.walk(node, visitor, walker=visitor) else: visitor = FunctionVisitor(self.token_parser, function_class=pynodes.method_section) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.function) class InitMethodVisitor(FunctionVisitor, AssignmentVisitor): pass class TokenParser: def __init__(self, text): self.text = text + '\n\n' self.lines = self.text.splitlines(1) self.generator = tokenize.generate_tokens(iter(self.lines).next) self.next() def __iter__(self): return self def next(self): self.token = self.generator.next() self.type, self.string, self.start, self.end, self.line = self.token return self.token def goto_line(self, lineno): while self.start[0] < lineno: self.next() return token def rhs(self, lineno): """ Return a whitespace-normalized expression string from the right-hand side of an assignment at line `lineno`. """ self.goto_line(lineno) while self.string != '=': self.next() self.stack = None while self.type != token.NEWLINE and self.string != ';': if self.string == '=' and not self.stack: self.tokens = [] self.stack = [] self._type = None self._string = None self._backquote = 0 else: self.note_token() self.next() self.next() text = ''.join(self.tokens) return text.strip() closers = {')': '(', ']': '[', '}': '{'} openers = {'(': 1, '[': 1, '{': 1} del_ws_prefix = {'.': 1, '=': 1, ')': 1, ']': 1, '}': 1, ':': 1, ',': 1} no_ws_suffix = {'.': 1, '=': 1, '(': 1, '[': 1, '{': 1} def note_token(self): if self.type == tokenize.NL: return del_ws = self.string in self.del_ws_prefix append_ws = self.string not in self.no_ws_suffix if self.string in self.openers: self.stack.append(self.string) if (self._type == token.NAME or self._string in self.closers): del_ws = 1 elif self.string in self.closers: assert self.stack[-1] == self.closers[self.string] self.stack.pop() elif self.string == '`': if self._backquote: del_ws = 1 assert self.stack[-1] == '`' self.stack.pop() else: append_ws = 0 self.stack.append('`') self._backquote = not self._backquote if del_ws and self.tokens and self.tokens[-1] == ' ': del self.tokens[-1] self.tokens.append(self.string) self._type = self.type self._string = self.string if append_ws: self.tokens.append(' ') def function_parameters(self, lineno): """ Return a dictionary mapping parameters to defaults (whitespace-normalized strings). """ self.goto_line(lineno) while self.string != 'def': self.next() while self.string != '(': self.next() name = None default = None parameter_tuple = None self.tokens = [] parameters = {} self.stack = [self.string] self.next() while 1: if len(self.stack) == 1: if parameter_tuple: # Just encountered ")". #print >>sys.stderr, 'parameter_tuple: %r' % self.tokens name = ''.join(self.tokens).strip() self.tokens = [] parameter_tuple = None if self.string in (')', ','): if name: if self.tokens: default_text = ''.join(self.tokens).strip() else: default_text = None parameters[name] = default_text self.tokens = [] name = None default = None if self.string == ')': break elif self.type == token.NAME: if name and default: self.note_token() else: assert name is None, ( 'token=%r name=%r parameters=%r stack=%r' % (self.token, name, parameters, self.stack)) name = self.string #print >>sys.stderr, 'name=%r' % name elif self.string == '=': assert name is not None, 'token=%r' % (self.token,) assert default is None, 'token=%r' % (self.token,) assert self.tokens == [], 'token=%r' % (self.token,) default = 1 self._type = None self._string = None self._backquote = 0 elif name: self.note_token() elif self.string == '(': parameter_tuple = 1 self._type = None self._string = None self._backquote = 0 self.note_token() else: # ignore these tokens: assert (self.string in ('*', '**', '\n') or self.type == tokenize.COMMENT), ( 'token=%r' % (self.token,)) else: self.note_token() self.next() return parameters def make_docstring(doc, lineno): n = pynodes.docstring() if lineno: # Really, only module docstrings don't have a line # (@@: but maybe they should) n['lineno'] = lineno n.append(Text(doc)) return n def append_docstring(node, doc, lineno): if doc: node.append(make_docstring(doc, lineno)) def make_class_section(name, bases, lineno, doc): n = pynodes.class_section() n['lineno'] = lineno n.append(make_object_name(name)) for base in bases: b = pynodes.class_base() b.append(make_object_name(base)) n.append(b) append_docstring(n, doc, lineno) return n def make_object_name(name): n = pynodes.object_name() n.append(Text(name)) return n def make_function_like_section(name, lineno, doc, function_class): n = function_class() n['lineno'] = lineno n.append(make_object_name(name)) append_docstring(n, doc, lineno) return n def make_import_group(names, lineno, from_name=None): n = pynodes.import_group() n['lineno'] = lineno if from_name: n_from = pynodes.import_from() n_from.append(Text(from_name)) n.append(n_from) for name, alias in names: n_name = pynodes.import_name() n_name.append(Text(name)) if alias: n_alias = pynodes.import_alias() n_alias.append(Text(alias)) n_name.append(n_alias) n.append(n_name) return n def make_class_attribute(name, lineno): n = pynodes.class_attribute() n['lineno'] = lineno n.append(Text(name)) return n def make_attribute(name, lineno): n = pynodes.attribute() n['lineno'] = lineno n.append(make_object_name(name)) return n def make_parameter(name, excess_keyword=0, excess_positional=0): """ excess_keyword and excess_positional must be either 1 or 0, and not both of them can be 1. """ n = pynodes.parameter() n.append(make_object_name(name)) assert not excess_keyword or not excess_positional if excess_keyword: n['excess_keyword'] = 1 if excess_positional: n['excess_positional'] = 1 return n def trim_docstring(text): """ Trim indentation and blank lines from docstring text & return it. See PEP 257. """ if not text: return text # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = text.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxint for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxint: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed) def normalize_parameter_name(name): """ Converts a tuple like ``('a', ('b', 'c'), 'd')`` into ``'(a, (b, c), d)'`` """ if type(name) is tuple: return '(%s)' % ', '.join([normalize_parameter_name(n) for n in name]) else: return name if __name__ == '__main__': import sys args = sys.argv[1:] if args[0] == '-v': filename = args[1] module_text = open(filename).read() ast = compiler.parse(module_text) visitor = compiler.visitor.ExampleASTVisitor() compiler.walk(ast, visitor, walker=visitor, verbose=1) else: filename = args[0] content = open(filename).read() print parse_module(content, filename).pformat()
Python
# $Id: __init__.py 5618 2008-07-28 08:37:32Z strank $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This package contains the Python Source Reader modules. """ __docformat__ = 'reStructuredText' import sys import docutils.readers from docutils.readers.python import moduleparser from docutils import parsers from docutils import nodes from docutils.readers.python import pynodes from docutils import readers class Reader(docutils.readers.Reader): config_section = 'python reader' config_section_dependencies = ('readers',) default_parser = 'restructuredtext' def parse(self): """Parse `self.input` into a document tree.""" self.document = document = self.new_document() module_section = moduleparser.parse_module(self.input, self.source.source_path) module_section.walk(DocformatVisitor(self.document)) visitor = DocstringFormattingVisitor( document=document, default_parser=self.default_parser) module_section.walk(visitor) self.document.append(module_section) class DocformatVisitor(nodes.SparseNodeVisitor): """ This sets docformat attributes in a module. Wherever an assignment to __docformat__ is found, we look for the enclosing scope -- a class, a module, or a function -- and set the docformat attribute there. We can't do this during the DocstringFormattingVisitor walking, because __docformat__ may appear below a docstring in that format (typically below the module docstring). """ def visit_attribute(self, node): assert isinstance(node[0], pynodes.object_name) name = node[0][0].data if name != '__docformat__': return value = None for child in children: if isinstance(child, pynodes.expression_value): value = child[0].data break assert value.startswith("'") or value.startswith('"'), "__docformat__ must be assigned a string literal (not %s); line: %s" % (value, node['lineno']) name = name[1:-1] looking_in = node.parent while not isinstance(looking_in, (pynodes.module_section, pynodes.function_section, pynodes.class_section)): looking_in = looking_in.parent looking_in['docformat'] = name class DocstringFormattingVisitor(nodes.SparseNodeVisitor): def __init__(self, document, default_parser): self.document = document self.default_parser = default_parser self.parsers = {} def visit_docstring(self, node): text = node[0].data docformat = self.find_docformat(node) del node[0] node['docformat'] = docformat parser = self.get_parser(docformat) parser.parse(text, self.document) for child in self.document.children: node.append(child) self.document.current_source = self.document.current_line = None del self.document[:] def get_parser(self, parser_name): """ Get a parser based on its name. We reuse parsers during this visitation, so parser instances are cached. """ parser_name = parsers._parser_aliases.get(parser_name, parser_name) if parser_name not in self.parsers: cls = parsers.get_parser_class(parser_name) self.parsers[parser_name] = cls() return self.parsers[parser_name] def find_docformat(self, node): """ Find the __docformat__ closest to this node (i.e., look in the class or module) """ while node: if node.get('docformat'): return node['docformat'] node = node.parent return self.default_parser if __name__ == '__main__': try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates pseudo-XML from Python modules ' '(for testing purposes). ' + default_description) publish_cmdline(description=description, reader=Reader())
Python
# $Id: pep.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Python Enhancement Proposal (PEP) Reader. """ __docformat__ = 'reStructuredText' from docutils.readers import standalone from docutils.transforms import peps, references, misc, frontmatter from docutils.parsers import rst class Reader(standalone.Reader): supported = ('pep',) """Contexts this reader supports.""" settings_spec = ( 'PEP Reader Option Defaults', 'The --pep-references and --rfc-references options (for the ' 'reStructuredText parser) are on by default.', ()) config_section = 'pep reader' config_section_dependencies = ('readers', 'standalone reader') def get_transforms(self): transforms = standalone.Reader.get_transforms(self) # We have PEP-specific frontmatter handling. transforms.remove(frontmatter.DocTitle) transforms.remove(frontmatter.SectionSubTitle) transforms.remove(frontmatter.DocInfo) transforms.extend([peps.Headers, peps.Contents, peps.TargetNotes]) return transforms settings_default_overrides = {'pep_references': 1, 'rfc_references': 1} inliner_class = rst.states.Inliner def __init__(self, parser=None, parser_name=None): """`parser` should be ``None``.""" if parser is None: parser = rst.Parser(rfc2822=1, inliner=self.inliner_class()) standalone.Reader.__init__(self, parser, '')
Python
# $Id: __init__.py 5618 2008-07-28 08:37:32Z strank $ # Authors: David Goodger <goodger@python.org>; Ueli Schlaepfer # Copyright: This module has been placed in the public domain. """ This package contains Docutils Reader modules. """ __docformat__ = 'reStructuredText' from docutils import utils, parsers, Component from docutils.transforms import universal class Reader(Component): """ Abstract base class for docutils Readers. Each reader module or package must export a subclass also called 'Reader'. The two steps of a Reader's responsibility are `scan()` and `parse()`. Call `read()` to process a document. """ component_type = 'reader' config_section = 'readers' def get_transforms(self): return Component.get_transforms(self) + [ universal.Decorations, universal.ExposeInternals, universal.StripComments,] def __init__(self, parser=None, parser_name=None): """ Initialize the Reader instance. Several instance attributes are defined with dummy initial values. Subclasses may use these attributes as they wish. """ self.parser = parser """A `parsers.Parser` instance shared by all doctrees. May be left unspecified if the document source determines the parser.""" if parser is None and parser_name: self.set_parser(parser_name) self.source = None """`docutils.io` IO object, source of input data.""" self.input = None """Raw text input; either a single string or, for more complex cases, a collection of strings.""" def set_parser(self, parser_name): """Set `self.parser` by name.""" parser_class = parsers.get_parser_class(parser_name) self.parser = parser_class() def read(self, source, parser, settings): self.source = source if not self.parser: self.parser = parser self.settings = settings self.input = self.source.read() self.parse() return self.document def parse(self): """Parse `self.input` into a document tree.""" self.document = document = self.new_document() self.parser.parse(self.input, document) document.current_source = document.current_line = None def new_document(self): """Create and return a new empty document tree (root node).""" document = utils.new_document(self.source.source_path, self.settings) return document class ReReader(Reader): """ A reader which rereads an existing document tree (e.g. a deserializer). Often used in conjunction with `writers.UnfilteredWriter`. """ def get_transforms(self): # Do not add any transforms. They have already been applied # by the reader which originally created the document. return Component.get_transforms(self) _reader_aliases = {} def get_reader_class(reader_name): """Return the Reader class from the `reader_name` module.""" reader_name = reader_name.lower() if reader_name in _reader_aliases: reader_name = _reader_aliases[reader_name] module = __import__(reader_name, globals(), locals()) return module.Reader
Python
# $Id: standalone.py 4802 2006-11-12 18:02:17Z goodger $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Standalone file Reader for the reStructuredText markup syntax. """ __docformat__ = 'reStructuredText' import sys from docutils import frontend, readers from docutils.transforms import frontmatter, references, misc class Reader(readers.Reader): supported = ('standalone',) """Contexts this reader supports.""" document = None """A single document tree.""" settings_spec = ( 'Standalone Reader', None, (('Disable the promotion of a lone top-level section title to ' 'document title (and subsequent section title to document ' 'subtitle promotion; enabled by default).', ['--no-doc-title'], {'dest': 'doctitle_xform', 'action': 'store_false', 'default': 1, 'validator': frontend.validate_boolean}), ('Disable the bibliographic field list transform (enabled by ' 'default).', ['--no-doc-info'], {'dest': 'docinfo_xform', 'action': 'store_false', 'default': 1, 'validator': frontend.validate_boolean}), ('Activate the promotion of lone subsection titles to ' 'section subtitles (disabled by default).', ['--section-subtitles'], {'dest': 'sectsubtitle_xform', 'action': 'store_true', 'default': 0, 'validator': frontend.validate_boolean}), ('Deactivate the promotion of lone subsection titles.', ['--no-section-subtitles'], {'dest': 'sectsubtitle_xform', 'action': 'store_false'}), )) config_section = 'standalone reader' config_section_dependencies = ('readers',) def get_transforms(self): return readers.Reader.get_transforms(self) + [ references.Substitutions, references.PropagateTargets, frontmatter.DocTitle, frontmatter.SectionSubTitle, frontmatter.DocInfo, references.AnonymousHyperlinks, references.IndirectHyperlinks, references.Footnotes, references.ExternalTargets, references.InternalTargets, references.DanglingReferences, misc.Transitions, ]
Python
# $Id: __init__.py 6354 2010-07-07 09:04:56Z grubert $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This is the Docutils (Python Documentation Utilities) package. Package Structure ================= Modules: - __init__.py: Contains component base classes, exception classes, and Docutils version information. - core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience functions. - frontend.py: Runtime settings (command-line interface, configuration files) processing, for Docutils front-ends. - io.py: Provides a uniform API for low-level input and output. - nodes.py: Docutils document tree (doctree) node class library. - statemachine.py: A finite state machine specialized for regular-expression-based text filters. - urischemes.py: Contains a complete mapping of known URI addressing scheme names to descriptions. - utils.py: Contains the ``Reporter`` system warning class and miscellaneous utilities. Subpackages: - languages: Language-specific mappings of terms. - parsers: Syntax-specific input parser modules or packages. - readers: Context-specific input handlers which understand the data source and manage a parser. - transforms: Modules used by readers and writers to modify DPS doctrees. - writers: Format-specific output translators. """ __docformat__ = 'reStructuredText' __version__ = '0.7' """``major.minor.micro`` version number. The micro number is bumped for API changes, for new functionality, and for interim project releases. The minor number is bumped whenever there is a significant project release. The major number will be bumped when the project is feature-complete, and perhaps if there is a major change in the design.""" __version_details__ = 'release' """Extra version details (e.g. 'snapshot 2005-05-29, r3410', 'repository', 'release'), modified automatically & manually.""" class ApplicationError(StandardError): pass class DataError(ApplicationError): pass class SettingsSpec: """ Runtime setting specification base class. SettingsSpec subclass objects used by `docutils.frontend.OptionParser`. """ settings_spec = () """Runtime settings specification. Override in subclasses. Defines runtime settings and associated command-line options, as used by `docutils.frontend.OptionParser`. This is a tuple of: - Option group title (string or `None` which implies no group, just a list of single options). - Description (string or `None`). - A sequence of option tuples. Each consists of: - Help text (string) - List of option strings (e.g. ``['-Q', '--quux']``). - Dictionary of keyword arguments sent to the OptionParser/OptionGroup ``add_option`` method. Runtime setting names are derived implicitly from long option names ('--a-setting' becomes ``settings.a_setting``) or explicitly from the 'dest' keyword argument. Most settings will also have a 'validator' keyword & function. The validator function validates setting values (from configuration files and command-line option arguments) and converts them to appropriate types. For example, the ``docutils.frontend.validate_boolean`` function, **required by all boolean settings**, converts true values ('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off', 'no', 'false', and '') to 0. Validators need only be set once per setting. See the `docutils.frontend.validate_*` functions. See the optparse docs for more details. - More triples of group title, description, options, as many times as needed. Thus, `settings_spec` tuples can be simply concatenated. """ settings_defaults = None """A dictionary of defaults for settings not in `settings_spec` (internal settings, intended to be inaccessible by command-line and config file). Override in subclasses.""" settings_default_overrides = None """A dictionary of auxiliary defaults, to override defaults for settings defined in other components. Override in subclasses.""" relative_path_settings = () """Settings containing filesystem paths. Override in subclasses. Settings listed here are to be interpreted relative to the current working directory.""" config_section = None """The name of the config file section specific to this component (lowercase, no brackets). Override in subclasses.""" config_section_dependencies = None """A list of names of config file sections that are to be applied before `config_section`, in order (from general to specific). In other words, the settings in `config_section` are to be overlaid on top of the settings from these sections. The "general" section is assumed implicitly. Override in subclasses.""" class TransformSpec: """ Runtime transform specification base class. TransformSpec subclass objects used by `docutils.transforms.Transformer`. """ def get_transforms(self): """Transforms required by this class. Override in subclasses.""" if self.default_transforms != (): import warnings warnings.warn('default_transforms attribute deprecated.\n' 'Use get_transforms() method instead.', DeprecationWarning) return list(self.default_transforms) return [] # Deprecated; for compatibility. default_transforms = () unknown_reference_resolvers = () """List of functions to try to resolve unknown references. Unknown references have a 'refname' attribute which doesn't correspond to any target in the document. Called when the transforms in `docutils.tranforms.references` are unable to find a correct target. The list should contain functions which will try to resolve unknown references, with the following signature:: def reference_resolver(node): '''Returns boolean: true if resolved, false if not.''' If the function is able to resolve the reference, it should also remove the 'refname' attribute and mark the node as resolved:: del node['refname'] node.resolved = 1 Each function must have a "priority" attribute which will affect the order the unknown_reference_resolvers are run:: reference_resolver.priority = 100 Override in subclasses.""" class Component(SettingsSpec, TransformSpec): """Base class for Docutils components.""" component_type = None """Name of the component type ('reader', 'parser', 'writer'). Override in subclasses.""" supported = () """Names for this component. Override in subclasses.""" def supports(self, format): """ Is `format` supported by this component? To be used by transforms to ask the dependent component if it supports a certain input context or output format. """ return format in self.supported
Python
# $Id: frontend.py 6205 2009-11-30 08:11:08Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Command-line and common processing for Docutils front-end tools. Exports the following classes: * `OptionParser`: Standard Docutils command-line processing. * `Option`: Customized version of `optparse.Option`; validation support. * `Values`: Runtime settings; objects are simple structs (``object.attribute``). Supports cumulative list settings (attributes). * `ConfigParser`: Standard Docutils config file processing. Also exports the following functions: * Option callbacks: `store_multiple`, `read_config_file`. * Setting validators: `validate_encoding`, `validate_encoding_error_handler`, `validate_encoding_and_error_handler`, `validate_boolean`, `validate_threshold`, `validate_colon_separated_string_list`, `validate_dependency_file`. * `make_paths_absolute`. * SettingSpec manipulation: `filter_settings_spec`. """ __docformat__ = 'reStructuredText' import os import os.path import sys import warnings import ConfigParser as CP import codecs import docutils import docutils.utils import docutils.nodes import optparse from optparse import SUPPRESS_HELP def store_multiple(option, opt, value, parser, *args, **kwargs): """ Store multiple values in `parser.values`. (Option callback.) Store `None` for each attribute named in `args`, and store the value for each key (attribute name) in `kwargs`. """ for attribute in args: setattr(parser.values, attribute, None) for key, value in kwargs.items(): setattr(parser.values, key, value) def read_config_file(option, opt, value, parser): """ Read a configuration file during option processing. (Option callback.) """ try: new_settings = parser.get_config_file_settings(value) except ValueError, error: parser.error(error) parser.values.update(new_settings, parser) def validate_encoding(setting, value, option_parser, config_parser=None, config_section=None): try: codecs.lookup(value) except LookupError: raise (LookupError('setting "%s": unknown encoding: "%s"' % (setting, value)), None, sys.exc_info()[2]) return value def validate_encoding_error_handler(setting, value, option_parser, config_parser=None, config_section=None): try: codecs.lookup_error(value) except AttributeError: # TODO: remove (only needed prior to Python 2.3) if value not in ('strict', 'ignore', 'replace', 'xmlcharrefreplace'): raise (LookupError( 'unknown encoding error handler: "%s" (choices: ' '"strict", "ignore", "replace", or "xmlcharrefreplace")' % value), None, sys.exc_info()[2]) except LookupError: raise (LookupError( 'unknown encoding error handler: "%s" (choices: ' '"strict", "ignore", "replace", "backslashreplace", ' '"xmlcharrefreplace", and possibly others; see documentation for ' 'the Python ``codecs`` module)' % value), None, sys.exc_info()[2]) return value def validate_encoding_and_error_handler( setting, value, option_parser, config_parser=None, config_section=None): """ Side-effect: if an error handler is included in the value, it is inserted into the appropriate place as if it was a separate setting/option. """ if ':' in value: encoding, handler = value.split(':') validate_encoding_error_handler( setting + '_error_handler', handler, option_parser, config_parser, config_section) if config_parser: config_parser.set(config_section, setting + '_error_handler', handler) else: setattr(option_parser.values, setting + '_error_handler', handler) else: encoding = value validate_encoding(setting, encoding, option_parser, config_parser, config_section) return encoding def validate_boolean(setting, value, option_parser, config_parser=None, config_section=None): if isinstance(value, unicode): try: return option_parser.booleans[value.strip().lower()] except KeyError: raise (LookupError('unknown boolean value: "%s"' % value), None, sys.exc_info()[2]) return value def validate_nonnegative_int(setting, value, option_parser, config_parser=None, config_section=None): value = int(value) if value < 0: raise ValueError('negative value; must be positive or zero') return value def validate_threshold(setting, value, option_parser, config_parser=None, config_section=None): try: return int(value) except ValueError: try: return option_parser.thresholds[value.lower()] except (KeyError, AttributeError): raise (LookupError('unknown threshold: %r.' % value), None, sys.exc_info[2]) def validate_colon_separated_string_list( setting, value, option_parser, config_parser=None, config_section=None): if isinstance(value, unicode): value = value.split(':') else: last = value.pop() value.extend(last.split(':')) return value def validate_url_trailing_slash( setting, value, option_parser, config_parser=None, config_section=None): if not value: return './' elif value.endswith('/'): return value else: return value + '/' def validate_dependency_file(setting, value, option_parser, config_parser=None, config_section=None): try: return docutils.utils.DependencyList(value) except IOError: return docutils.utils.DependencyList(None) def validate_strip_class(setting, value, option_parser, config_parser=None, config_section=None): if config_parser: # validate all values class_values = value else: # just validate the latest value class_values = [value[-1]] for class_value in class_values: normalized = docutils.nodes.make_id(class_value) if class_value != normalized: raise ValueError('invalid class value %r (perhaps %r?)' % (class_value, normalized)) return value def make_paths_absolute(pathdict, keys, base_path=None): """ Interpret filesystem path settings relative to the `base_path` given. Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from `OptionParser.relative_path_settings`. """ if base_path is None: base_path = os.getcwd() for key in keys: if key in pathdict: value = pathdict[key] if isinstance(value, list): value = [make_one_path_absolute(base_path, path) for path in value] elif value: value = make_one_path_absolute(base_path, value) pathdict[key] = value def make_one_path_absolute(base_path, path): return os.path.abspath(os.path.join(base_path, path)) def filter_settings_spec(settings_spec, *exclude, **replace): """Return a copy of `settings_spec` excluding/replacing some settings. `settings_spec` is a tuple of configuration settings with a structure described for docutils.SettingsSpec.settings_spec. Optional positional arguments are names of to-be-excluded settings. Keyword arguments are option specification replacements. (See the html4strict writer for an example.) """ settings = list(settings_spec) # every third item is a sequence of option tuples for i in range(2, len(settings), 3): newopts = [] for opt_spec in settings[i]: # opt_spec is ("<help>", [<option strings>], {<keyword args>}) opt_name = [opt_string[2:].replace('-', '_') for opt_string in opt_spec[1] if opt_string.startswith('--') ][0] if opt_name in exclude: continue if opt_name in replace.keys(): newopts.append(replace[opt_name]) else: newopts.append(opt_spec) settings[i] = tuple(newopts) return tuple(settings) class Values(optparse.Values): """ Updates list attributes by extension rather than by replacement. Works in conjunction with the `OptionParser.lists` instance attribute. """ def __init__(self, *args, **kwargs): optparse.Values.__init__(self, *args, **kwargs) if (not hasattr(self, 'record_dependencies') or self.record_dependencies is None): # Set up dependency list, in case it is needed. self.record_dependencies = docutils.utils.DependencyList() def update(self, other_dict, option_parser): if isinstance(other_dict, Values): other_dict = other_dict.__dict__ other_dict = other_dict.copy() for setting in option_parser.lists.keys(): if (hasattr(self, setting) and setting in other_dict): value = getattr(self, setting) if value: value += other_dict[setting] del other_dict[setting] self._update_loose(other_dict) def copy(self): """Return a shallow copy of `self`.""" return self.__class__(defaults=self.__dict__) class Option(optparse.Option): ATTRS = optparse.Option.ATTRS + ['validator', 'overrides'] def process(self, opt, value, values, parser): """ Call the validator function on applicable settings and evaluate the 'overrides' option. Extends `optparse.Option.process`. """ result = optparse.Option.process(self, opt, value, values, parser) setting = self.dest if setting: if self.validator: value = getattr(values, setting) try: new_value = self.validator(setting, value, parser) except Exception, error: raise (optparse.OptionValueError( 'Error in option "%s":\n %s: %s' % (opt, error.__class__.__name__, error)), None, sys.exc_info()[2]) setattr(values, setting, new_value) if self.overrides: setattr(values, self.overrides, None) return result class OptionParser(optparse.OptionParser, docutils.SettingsSpec): """ Parser for command-line and library use. The `settings_spec` specification here and in other Docutils components are merged to build the set of command-line options and runtime settings for this process. Common settings (defined below) and component-specific settings must not conflict. Short options are reserved for common settings, and components are restrict to using long options. """ standard_config_files = [ '/etc/docutils.conf', # system-wide './docutils.conf', # project-specific '~/.docutils'] # user-specific """Docutils configuration files, using ConfigParser syntax. Filenames will be tilde-expanded later. Later files override earlier ones.""" threshold_choices = 'info 1 warning 2 error 3 severe 4 none 5'.split() """Possible inputs for for --report and --halt threshold values.""" thresholds = {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5} """Lookup table for --report and --halt threshold values.""" booleans={'1': 1, 'on': 1, 'yes': 1, 'true': 1, '0': 0, 'off': 0, 'no': 0, 'false': 0, '': 0} """Lookup table for boolean configuration file settings.""" try: default_error_encoding = sys.stderr.encoding or 'ascii' except AttributeError: default_error_encoding = 'ascii' default_error_encoding_error_handler = 'backslashreplace' settings_spec = ( 'General Docutils Options', None, (('Specify the document title as metadata.', ['--title'], {}), ('Include a "Generated by Docutils" credit and link.', ['--generator', '-g'], {'action': 'store_true', 'validator': validate_boolean}), ('Do not include a generator credit.', ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}), ('Include the date at the end of the document (UTC).', ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d', 'dest': 'datestamp'}), ('Include the time & date (UTC).', ['--time', '-t'], {'action': 'store_const', 'const': '%Y-%m-%d %H:%M UTC', 'dest': 'datestamp'}), ('Do not include a datestamp of any kind.', ['--no-datestamp'], {'action': 'store_const', 'const': None, 'dest': 'datestamp'}), ('Include a "View document source" link.', ['--source-link', '-s'], {'action': 'store_true', 'validator': validate_boolean}), ('Use <URL> for a source link; implies --source-link.', ['--source-url'], {'metavar': '<URL>'}), ('Do not include a "View document source" link.', ['--no-source-link'], {'action': 'callback', 'callback': store_multiple, 'callback_args': ('source_link', 'source_url')}), ('Link from section headers to TOC entries. (default)', ['--toc-entry-backlinks'], {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry', 'default': 'entry'}), ('Link from section headers to the top of the TOC.', ['--toc-top-backlinks'], {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}), ('Disable backlinks to the table of contents.', ['--no-toc-backlinks'], {'dest': 'toc_backlinks', 'action': 'store_false'}), ('Link from footnotes/citations to references. (default)', ['--footnote-backlinks'], {'action': 'store_true', 'default': 1, 'validator': validate_boolean}), ('Disable backlinks from footnotes and citations.', ['--no-footnote-backlinks'], {'dest': 'footnote_backlinks', 'action': 'store_false'}), ('Enable section numbering by Docutils. (default)', ['--section-numbering'], {'action': 'store_true', 'dest': 'sectnum_xform', 'default': 1, 'validator': validate_boolean}), ('Disable section numbering by Docutils.', ['--no-section-numbering'], {'action': 'store_false', 'dest': 'sectnum_xform'}), ('Remove comment elements from the document tree.', ['--strip-comments'], {'action': 'store_true', 'validator': validate_boolean}), ('Leave comment elements in the document tree. (default)', ['--leave-comments'], {'action': 'store_false', 'dest': 'strip_comments'}), ('Remove all elements with classes="<class>" from the document tree. ' 'Warning: potentially dangerous; use with caution. ' '(Multiple-use option.)', ['--strip-elements-with-class'], {'action': 'append', 'dest': 'strip_elements_with_classes', 'metavar': '<class>', 'validator': validate_strip_class}), ('Remove all classes="<class>" attributes from elements in the ' 'document tree. Warning: potentially dangerous; use with caution. ' '(Multiple-use option.)', ['--strip-class'], {'action': 'append', 'dest': 'strip_classes', 'metavar': '<class>', 'validator': validate_strip_class}), ('Report system messages at or higher than <level>: "info" or "1", ' '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"', ['--report', '-r'], {'choices': threshold_choices, 'default': 2, 'dest': 'report_level', 'metavar': '<level>', 'validator': validate_threshold}), ('Report all system messages. (Same as "--report=1".)', ['--verbose', '-v'], {'action': 'store_const', 'const': 1, 'dest': 'report_level'}), ('Report no system messages. (Same as "--report=5".)', ['--quiet', '-q'], {'action': 'store_const', 'const': 5, 'dest': 'report_level'}), ('Halt execution at system messages at or above <level>. ' 'Levels as in --report. Default: 4 (severe).', ['--halt'], {'choices': threshold_choices, 'dest': 'halt_level', 'default': 4, 'metavar': '<level>', 'validator': validate_threshold}), ('Halt at the slightest problem. Same as "--halt=info".', ['--strict'], {'action': 'store_const', 'const': 1, 'dest': 'halt_level'}), ('Enable a non-zero exit status for non-halting system messages at ' 'or above <level>. Default: 5 (disabled).', ['--exit-status'], {'choices': threshold_choices, 'dest': 'exit_status_level', 'default': 5, 'metavar': '<level>', 'validator': validate_threshold}), ('Enable debug-level system messages and diagnostics.', ['--debug'], {'action': 'store_true', 'validator': validate_boolean}), ('Disable debug output. (default)', ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}), ('Send the output of system messages to <file>.', ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}), ('Enable Python tracebacks when Docutils is halted.', ['--traceback'], {'action': 'store_true', 'default': None, 'validator': validate_boolean}), ('Disable Python tracebacks. (default)', ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}), ('Specify the encoding and optionally the ' 'error handler of input text. Default: <locale-dependent>:strict.', ['--input-encoding', '-i'], {'metavar': '<name[:handler]>', 'validator': validate_encoding_and_error_handler}), ('Specify the error handler for undecodable characters. ' 'Choices: "strict" (default), "ignore", and "replace".', ['--input-encoding-error-handler'], {'default': 'strict', 'validator': validate_encoding_error_handler}), ('Specify the text encoding and optionally the error handler for ' 'output. Default: UTF-8:strict.', ['--output-encoding', '-o'], {'metavar': '<name[:handler]>', 'default': 'utf-8', 'validator': validate_encoding_and_error_handler}), ('Specify error handler for unencodable output characters; ' '"strict" (default), "ignore", "replace", ' '"xmlcharrefreplace", "backslashreplace".', ['--output-encoding-error-handler'], {'default': 'strict', 'validator': validate_encoding_error_handler}), ('Specify text encoding and error handler for error output. ' 'Default: %s:%s.' % (default_error_encoding, default_error_encoding_error_handler), ['--error-encoding', '-e'], {'metavar': '<name[:handler]>', 'default': default_error_encoding, 'validator': validate_encoding_and_error_handler}), ('Specify the error handler for unencodable characters in ' 'error output. Default: %s.' % default_error_encoding_error_handler, ['--error-encoding-error-handler'], {'default': default_error_encoding_error_handler, 'validator': validate_encoding_error_handler}), ('Specify the language (as 2-letter code). Default: en.', ['--language', '-l'], {'dest': 'language_code', 'default': 'en', 'metavar': '<name>'}), ('Write output file dependencies to <file>.', ['--record-dependencies'], {'metavar': '<file>', 'validator': validate_dependency_file, 'default': None}), # default set in Values class ('Read configuration settings from <file>, if it exists.', ['--config'], {'metavar': '<file>', 'type': 'string', 'action': 'callback', 'callback': read_config_file}), ("Show this program's version number and exit.", ['--version', '-V'], {'action': 'version'}), ('Show this help message and exit.', ['--help', '-h'], {'action': 'help'}), # Typically not useful for non-programmatical use: (SUPPRESS_HELP, ['--id-prefix'], {'default': ''}), (SUPPRESS_HELP, ['--auto-id-prefix'], {'default': 'id'}), # Hidden options, for development use only: (SUPPRESS_HELP, ['--dump-settings'], {'action': 'store_true'}), (SUPPRESS_HELP, ['--dump-internals'], {'action': 'store_true'}), (SUPPRESS_HELP, ['--dump-transforms'], {'action': 'store_true'}), (SUPPRESS_HELP, ['--dump-pseudo-xml'], {'action': 'store_true'}), (SUPPRESS_HELP, ['--expose-internal-attribute'], {'action': 'append', 'dest': 'expose_internals', 'validator': validate_colon_separated_string_list}), (SUPPRESS_HELP, ['--strict-visitor'], {'action': 'store_true'}), )) """Runtime settings and command-line options common to all Docutils front ends. Setting specs specific to individual Docutils components are also used (see `populate_from_components()`).""" settings_defaults = {'_disable_config': None, '_source': None, '_destination': None, '_config_files': None} """Defaults for settings that don't have command-line option equivalents.""" relative_path_settings = ('warning_stream',) config_section = 'general' version_template = ('%%prog (Docutils %s [%s], Python %s, on %s)' % (docutils.__version__, docutils.__version_details__, sys.version.split()[0], sys.platform)) """Default version message.""" def __init__(self, components=(), defaults=None, read_config_files=None, *args, **kwargs): """ `components` is a list of Docutils components each containing a ``.settings_spec`` attribute. `defaults` is a mapping of setting default overrides. """ self.lists = {} """Set of list-type settings.""" self.config_files = [] """List of paths of applied configuration files.""" optparse.OptionParser.__init__( self, option_class=Option, add_help_option=None, formatter=optparse.TitledHelpFormatter(width=78), *args, **kwargs) if not self.version: self.version = self.version_template # Make an instance copy (it will be modified): self.relative_path_settings = list(self.relative_path_settings) self.components = (self,) + tuple(components) self.populate_from_components(self.components) self.set_defaults_from_dict(defaults or {}) if read_config_files and not self.defaults['_disable_config']: try: config_settings = self.get_standard_config_settings() except ValueError, error: self.error(error) self.set_defaults_from_dict(config_settings.__dict__) def populate_from_components(self, components): """ For each component, first populate from the `SettingsSpec.settings_spec` structure, then from the `SettingsSpec.settings_defaults` dictionary. After all components have been processed, check for and populate from each component's `SettingsSpec.settings_default_overrides` dictionary. """ for component in components: if component is None: continue settings_spec = component.settings_spec self.relative_path_settings.extend( component.relative_path_settings) for i in range(0, len(settings_spec), 3): title, description, option_spec = settings_spec[i:i+3] if title: group = optparse.OptionGroup(self, title, description) self.add_option_group(group) else: group = self # single options for (help_text, option_strings, kwargs) in option_spec: option = group.add_option(help=help_text, *option_strings, **kwargs) if kwargs.get('action') == 'append': self.lists[option.dest] = 1 if component.settings_defaults: self.defaults.update(component.settings_defaults) for component in components: if component and component.settings_default_overrides: self.defaults.update(component.settings_default_overrides) def get_standard_config_files(self): """Return list of config files, from environment or standard.""" try: config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep) except KeyError: config_files = self.standard_config_files # If 'HOME' is not set, expandvars() requires the 'pwd' module which is # not available under certain environments, for example, within # mod_python. The publisher ends up in here, and we need to publish # from within mod_python. Therefore we need to avoid expanding when we # are in those environments. expand = os.path.expanduser if 'HOME' not in os.environ: try: import pwd except ImportError: expand = lambda x: x return [expand(f) for f in config_files if f.strip()] def get_standard_config_settings(self): settings = Values() for filename in self.get_standard_config_files(): settings.update(self.get_config_file_settings(filename), self) return settings def get_config_file_settings(self, config_file): """Returns a dictionary containing appropriate config file settings.""" parser = ConfigParser() parser.read(config_file, self) self.config_files.extend(parser._files) base_path = os.path.dirname(config_file) applied = {} settings = Values() for component in self.components: if not component: continue for section in (tuple(component.config_section_dependencies or ()) + (component.config_section,)): if section in applied: continue applied[section] = 1 settings.update(parser.get_section(section), self) make_paths_absolute( settings.__dict__, self.relative_path_settings, base_path) return settings.__dict__ def check_values(self, values, args): """Store positional arguments as runtime settings.""" values._source, values._destination = self.check_args(args) make_paths_absolute(values.__dict__, self.relative_path_settings, os.getcwd()) values._config_files = self.config_files return values def check_args(self, args): source = destination = None if args: source = args.pop(0) if source == '-': # means stdin source = None if args: destination = args.pop(0) if destination == '-': # means stdout destination = None if args: self.error('Maximum 2 arguments allowed.') if source and source == destination: self.error('Do not specify the same file for both source and ' 'destination. It will clobber the source file.') return source, destination def set_defaults_from_dict(self, defaults): self.defaults.update(defaults) def get_default_values(self): """Needed to get custom `Values` instances.""" defaults = Values(self.defaults) defaults._config_files = self.config_files return defaults def get_option_by_dest(self, dest): """ Get an option by its dest. If you're supplying a dest which is shared by several options, it is undefined which option of those is returned. A KeyError is raised if there is no option with the supplied dest. """ for group in self.option_groups + [self]: for option in group.option_list: if option.dest == dest: return option raise KeyError('No option with dest == %r.' % dest) class ConfigParser(CP.ConfigParser): old_settings = { 'pep_stylesheet': ('pep_html writer', 'stylesheet'), 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'), 'pep_template': ('pep_html writer', 'template')} """{old setting: (new section, new setting)} mapping, used by `handle_old_config`, to convert settings from the old [options] section.""" old_warning = """ The "[option]" section is deprecated. Support for old-format configuration files may be removed in a future Docutils release. Please revise your configuration files. See <http://docutils.sf.net/docs/user/config.html>, section "Old-Format Configuration Files". """ not_utf8_error = """\ Unable to read configuration file "%s": content not encoded as UTF-8. Skipping "%s" configuration file. """ def __init__(self, *args, **kwargs): CP.ConfigParser.__init__(self, *args, **kwargs) self._files = [] """List of paths of configuration files read.""" def read(self, filenames, option_parser): if type(filenames) in (str, unicode): filenames = [filenames] for filename in filenames: try: # Config files must be UTF-8-encoded: fp = codecs.open(filename, 'r', 'utf-8') except IOError: continue try: CP.ConfigParser.readfp(self, fp, filename) except UnicodeDecodeError: sys.stderr.write(self.not_utf8_error % (filename, filename)) fp.close() continue fp.close() self._files.append(filename) if self.has_section('options'): self.handle_old_config(filename) self.validate_settings(filename, option_parser) def handle_old_config(self, filename): warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning, filename, 0) options = self.get_section('options') if not self.has_section('general'): self.add_section('general') for key, value in options.items(): if key in self.old_settings: section, setting = self.old_settings[key] if not self.has_section(section): self.add_section(section) else: section = 'general' setting = key if not self.has_option(section, setting): self.set(section, setting, value) self.remove_section('options') def validate_settings(self, filename, option_parser): """ Call the validator function and implement overrides on all applicable settings. """ for section in self.sections(): for setting in self.options(section): try: option = option_parser.get_option_by_dest(setting) except KeyError: continue if option.validator: value = self.get(section, setting, raw=1) try: new_value = option.validator( setting, value, option_parser, config_parser=self, config_section=section) except Exception, error: raise (ValueError( 'Error in config file "%s", section "[%s]":\n' ' %s: %s\n %s = %s' % (filename, section, error.__class__.__name__, error, setting, value)), None, sys.exc_info()[2]) self.set(section, setting, new_value) if option.overrides: self.set(section, option.overrides, None) def optionxform(self, optionstr): """ Transform '-' to '_' so the cmdline form of option names can be used. """ return optionstr.lower().replace('-', '_') def get_section(self, section): """ Return a given section as a dictionary (empty if the section doesn't exist). """ section_dict = {} if self.has_section(section): for option in self.options(section): section_dict[option] = self.get(section, option, raw=1) return section_dict class ConfigDeprecationWarning(DeprecationWarning): """Warning for deprecated configuration file features."""
Python
# $Id: null.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Martin Blais <blais@furius.ca> # Copyright: This module has been placed in the public domain. """A do-nothing parser.""" from docutils import parsers class Parser(parsers.Parser): """A do-nothing parser.""" supported = ('null',) config_section = 'null parser' config_section_dependencies = ('parsers',) def parse(self, inputstring, document): pass
Python
# $Id: roles.py 6121 2009-09-10 12:05:04Z milde $ # Author: Edward Loper <edloper@gradient.cis.upenn.edu> # Copyright: This module has been placed in the public domain. """ This module defines standard interpreted text role functions, a registry for interpreted text roles, and an API for adding to and retrieving from the registry. The interface for interpreted role functions is as follows:: def role_fn(name, rawtext, text, lineno, inliner, options={}, content=[]): code... # Set function attributes for customization: role_fn.options = ... role_fn.content = ... Parameters: - ``name`` is the local name of the interpreted text role, the role name actually used in the document. - ``rawtext`` is a string containing the entire interpreted text construct. Return it as a ``problematic`` node linked to a system message if there is a problem. - ``text`` is the interpreted text content, with backslash escapes converted to nulls (``\x00``). - ``lineno`` is the line number where the interpreted text beings. - ``inliner`` is the Inliner object that called the role function. It defines the following useful attributes: ``reporter``, ``problematic``, ``memo``, ``parent``, ``document``. - ``options``: A dictionary of directive options for customization, to be interpreted by the role function. Used for additional attributes for the generated elements and other functionality. - ``content``: A list of strings, the directive content for customization ("role" directive). To be interpreted by the role function. Function attributes for customization, interpreted by the "role" directive: - ``options``: A dictionary, mapping known option names to conversion functions such as `int` or `float`. ``None`` or an empty dict implies no options to parse. Several directive option conversion functions are defined in the `directives` module. All role functions implicitly support the "class" option, unless disabled with an explicit ``{'class': None}``. - ``content``: A boolean; true if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Note that unlike directives, the "arguments" function attribute is not supported for role customization. Directive arguments are handled by the "role" directive itself. Interpreted role functions return a tuple of two values: - A list of nodes which will be inserted into the document tree at the point where the interpreted role was encountered (can be an empty list). - A list of system messages, which will be inserted into the document tree immediately after the end of the current inline block (can also be empty). """ __docformat__ = 'reStructuredText' from docutils import nodes, utils from docutils.parsers.rst import directives from docutils.parsers.rst.languages import en as _fallback_language_module DEFAULT_INTERPRETED_ROLE = 'title-reference' """ The canonical name of the default interpreted role. This role is used when no role is specified for a piece of interpreted text. """ _role_registry = {} """Mapping of canonical role names to role functions. Language-dependent role names are defined in the ``language`` subpackage.""" _roles = {} """Mapping of local or language-dependent interpreted text role names to role functions.""" def role(role_name, language_module, lineno, reporter): """ Locate and return a role function from its language-dependent name, along with a list of system messages. If the role is not found in the current language, check English. Return a 2-tuple: role function (``None`` if the named role cannot be found) and a list of system messages. """ normname = role_name.lower() messages = [] msg_text = [] if normname in _roles: return _roles[normname], messages if role_name: canonicalname = None try: canonicalname = language_module.roles[normname] except AttributeError, error: msg_text.append('Problem retrieving role entry from language ' 'module %r: %s.' % (language_module, error)) except KeyError: msg_text.append('No role entry for "%s" in module "%s".' % (role_name, language_module.__name__)) else: canonicalname = DEFAULT_INTERPRETED_ROLE # If we didn't find it, try English as a fallback. if not canonicalname: try: canonicalname = _fallback_language_module.roles[normname] msg_text.append('Using English fallback for role "%s".' % role_name) except KeyError: msg_text.append('Trying "%s" as canonical role name.' % role_name) # The canonical name should be an English name, but just in case: canonicalname = normname # Collect any messages that we generated. if msg_text: message = reporter.info('\n'.join(msg_text), line=lineno) messages.append(message) # Look the role up in the registry, and return it. if canonicalname in _role_registry: role_fn = _role_registry[canonicalname] register_local_role(normname, role_fn) return role_fn, messages else: return None, messages # Error message will be generated by caller. def register_canonical_role(name, role_fn): """ Register an interpreted text role by its canonical name. :Parameters: - `name`: The canonical name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _role_registry[name] = role_fn def register_local_role(name, role_fn): """ Register an interpreted text role by its local or language-dependent name. :Parameters: - `name`: The local or language-dependent name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _roles[name] = role_fn def set_implicit_options(role_fn): """ Add customization options to role functions, unless explicitly set or disabled. """ if not hasattr(role_fn, 'options') or role_fn.options is None: role_fn.options = {'class': directives.class_option} elif 'class' not in role_fn.options: role_fn.options['class'] = directives.class_option def register_generic_role(canonical_name, node_class): """For roles which simply wrap a given `node_class` around the text.""" role = GenericRole(canonical_name, node_class) register_canonical_role(canonical_name, role) class GenericRole: """ Generic interpreted text role, where the interpreted text is simply wrapped with the provided node class. """ def __init__(self, role_name, node_class): self.name = role_name self.node_class = node_class def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): set_classes(options) return [self.node_class(rawtext, utils.unescape(text), **options)], [] class CustomRole: """ Wrapper for custom interpreted text roles. """ def __init__(self, role_name, base_role, options={}, content=[]): self.name = role_name self.base_role = base_role self.options = None if hasattr(base_role, 'options'): self.options = base_role.options self.content = None if hasattr(base_role, 'content'): self.content = base_role.content self.supplied_options = options self.supplied_content = content def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): opts = self.supplied_options.copy() opts.update(options) cont = list(self.supplied_content) if cont and content: cont += '\n' cont.extend(content) return self.base_role(role, rawtext, text, lineno, inliner, options=opts, content=cont) def generic_custom_role(role, rawtext, text, lineno, inliner, options={}, content=[]): """""" # Once nested inline markup is implemented, this and other methods should # recursively call inliner.nested_parse(). set_classes(options) return [nodes.inline(rawtext, utils.unescape(text), **options)], [] generic_custom_role.options = {'class': directives.class_option} ###################################################################### # Define and register the standard roles: ###################################################################### register_generic_role('abbreviation', nodes.abbreviation) register_generic_role('acronym', nodes.acronym) register_generic_role('emphasis', nodes.emphasis) register_generic_role('literal', nodes.literal) register_generic_role('strong', nodes.strong) register_generic_role('subscript', nodes.subscript) register_generic_role('superscript', nodes.superscript) register_generic_role('title-reference', nodes.title_reference) def pep_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: pepnum = int(text) if pepnum < 0 or pepnum > 9999: raise ValueError except ValueError: msg = inliner.reporter.error( 'PEP number must be a number from 0 to 9999; "%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.pep_reference; so this is correct: ref = (inliner.document.settings.pep_base_url + inliner.document.settings.pep_file_url_template % pepnum) set_classes(options) return [nodes.reference(rawtext, 'PEP ' + utils.unescape(text), refuri=ref, **options)], [] register_canonical_role('pep-reference', pep_reference_role) def rfc_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: rfcnum = int(text) if rfcnum <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'RFC number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.rfc_reference, so this is correct: ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum set_classes(options) node = nodes.reference(rawtext, 'RFC ' + utils.unescape(text), refuri=ref, **options) return [node], [] register_canonical_role('rfc-reference', rfc_reference_role) def raw_role(role, rawtext, text, lineno, inliner, options={}, content=[]): if not inliner.document.settings.raw_enabled: msg = inliner.reporter.warning('raw (and derived) roles disabled') prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] if 'format' not in options: msg = inliner.reporter.error( 'No format (Writer name) is associated with this role: "%s".\n' 'The "raw" role cannot be used directly.\n' 'Instead, use the "role" directive to create a new role with ' 'an associated format.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] set_classes(options) node = nodes.raw(rawtext, utils.unescape(text, 1), **options) return [node], [] raw_role.options = {'format': directives.unchanged} register_canonical_role('raw', raw_role) ###################################################################### # Register roles that are currently unimplemented. ###################################################################### def unimplemented_role(role, rawtext, text, lineno, inliner, attributes={}): msg = inliner.reporter.error( 'Interpreted text role "%s" not implemented.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] register_canonical_role('index', unimplemented_role) register_canonical_role('named-reference', unimplemented_role) register_canonical_role('anonymous-reference', unimplemented_role) register_canonical_role('uri-reference', unimplemented_role) register_canonical_role('footnote-reference', unimplemented_role) register_canonical_role('citation-reference', unimplemented_role) register_canonical_role('substitution-reference', unimplemented_role) register_canonical_role('target', unimplemented_role) # This should remain unimplemented, for testing purposes: register_canonical_role('restructuredtext-unimplemented-role', unimplemented_role) def set_classes(options): """ Auxiliary function to set options['classes'] and delete options['class']. """ if 'class' in options: assert 'classes' not in options options['classes'] = options['class'] del options['class']
Python
# $Id: pt_br.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Brazilian Portuguese-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'aten\u00E7\u00E3o': 'attention', 'cuidado': 'caution', 'perigo': 'danger', 'erro': 'error', u'sugest\u00E3o': 'hint', 'importante': 'important', 'nota': 'note', 'dica': 'tip', 'aviso': 'warning', u'exorta\u00E7\u00E3o': 'admonition', 'barra-lateral': 'sidebar', u't\u00F3pico': 'topic', 'bloco-de-linhas': 'line-block', 'literal-interpretado': 'parsed-literal', 'rubrica': 'rubric', u'ep\u00EDgrafo': 'epigraph', 'destaques': 'highlights', u'cita\u00E7\u00E3o-destacada': 'pull-quote', u'compound (translation required)': 'compound', u'container (translation required)': 'container', #'perguntas': 'questions', #'qa': 'questions', #'faq': 'questions', u'table (translation required)': 'table', u'csv-table (translation required)': 'csv-table', u'list-table (translation required)': 'list-table', 'meta': 'meta', #'imagemap': 'imagemap', 'imagem': 'image', 'figura': 'figure', u'inclus\u00E3o': 'include', 'cru': 'raw', u'substitui\u00E7\u00E3o': 'replace', 'unicode': 'unicode', 'data': 'date', 'classe': 'class', 'role (translation required)': 'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', u'\u00EDndice': 'contents', 'numsec': 'sectnum', u'numera\u00E7\u00E3o-de-se\u00E7\u00F5es': 'sectnum', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #u'notas-de-rorap\u00E9': 'footnotes', #u'cita\u00E7\u00F5es': 'citations', u'links-no-rodap\u00E9': 'target-notes', 'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Brazilian Portuguese name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'abbrevia\u00E7\u00E3o': 'abbreviation', 'ab': 'abbreviation', u'acr\u00F4nimo': 'acronym', 'ac': 'acronym', u'\u00EDndice-remissivo': 'index', 'i': 'index', 'subscrito': 'subscript', 'sub': 'subscript', 'sobrescrito': 'superscript', 'sob': 'superscript', u'refer\u00EAncia-a-t\u00EDtulo': 'title-reference', u't\u00EDtulo': 'title-reference', 't': 'title-reference', u'refer\u00EAncia-a-pep': 'pep-reference', 'pep': 'pep-reference', u'refer\u00EAncia-a-rfc': 'rfc-reference', 'rfc': 'rfc-reference', u'\u00EAnfase': 'emphasis', 'forte': 'strong', 'literal': 'literal', # translation required? u'refer\u00EAncia-por-nome': 'named-reference', u'refer\u00EAncia-an\u00F4nima': 'anonymous-reference', u'refer\u00EAncia-a-nota-de-rodap\u00E9': 'footnote-reference', u'refer\u00EAncia-a-cita\u00E7\u00E3o': 'citation-reference', u'refer\u00EAncia-a-substitui\u00E7\u00E3o': 'substitution-reference', 'alvo': 'target', u'refer\u00EAncia-a-uri': 'uri-reference', 'uri': 'uri-reference', 'url': 'uri-reference', 'cru': 'raw',} """Mapping of Brazilian Portuguese role names to canonical role names for interpreted text."""
Python
# -*- coding: utf-8 -*- # $Id: zh_cn.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Panjunyong <panjy@zopechina.com> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Simplified Chinese language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'注意': 'attention', u'小心': 'caution', u'危险': 'danger', u'错误': 'error', u'提示': 'hint', u'重要': 'important', u'注解': 'note', u'技巧': 'tip', u'警告': 'warning', u'忠告': 'admonition', u'侧框': 'sidebar', u'主题': 'topic', u'line-block (translation required)': 'line-block', u'parsed-literal (translation required)': 'parsed-literal', u'醒目': 'rubric', u'铭文': 'epigraph', u'要点': 'highlights', u'pull-quote (translation required)': 'pull-quote', u'复合': 'compound', u'容器': 'container', #u'questions (translation required)': 'questions', u'表格': 'table', u'csv表格': 'csv-table', u'列表表格': 'list-table', #u'qa (translation required)': 'questions', #u'faq (translation required)': 'questions', u'元数据': 'meta', #u'imagemap (translation required)': 'imagemap', u'图片': 'image', u'图例': 'figure', u'包含': 'include', u'原文': 'raw', u'代替': 'replace', u'统一码': 'unicode', u'日期': 'date', u'类型': 'class', u'角色': 'role', u'默认角色': 'default-role', u'标题': 'title', u'目录': 'contents', u'章节序号': 'sectnum', u'题头': 'header', u'页脚': 'footer', #u'footnotes (translation required)': 'footnotes', #u'citations (translation required)': 'citations', u'target-notes (translation required)': 'target-notes', u'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Simplified Chinese name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'缩写': 'abbreviation', u'简称': 'acronym', u'index (translation required)': 'index', u'i (translation required)': 'index', u'下标': 'subscript', u'上标': 'superscript', u'title-reference (translation required)': 'title-reference', u'title (translation required)': 'title-reference', u't (translation required)': 'title-reference', u'pep-reference (translation required)': 'pep-reference', u'pep (translation required)': 'pep-reference', u'rfc-reference (translation required)': 'rfc-reference', u'rfc (translation required)': 'rfc-reference', u'强调': 'emphasis', u'加粗': 'strong', u'字面': 'literal', u'named-reference (translation required)': 'named-reference', u'anonymous-reference (translation required)': 'anonymous-reference', u'footnote-reference (translation required)': 'footnote-reference', u'citation-reference (translation required)': 'citation-reference', u'substitution-reference (translation required)': 'substitution-reference', u'target (translation required)': 'target', u'uri-reference (translation required)': 'uri-reference', u'uri (translation required)': 'uri-reference', u'url (translation required)': 'uri-reference', u'raw (translation required)': 'raw',} """Mapping of Simplified Chinese role names to canonical role names for interpreted text."""
Python
# $Id: sv.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Adam Chodorowski <chodorowski@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Swedish language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { u'observera': 'attention', u'caution (translation required)': 'caution', u'fara': 'danger', u'fel': 'error', u'v\u00e4gledning': 'hint', u'viktigt': 'important', u'notera': 'note', u'tips': 'tip', u'varning': 'warning', u'admonition (translation required)': 'admonition', u'sidebar (translation required)': 'sidebar', u'\u00e4mne': 'topic', u'line-block (translation required)': 'line-block', u'parsed-literal (translation required)': 'parsed-literal', u'mellanrubrik': 'rubric', u'epigraph (translation required)': 'epigraph', u'highlights (translation required)': 'highlights', u'pull-quote (translation required)': 'pull-quote', u'compound (translation required)': 'compound', u'container (translation required)': 'container', # u'fr\u00e5gor': 'questions', # NOTE: A bit long, but recommended by http://www.nada.kth.se/dataterm/: # u'fr\u00e5gor-och-svar': 'questions', # u'vanliga-fr\u00e5gor': 'questions', u'table (translation required)': 'table', u'csv-table (translation required)': 'csv-table', u'list-table (translation required)': 'list-table', u'meta': 'meta', # u'bildkarta': 'imagemap', # FIXME: Translation might be too literal. u'bild': 'image', u'figur': 'figure', u'inkludera': 'include', u'r\u00e5': 'raw', # FIXME: Translation might be too literal. u'ers\u00e4tt': 'replace', u'unicode': 'unicode', u'datum': 'date', u'class (translation required)': 'class', u'role (translation required)': 'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', u'inneh\u00e5ll': 'contents', u'sektionsnumrering': 'sectnum', u'target-notes (translation required)': 'target-notes', u'header (translation required)': 'header', u'footer (translation required)': 'footer', # u'fotnoter': 'footnotes', # u'citeringar': 'citations', } """Swedish name to registered (in directives/__init__.py) directive name mapping.""" roles = { u'abbreviation (translation required)': 'abbreviation', u'acronym (translation required)': 'acronym', u'index (translation required)': 'index', u'subscript (translation required)': 'subscript', u'superscript (translation required)': 'superscript', u'title-reference (translation required)': 'title-reference', u'pep-reference (translation required)': 'pep-reference', u'rfc-reference (translation required)': 'rfc-reference', u'emphasis (translation required)': 'emphasis', u'strong (translation required)': 'strong', u'literal (translation required)': 'literal', u'named-reference (translation required)': 'named-reference', u'anonymous-reference (translation required)': 'anonymous-reference', u'footnote-reference (translation required)': 'footnote-reference', u'citation-reference (translation required)': 'citation-reference', u'substitution-reference (translation required)': 'substitution-reference', u'target (translation required)': 'target', u'uri-reference (translation required)': 'uri-reference', u'r\u00e5': 'raw',} """Mapping of Swedish role names to canonical role names for interpreted text. """
Python
# $Id: it.py 4564 2006-05-21 20:44:42Z wiemann $ # Authors: Nicola Larosa <docutils@tekNico.net>; # Lele Gaifax <lele@seldati.it> # Copyright: This module has been placed in the public domain. # Beware: the italian translation of the reStructuredText documentation # at http://docit.bice.dyndns.org/static/ReST, in particular # http://docit.bice.dyndns.org/static/ReST/ref/rst/directives.html, needs # to be synced with the content of this file. """ Italian-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { 'attenzione': 'attention', 'cautela': 'caution', 'pericolo': 'danger', 'errore': 'error', 'suggerimento': 'hint', 'importante': 'important', 'nota': 'note', 'consiglio': 'tip', 'avvertenza': 'warning', 'ammonizione': 'admonition', 'riquadro': 'sidebar', 'argomento': 'topic', 'blocco-di-righe': 'line-block', 'blocco-interpretato': 'parsed-literal', 'rubrica': 'rubric', 'epigrafe': 'epigraph', 'punti-salienti': 'highlights', 'estratto-evidenziato': 'pull-quote', 'composito': 'compound', u'container (translation required)': 'container', #'questions': 'questions', #'qa': 'questions', #'faq': 'questions', 'tabella': 'table', 'tabella-csv': 'csv-table', 'tabella-elenco': 'list-table', 'meta': 'meta', #'imagemap': 'imagemap', 'immagine': 'image', 'figura': 'figure', 'includi': 'include', 'grezzo': 'raw', 'sostituisci': 'replace', 'unicode': 'unicode', 'data': 'date', 'classe': 'class', 'ruolo': 'role', 'ruolo-predefinito': 'default-role', 'titolo': 'title', 'indice': 'contents', 'contenuti': 'contents', 'seznum': 'sectnum', 'sezioni-autonumerate': 'sectnum', 'annota-riferimenti-esterni': 'target-notes', 'intestazione': 'header', 'piede-pagina': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', 'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Italian name to registered (in directives/__init__.py) directive name mapping.""" roles = { 'abbreviazione': 'abbreviation', 'acronimo': 'acronym', 'indice': 'index', 'deponente': 'subscript', 'esponente': 'superscript', 'riferimento-titolo': 'title-reference', 'riferimento-pep': 'pep-reference', 'riferimento-rfc': 'rfc-reference', 'enfasi': 'emphasis', 'forte': 'strong', 'letterale': 'literal', 'riferimento-con-nome': 'named-reference', 'riferimento-anonimo': 'anonymous-reference', 'riferimento-nota': 'footnote-reference', 'riferimento-citazione': 'citation-reference', 'riferimento-sostituzione': 'substitution-reference', 'destinazione': 'target', 'riferimento-uri': 'uri-reference', 'grezzo': 'raw',} """Mapping of Italian role names to canonical role names for interpreted text. """
Python
# -*- coding: utf-8 -*- # Author: David Goodger # Contact: goodger@users.sourceforge.net # Revision: $Revision: 4229 $ # Date: $Date: 2005-12-23 00:46:16 +0100 (Fri, 23 Dec 2005) $ # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Galician-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'atenci\u00f3n': 'attention', u'advertencia': 'caution', u'perigo': 'danger', u'erro': 'error', u'pista': 'hint', u'importante': 'important', u'nota': 'note', u'consello': 'tip', u'aviso': 'warning', u'admonici\u00f3n': 'admonition', u'barra lateral': 'sidebar', u't\u00f3pico': 'topic', u'bloque-li\u00f1a': 'line-block', u'literal-analizado': 'parsed-literal', u'r\u00fabrica': 'rubric', u'ep\u00edgrafe': 'epigraph', u'realzados': 'highlights', u'coller-citaci\u00f3n': 'pull-quote', u'compor': 'compound', u'recipiente': 'container', #'questions': 'questions', u't\u00e1boa': 'table', u't\u00e1boa-csv': 'csv-table', u't\u00e1boa-listaxe': 'list-table', #'qa': 'questions', #'faq': 'questions', u'meta': 'meta', #'imagemap': 'imagemap', u'imaxe': 'image', u'figura': 'figure', u'inclu\u00edr': 'include', u'cru': 'raw', u'substitu\u00edr': 'replace', u'unicode': 'unicode', u'data': 'date', u'clase': 'class', u'regra': 'role', u'regra-predeterminada': 'default-role', u't\u00edtulo': 'title', u'contido': 'contents', u'seccnum': 'sectnum', u'secci\u00f3n-numerar': 'sectnum', u'cabeceira': 'header', u'p\u00e9 de p\u00e1xina': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', u'notas-destino': 'target-notes', u'texto restruturado-proba-directiva': 'restructuredtext-test-directive'} """Galician name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'abreviatura': 'abbreviation', u'ab': 'abbreviation', u'acr\u00f3nimo': 'acronym', u'ac': 'acronym', u'\u00edndice': 'index', u'i': 'index', u'sub\u00edndice': 'subscript', u'sub': 'subscript', u'super\u00edndice': 'superscript', u'sup': 'superscript', u'referencia t\u00edtulo': 'title-reference', u't\u00edtulo': 'title-reference', u't': 'title-reference', u'referencia-pep': 'pep-reference', u'pep': 'pep-reference', u'referencia-rfc': 'rfc-reference', u'rfc': 'rfc-reference', u'\u00e9nfase': 'emphasis', u'forte': 'strong', u'literal': 'literal', u'referencia-nome': 'named-reference', u'referencia-an\u00f3nimo': 'anonymous-reference', u'referencia-nota ao p\u00e9': 'footnote-reference', u'referencia-citaci\u00f3n': 'citation-reference', u'referencia-substituci\u00f3n': 'substitution-reference', u'destino': 'target', u'referencia-uri': 'uri-reference', u'uri': 'uri-reference', u'url': 'uri-reference', u'cru': 'raw',} """Mapping of Galician role names to canonical role names for interpreted text. """
Python
# -*- coding: utf-8 -*- # $Id: es.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Marcelo Huerta San Martín <richieadler@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Spanish-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { u'atenci\u00f3n': 'attention', u'atencion': 'attention', u'precauci\u00f3n': 'caution', u'precaucion': 'caution', u'peligro': 'danger', u'error': 'error', u'sugerencia': 'hint', u'importante': 'important', u'nota': 'note', u'consejo': 'tip', u'advertencia': 'warning', u'exhortacion': 'admonition', u'exhortaci\u00f3n': 'admonition', u'nota-al-margen': 'sidebar', u'tema': 'topic', u'bloque-de-lineas': 'line-block', u'bloque-de-l\u00edneas': 'line-block', u'literal-evaluado': 'parsed-literal', u'firma': 'rubric', u'ep\u00edgrafe': 'epigraph', u'epigrafe': 'epigraph', u'destacado': 'highlights', u'cita-destacada': 'pull-quote', u'combinacion': 'compound', u'combinaci\u00f3n': 'compound', u'contenedor': 'container', #'questions': 'questions', #'qa': 'questions', #'faq': 'questions', u'tabla': 'table', u'tabla-vsc': 'csv-table', u'tabla-csv': 'csv-table', u'tabla-lista': 'list-table', u'meta': 'meta', #'imagemap': 'imagemap', u'imagen': 'image', u'figura': 'figure', u'incluir': 'include', u'sin-analisis': 'raw', u'sin-an\u00e1lisis': 'raw', u'reemplazar': 'replace', u'unicode': 'unicode', u'fecha': 'date', u'clase': 'class', u'rol': 'role', u'rol-por-omision': 'default-role', u'rol-por-omisi\u00f3n': 'default-role', u'titulo': 'title', u't\u00edtulo': 'title', u'contenido': 'contents', u'numseccion': 'sectnum', u'numsecci\u00f3n': 'sectnum', u'numeracion-seccion': 'sectnum', u'numeraci\u00f3n-secci\u00f3n': 'sectnum', u'notas-destino': 'target-notes', u'cabecera': 'header', u'pie': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', u'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Spanish name to registered (in directives/__init__.py) directive name mapping.""" roles = { u'abreviatura': 'abbreviation', u'ab': 'abbreviation', u'acronimo': 'acronym', u'acronimo': 'acronym', u'ac': 'acronym', u'indice': 'index', u'i': 'index', u'subindice': 'subscript', u'sub\u00edndice': 'subscript', u'superindice': 'superscript', u'super\u00edndice': 'superscript', u'referencia-titulo': 'title-reference', u'titulo': 'title-reference', u't': 'title-reference', u'referencia-pep': 'pep-reference', u'pep': 'pep-reference', u'referencia-rfc': 'rfc-reference', u'rfc': 'rfc-reference', u'enfasis': 'emphasis', u'\u00e9nfasis': 'emphasis', u'destacado': 'strong', u'literal': 'literal', # "literal" is also a word in Spanish :-) u'referencia-con-nombre': 'named-reference', u'referencia-anonima': 'anonymous-reference', u'referencia-an\u00f3nima': 'anonymous-reference', u'referencia-nota-al-pie': 'footnote-reference', u'referencia-cita': 'citation-reference', u'referencia-sustitucion': 'substitution-reference', u'referencia-sustituci\u00f3n': 'substitution-reference', u'destino': 'target', u'referencia-uri': 'uri-reference', u'uri': 'uri-reference', u'url': 'uri-reference', u'sin-analisis': 'raw', u'sin-an\u00e1lisis': 'raw', } """Mapping of Spanish role names to canonical role names for interpreted text. """
Python
# -*- coding: utf-8 -*- # $Id: ja.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Japanese-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' # Corrections to these translations are welcome! # 間違いがあれば、どうぞ正しい翻訳を教えて下さい。 directives = { # language-dependent: fixed u'注目': 'attention', u'注意': 'caution', u'危険': 'danger', u'エラー': 'error', u'ヒント': 'hint', u'重要': 'important', u'備考': 'note', u'通報': 'tip', u'警告': 'warning', u'戒告': 'admonition', u'サイドバー': 'sidebar', u'トピック': 'topic', u'ラインブロック': 'line-block', u'パーズドリテラル': 'parsed-literal', u'ルブリック': 'rubric', u'エピグラフ': 'epigraph', u'題言': 'epigraph', u'ハイライト': 'highlights', u'見所': 'highlights', u'プルクオート': 'pull-quote', u'合成': 'compound', u'コンテナー': 'container', u'容器': 'container', u'表': 'table', u'csv表': 'csv-table', u'リスト表': 'list-table', #u'質問': 'questions', #u'問答': 'questions', #u'faq': 'questions', u'メタ': 'meta', #u'イメージマプ': 'imagemap', u'イメージ': 'image', u'画像': 'image', u'フィグア': 'figure', u'図版': 'figure', u'インクルード': 'include', u'含む': 'include', u'組み込み': 'include', u'生': 'raw', u'原': 'raw', u'換える': 'replace', u'取り換える': 'replace', u'掛け替える': 'replace', u'ユニコード': 'unicode', u'日付': 'date', u'クラス': 'class', u'ロール': 'role', u'役': 'role', u'ディフォルトロール': 'default-role', u'既定役': 'default-role', u'タイトル': 'title', u'題': 'title', # 題名 件名 u'目次': 'contents', u'節数': 'sectnum', u'ヘッダ': 'header', u'フッタ': 'footer', #u'脚注': 'footnotes', # 脚註? #u'サイテーション': 'citations',   # 出典 引証 引用 u'ターゲットノート': 'target-notes', # 的注 的脚注 } """Japanese name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'略': 'abbreviation', u'頭字語': 'acronym', u'インデックス': 'index', u'索引': 'index', u'添字': 'subscript', u'下付': 'subscript', u'下': 'subscript', u'上付': 'superscript', u'上': 'superscript', u'題参照': 'title-reference', u'pep参照': 'pep-reference', u'rfc参照': 'rfc-reference', u'強調': 'emphasis', u'強い': 'strong', u'リテラル': 'literal', u'整形済み': 'literal', u'名付参照': 'named-reference', u'無名参照': 'anonymous-reference', u'脚注参照': 'footnote-reference', u'出典参照': 'citation-reference', u'代入参照': 'substitution-reference', u'的': 'target', u'uri参照': 'uri-reference', u'uri': 'uri-reference', u'url': 'uri-reference', u'生': 'raw',} """Mapping of Japanese role names to canonical role names for interpreted text."""
Python
# $Id: ca.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Ivan Vilata i Balaguer <ivan@selidor.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Catalan-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'atenci\u00F3': 'attention', u'compte': 'caution', u'perill': 'danger', u'error': 'error', u'suggeriment': 'hint', u'important': 'important', u'nota': 'note', u'consell': 'tip', u'av\u00EDs': 'warning', u'advertiment': 'admonition', u'nota-al-marge': 'sidebar', u'nota-marge': 'sidebar', u'tema': 'topic', u'bloc-de-l\u00EDnies': 'line-block', u'bloc-l\u00EDnies': 'line-block', u'literal-analitzat': 'parsed-literal', u'r\u00FAbrica': 'rubric', u'ep\u00EDgraf': 'epigraph', u'sumari': 'highlights', u'cita-destacada': 'pull-quote', u'compost': 'compound', u'container (translation required)': 'container', #'questions': 'questions', u'taula': 'table', u'taula-csv': 'csv-table', u'taula-llista': 'list-table', #'qa': 'questions', #'faq': 'questions', u'meta': 'meta', #'imagemap': 'imagemap', u'imatge': 'image', u'figura': 'figure', u'inclou': 'include', u'incloure': 'include', u'cru': 'raw', u'reempla\u00E7a': 'replace', u'reempla\u00E7ar': 'replace', u'unicode': 'unicode', u'data': 'date', u'classe': 'class', u'rol': 'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', u'contingut': 'contents', u'numsec': 'sectnum', u'numeraci\u00F3-de-seccions': 'sectnum', u'numeraci\u00F3-seccions': 'sectnum', u'cap\u00E7alera': 'header', u'peu-de-p\u00E0gina': 'footer', u'peu-p\u00E0gina': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', u'notes-amb-destinacions': 'target-notes', u'notes-destinacions': 'target-notes', u'directiva-de-prova-de-restructuredtext': 'restructuredtext-test-directive'} """Catalan name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'abreviatura': 'abbreviation', u'abreviaci\u00F3': 'abbreviation', u'abrev': 'abbreviation', u'ab': 'abbreviation', u'acr\u00F2nim': 'acronym', u'ac': 'acronym', u'\u00EDndex': 'index', u'i': 'index', u'sub\u00EDndex': 'subscript', u'sub': 'subscript', u'super\u00EDndex': 'superscript', u'sup': 'superscript', u'refer\u00E8ncia-a-t\u00EDtol': 'title-reference', u'refer\u00E8ncia-t\u00EDtol': 'title-reference', u't\u00EDtol': 'title-reference', u't': 'title-reference', u'refer\u00E8ncia-a-pep': 'pep-reference', u'refer\u00E8ncia-pep': 'pep-reference', u'pep': 'pep-reference', u'refer\u00E8ncia-a-rfc': 'rfc-reference', u'refer\u00E8ncia-rfc': 'rfc-reference', u'rfc': 'rfc-reference', u'\u00E8mfasi': 'emphasis', u'destacat': 'strong', u'literal': 'literal', u'refer\u00E8ncia-amb-nom': 'named-reference', u'refer\u00E8ncia-nom': 'named-reference', u'refer\u00E8ncia-an\u00F2nima': 'anonymous-reference', u'refer\u00E8ncia-a-nota-al-peu': 'footnote-reference', u'refer\u00E8ncia-nota-al-peu': 'footnote-reference', u'refer\u00E8ncia-a-cita': 'citation-reference', u'refer\u00E8ncia-cita': 'citation-reference', u'refer\u00E8ncia-a-substituci\u00F3': 'substitution-reference', u'refer\u00E8ncia-substituci\u00F3': 'substitution-reference', u'destinaci\u00F3': 'target', u'refer\u00E8ncia-a-uri': 'uri-reference', u'refer\u00E8ncia-uri': 'uri-reference', u'uri': 'uri-reference', u'url': 'uri-reference', u'cru': 'raw',} """Mapping of Catalan role names to canonical role names for interpreted text. """
Python
# $Id: cs.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Marek Blaha <mb@dat.cz> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Czech-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'pozor': 'attention', u'caution (translation required)': 'caution', # jak rozlisit caution a warning? u'nebezpe\u010D\u00ED': 'danger', u'chyba': 'error', u'rada': 'hint', u'd\u016Fle\u017Eit\u00E9': 'important', u'pozn\u00E1mka': 'note', u'tip (translation required)': 'tip', u'varov\u00E1n\u00ED': 'warning', u'admonition (translation required)': 'admonition', u'sidebar (translation required)': 'sidebar', u't\u00E9ma': 'topic', u'line-block (translation required)': 'line-block', u'parsed-literal (translation required)': 'parsed-literal', u'odd\u00EDl': 'rubric', u'moto': 'epigraph', u'highlights (translation required)': 'highlights', u'pull-quote (translation required)': 'pull-quote', u'compound (translation required)': 'compound', u'container (translation required)': 'container', #'questions': 'questions', #'qa': 'questions', #'faq': 'questions', u'table (translation required)': 'table', u'csv-table (translation required)': 'csv-table', u'list-table (translation required)': 'list-table', u'meta (translation required)': 'meta', #'imagemap': 'imagemap', u'image (translation required)': 'image', # obrazek u'figure (translation required)': 'figure', # a tady? u'include (translation required)': 'include', u'raw (translation required)': 'raw', u'replace (translation required)': 'replace', u'unicode (translation required)': 'unicode', u'datum': 'date', u't\u0159\u00EDda': 'class', u'role (translation required)': 'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', u'obsah': 'contents', u'sectnum (translation required)': 'sectnum', u'section-numbering (translation required)': 'sectnum', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', u'target-notes (translation required)': 'target-notes', u'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Czech name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'abbreviation (translation required)': 'abbreviation', u'ab (translation required)': 'abbreviation', u'acronym (translation required)': 'acronym', u'ac (translation required)': 'acronym', u'index (translation required)': 'index', u'i (translation required)': 'index', u'subscript (translation required)': 'subscript', u'sub (translation required)': 'subscript', u'superscript (translation required)': 'superscript', u'sup (translation required)': 'superscript', u'title-reference (translation required)': 'title-reference', u'title (translation required)': 'title-reference', u't (translation required)': 'title-reference', u'pep-reference (translation required)': 'pep-reference', u'pep (translation required)': 'pep-reference', u'rfc-reference (translation required)': 'rfc-reference', u'rfc (translation required)': 'rfc-reference', u'emphasis (translation required)': 'emphasis', u'strong (translation required)': 'strong', u'literal (translation required)': 'literal', u'named-reference (translation required)': 'named-reference', u'anonymous-reference (translation required)': 'anonymous-reference', u'footnote-reference (translation required)': 'footnote-reference', u'citation-reference (translation required)': 'citation-reference', u'substitution-reference (translation required)': 'substitution-reference', u'target (translation required)': 'target', u'uri-reference (translation required)': 'uri-reference', u'uri (translation required)': 'uri-reference', u'url (translation required)': 'uri-reference', u'raw (translation required)': 'raw',} """Mapping of Czech role names to canonical role names for interpreted text. """
Python
# $Id: af.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Jannie Hofmeyr <jhsh@sun.ac.za> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Afrikaans-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { 'aandag': 'attention', 'versigtig': 'caution', 'gevaar': 'danger', 'fout': 'error', 'wenk': 'hint', 'belangrik': 'important', 'nota': 'note', 'tip': 'tip', # hint and tip both have the same translation: wenk 'waarskuwing': 'warning', 'vermaning': 'admonition', 'kantstreep': 'sidebar', 'onderwerp': 'topic', 'lynblok': 'line-block', 'parsed-literal (translation required)': 'parsed-literal', 'rubriek': 'rubric', 'epigraaf': 'epigraph', 'hoogtepunte': 'highlights', 'pull-quote (translation required)': 'pull-quote', u'compound (translation required)': 'compound', u'container (translation required)': 'container', #'vrae': 'questions', #'qa': 'questions', #'faq': 'questions', 'table (translation required)': 'table', 'csv-table (translation required)': 'csv-table', 'list-table (translation required)': 'list-table', 'meta': 'meta', #'beeldkaart': 'imagemap', 'beeld': 'image', 'figuur': 'figure', 'insluiting': 'include', 'rou': 'raw', 'vervang': 'replace', 'unicode': 'unicode', # should this be translated? unikode 'datum': 'date', 'klas': 'class', 'role (translation required)': 'role', 'default-role (translation required)': 'default-role', 'title (translation required)': 'title', 'inhoud': 'contents', 'sectnum': 'sectnum', 'section-numbering': 'sectnum', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #'voetnote': 'footnotes', #'aanhalings': 'citations', 'teikennotas': 'target-notes', 'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Afrikaans name to registered (in directives/__init__.py) directive name mapping.""" roles = { 'afkorting': 'abbreviation', 'ab': 'abbreviation', 'akroniem': 'acronym', 'ac': 'acronym', 'indeks': 'index', 'i': 'index', 'voetskrif': 'subscript', 'sub': 'subscript', 'boskrif': 'superscript', 'sup': 'superscript', 'titelverwysing': 'title-reference', 'titel': 'title-reference', 't': 'title-reference', 'pep-verwysing': 'pep-reference', 'pep': 'pep-reference', 'rfc-verwysing': 'rfc-reference', 'rfc': 'rfc-reference', 'nadruk': 'emphasis', 'sterk': 'strong', 'literal (translation required)': 'literal', 'benoemde verwysing': 'named-reference', 'anonieme verwysing': 'anonymous-reference', 'voetnootverwysing': 'footnote-reference', 'aanhalingverwysing': 'citation-reference', 'vervangingsverwysing': 'substitution-reference', 'teiken': 'target', 'uri-verwysing': 'uri-reference', 'uri': 'uri-reference', 'url': 'uri-reference', 'rou': 'raw',} """Mapping of Afrikaans role names to canonical role names for interpreted text. """
Python
# $Id: sk.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Miroslav Vasko <zemiak@zoznam.sk> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Slovak-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { u'pozor': 'attention', u'opatrne': 'caution', u'nebezpe\xe8enstvo': 'danger', u'chyba': 'error', u'rada': 'hint', u'd\xf4le\x9eit\xe9': 'important', u'pozn\xe1mka': 'note', u'tip (translation required)': 'tip', u'varovanie': 'warning', u'admonition (translation required)': 'admonition', u'sidebar (translation required)': 'sidebar', u't\xe9ma': 'topic', u'blok-riadkov': 'line-block', u'parsed-literal': 'parsed-literal', u'rubric (translation required)': 'rubric', u'epigraph (translation required)': 'epigraph', u'highlights (translation required)': 'highlights', u'pull-quote (translation required)': 'pull-quote', u'compound (translation required)': 'compound', u'container (translation required)': 'container', #u'questions': 'questions', #u'qa': 'questions', #u'faq': 'questions', u'table (translation required)': 'table', u'csv-table (translation required)': 'csv-table', u'list-table (translation required)': 'list-table', u'meta': 'meta', #u'imagemap': 'imagemap', u'obr\xe1zok': 'image', u'tvar': 'figure', u'vlo\x9ei\x9d': 'include', u'raw (translation required)': 'raw', u'nahradi\x9d': 'replace', u'unicode': 'unicode', u'd\u00E1tum': 'date', u'class (translation required)': 'class', u'role (translation required)': 'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', u'obsah': 'contents', u'\xe8as\x9d': 'sectnum', u'\xe8as\x9d-\xe8\xedslovanie': 'sectnum', u'cie\xbeov\xe9-pozn\xe1mky': 'target-notes', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #u'footnotes': 'footnotes', #u'citations': 'citations', } """Slovak name to registered (in directives/__init__.py) directive name mapping.""" roles = { u'abbreviation (translation required)': 'abbreviation', u'acronym (translation required)': 'acronym', u'index (translation required)': 'index', u'subscript (translation required)': 'subscript', u'superscript (translation required)': 'superscript', u'title-reference (translation required)': 'title-reference', u'pep-reference (translation required)': 'pep-reference', u'rfc-reference (translation required)': 'rfc-reference', u'emphasis (translation required)': 'emphasis', u'strong (translation required)': 'strong', u'literal (translation required)': 'literal', u'named-reference (translation required)': 'named-reference', u'anonymous-reference (translation required)': 'anonymous-reference', u'footnote-reference (translation required)': 'footnote-reference', u'citation-reference (translation required)': 'citation-reference', u'substitution-reference (translation required)': 'substitution-reference', u'target (translation required)': 'target', u'uri-reference (translation required)': 'uri-reference', u'raw (translation required)': 'raw',} """Mapping of Slovak role names to canonical role names for interpreted text. """
Python
# $Id$ # Author: Robert Wojciechowicz <rw@smsnet.pl> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Polish-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'uwaga': 'attention', u'ostro\u017cnie': 'caution', u'niebezpiecze\u0144stwo': 'danger', u'b\u0142\u0105d': 'error', u'wskaz\u00f3wka': 'hint', u'wa\u017cne': 'important', u'przypis': 'note', u'rada': 'tip', u'ostrze\u017cenie': 'warning', u'upomnienie': 'admonition', u'ramka': 'sidebar', u'temat': 'topic', u'blok-linii': 'line-block', u'sparsowany-litera\u0142': 'parsed-literal', u'rubryka': 'rubric', u'epigraf': 'epigraph', u'highlights': 'highlights', # FIXME no polish equivalent? u'pull-quote': 'pull-quote', # FIXME no polish equivalent? u'z\u0142o\u017cony': 'compound', u'kontener': 'container', #'questions': 'questions', u'tabela': 'table', u'tabela-csv': 'csv-table', u'tabela-listowa': 'list-table', #'qa': 'questions', #'faq': 'questions', u'meta': 'meta', #'imagemap': 'imagemap', u'obraz': 'image', u'rycina': 'figure', u'do\u0142\u0105cz': 'include', u'surowe': 'raw', u'zast\u0105p': 'replace', u'unikod': 'unicode', u'data': 'date', u'klasa': 'class', u'rola': 'role', u'rola-domy\u015blna': 'default-role', u'tytu\u0142': 'title', u'tre\u015b\u0107': 'contents', u'sectnum': 'sectnum', u'numeracja-sekcji': 'sectnum', u'nag\u0142\u00f3wek': 'header', u'stopka': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', u'target-notes': 'target-notes', # FIXME no polish equivalent? u'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Polish name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'skr\u00f3t': 'abbreviation', u'akronim': 'acronym', u'indeks': 'index', u'indeks-dolny': 'subscript', u'indeks-g\u00f3rny': 'superscript', u'referencja-tytu\u0142': 'title-reference', u'referencja-pep': 'pep-reference', u'referencja-rfc': 'rfc-reference', u'podkre\u015blenie': 'emphasis', u'wyt\u0142uszczenie': 'strong', u'dos\u0142ownie': 'literal', u'referencja-nazwana': 'named-reference', u'referencja-anonimowa': 'anonymous-reference', u'referencja-przypis': 'footnote-reference', u'referencja-cytat': 'citation-reference', u'referencja-podstawienie': 'substitution-reference', u'cel': 'target', u'referencja-uri': 'uri-reference', u'uri': 'uri-reference', u'url': 'uri-reference', u'surowe': 'raw',} """Mapping of Polish role names to canonical role names for interpreted text. """
Python
# $Id: ru.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Roman Suzi <rnd@onego.ru> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Russian-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { u'\u0431\u043b\u043e\u043a-\u0441\u0442\u0440\u043e\u043a': u'line-block', u'meta': u'meta', u'\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u043d\u044b\u0439-\u043b\u0438\u0442\u0435\u0440\u0430\u043b': u'parsed-literal', u'\u0432\u044b\u0434\u0435\u043b\u0435\u043d\u043d\u0430\u044f-\u0446\u0438\u0442\u0430\u0442\u0430': u'pull-quote', u'compound (translation required)': 'compound', u'container (translation required)': 'container', u'table (translation required)': 'table', u'csv-table (translation required)': 'csv-table', u'list-table (translation required)': 'list-table', u'\u0441\u044b\u0440\u043e\u0439': u'raw', u'\u0437\u0430\u043c\u0435\u043d\u0430': u'replace', u'\u0442\u0435\u0441\u0442\u043e\u0432\u0430\u044f-\u0434\u0438\u0440\u0435\u043a\u0442\u0438\u0432\u0430-restructuredtext': u'restructuredtext-test-directive', u'\u0446\u0435\u043b\u0435\u0432\u044b\u0435-\u0441\u043d\u043e\u0441\u043a\u0438': u'target-notes', u'unicode': u'unicode', u'\u0434\u0430\u0442\u0430': u'date', u'\u0431\u043e\u043a\u043e\u0432\u0430\u044f-\u043f\u043e\u043b\u043e\u0441\u0430': u'sidebar', u'\u0432\u0430\u0436\u043d\u043e': u'important', u'\u0432\u043a\u043b\u044e\u0447\u0430\u0442\u044c': u'include', u'\u0432\u043d\u0438\u043c\u0430\u043d\u0438\u0435': u'attention', u'\u0432\u044b\u0434\u0435\u043b\u0435\u043d\u0438\u0435': u'highlights', u'\u0437\u0430\u043c\u0435\u0447\u0430\u043d\u0438\u0435': u'admonition', u'\u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435': u'image', u'\u043a\u043b\u0430\u0441\u0441': u'class', u'role (translation required)': 'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', u'\u043d\u043e\u043c\u0435\u0440-\u0440\u0430\u0437\u0434\u0435\u043b\u0430': u'sectnum', u'\u043d\u0443\u043c\u0435\u0440\u0430\u0446\u0438\u044f-\u0440\u0430\u0437' u'\u0434\u0435\u043b\u043e\u0432': u'sectnum', u'\u043e\u043f\u0430\u0441\u043d\u043e': u'danger', u'\u043e\u0441\u0442\u043e\u0440\u043e\u0436\u043d\u043e': u'caution', u'\u043e\u0448\u0438\u0431\u043a\u0430': u'error', u'\u043f\u043e\u0434\u0441\u043a\u0430\u0437\u043a\u0430': u'tip', u'\u043f\u0440\u0435\u0434\u0443\u043f\u0440\u0435\u0436\u0434\u0435\u043d' u'\u0438\u0435': u'warning', u'\u043f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435': u'note', u'\u0440\u0438\u0441\u0443\u043d\u043e\u043a': u'figure', u'\u0440\u0443\u0431\u0440\u0438\u043a\u0430': u'rubric', u'\u0441\u043e\u0432\u0435\u0442': u'hint', u'\u0441\u043e\u0434\u0435\u0440\u0436\u0430\u043d\u0438\u0435': u'contents', u'\u0442\u0435\u043c\u0430': u'topic', u'\u044d\u043f\u0438\u0433\u0440\u0430\u0444': u'epigraph', u'header (translation required)': 'header', u'footer (translation required)': 'footer',} """Russian name to registered (in directives/__init__.py) directive name mapping.""" roles = { u'\u0430\u043a\u0440\u043e\u043d\u0438\u043c': 'acronym', u'\u0430\u043d\u043e\u043d\u0438\u043c\u043d\u0430\u044f-\u0441\u0441\u044b\u043b\u043a\u0430': 'anonymous-reference', u'\u0431\u0443\u043a\u0432\u0430\u043b\u044c\u043d\u043e': 'literal', u'\u0432\u0435\u0440\u0445\u043d\u0438\u0439-\u0438\u043d\u0434\u0435\u043a\u0441': 'superscript', u'\u0432\u044b\u0434\u0435\u043b\u0435\u043d\u0438\u0435': 'emphasis', u'\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u043d\u0430\u044f-\u0441\u0441\u044b\u043b\u043a\u0430': 'named-reference', u'\u0438\u043d\u0434\u0435\u043a\u0441': 'index', u'\u043d\u0438\u0436\u043d\u0438\u0439-\u0438\u043d\u0434\u0435\u043a\u0441': 'subscript', u'\u0441\u0438\u043b\u044c\u043d\u043e\u0435-\u0432\u044b\u0434\u0435\u043b\u0435\u043d\u0438\u0435': 'strong', u'\u0441\u043e\u043a\u0440\u0430\u0449\u0435\u043d\u0438\u0435': 'abbreviation', u'\u0441\u0441\u044b\u043b\u043a\u0430-\u0437\u0430\u043c\u0435\u043d\u0430': 'substitution-reference', u'\u0441\u0441\u044b\u043b\u043a\u0430-\u043d\u0430-pep': 'pep-reference', u'\u0441\u0441\u044b\u043b\u043a\u0430-\u043d\u0430-rfc': 'rfc-reference', u'\u0441\u0441\u044b\u043b\u043a\u0430-\u043d\u0430-uri': 'uri-reference', u'\u0441\u0441\u044b\u043b\u043a\u0430-\u043d\u0430-\u0437\u0430\u0433\u043b\u0430\u0432\u0438\u0435': 'title-reference', u'\u0441\u0441\u044b\u043b\u043a\u0430-\u043d\u0430-\u0441\u043d\u043e\u0441\u043a\u0443': 'footnote-reference', u'\u0446\u0438\u0442\u0430\u0442\u043d\u0430\u044f-\u0441\u0441\u044b\u043b\u043a\u0430': 'citation-reference', u'\u0446\u0435\u043b\u044c': 'target', u'raw (translation required)': 'raw',} """Mapping of Russian role names to canonical role names for interpreted text. """
Python
# $Id: de.py 5174 2007-05-31 00:01:52Z wiemann $ # Authors: Engelbert Gruber <grubert@users.sourceforge.net>; # Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ German-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { 'achtung': 'attention', 'vorsicht': 'caution', 'gefahr': 'danger', 'fehler': 'error', 'hinweis': 'hint', 'wichtig': 'important', 'notiz': 'note', 'tipp': 'tip', 'warnung': 'warning', 'ermahnung': 'admonition', 'kasten': 'sidebar', 'seitenkasten': 'sidebar', 'thema': 'topic', 'zeilen-block': 'line-block', 'parsed-literal (translation required)': 'parsed-literal', 'rubrik': 'rubric', 'epigraph': 'epigraph', 'highlights (translation required)': 'highlights', 'pull-quote (translation required)': 'pull-quote', # kasten too ? 'zusammengesetzt': 'compound', 'verbund': 'compound', u'container (translation required)': 'container', #'fragen': 'questions', 'tabelle': 'table', 'csv-tabelle': 'csv-table', 'list-table (translation required)': 'list-table', 'meta': 'meta', #'imagemap': 'imagemap', 'bild': 'image', 'abbildung': 'figure', u'unver\xe4ndert': 'raw', u'roh': 'raw', u'einf\xfcgen': 'include', 'ersetzung': 'replace', 'ersetzen': 'replace', 'ersetze': 'replace', 'unicode': 'unicode', 'datum': 'date', 'klasse': 'class', 'rolle': 'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', 'inhalt': 'contents', 'kapitel-nummerierung': 'sectnum', 'abschnitts-nummerierung': 'sectnum', u'linkziel-fu\xdfnoten': 'target-notes', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #u'fu\xdfnoten': 'footnotes', #'zitate': 'citations', } """German name to registered (in directives/__init__.py) directive name mapping.""" roles = { u'abk\xfcrzung': 'abbreviation', 'akronym': 'acronym', 'index': 'index', 'tiefgestellt': 'subscript', 'hochgestellt': 'superscript', 'titel-referenz': 'title-reference', 'pep-referenz': 'pep-reference', 'rfc-referenz': 'rfc-reference', 'betonung': 'emphasis', 'fett': 'strong', u'w\xf6rtlich': 'literal', 'benannte-referenz': 'named-reference', 'unbenannte-referenz': 'anonymous-reference', u'fu\xdfnoten-referenz': 'footnote-reference', 'zitat-referenz': 'citation-reference', 'ersetzungs-referenz': 'substitution-reference', 'ziel': 'target', 'uri-referenz': 'uri-reference', u'unver\xe4ndert': 'raw', u'roh': 'raw',} """Mapping of German role names to canonical role names for interpreted text. """
Python
# $Id: en.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ English-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed 'attention': 'attention', 'caution': 'caution', 'danger': 'danger', 'error': 'error', 'hint': 'hint', 'important': 'important', 'note': 'note', 'tip': 'tip', 'warning': 'warning', 'admonition': 'admonition', 'sidebar': 'sidebar', 'topic': 'topic', 'line-block': 'line-block', 'parsed-literal': 'parsed-literal', 'rubric': 'rubric', 'epigraph': 'epigraph', 'highlights': 'highlights', 'pull-quote': 'pull-quote', 'compound': 'compound', 'container': 'container', #'questions': 'questions', 'table': 'table', 'csv-table': 'csv-table', 'list-table': 'list-table', #'qa': 'questions', #'faq': 'questions', 'meta': 'meta', #'imagemap': 'imagemap', 'image': 'image', 'figure': 'figure', 'include': 'include', 'raw': 'raw', 'replace': 'replace', 'unicode': 'unicode', 'date': 'date', 'class': 'class', 'role': 'role', 'default-role': 'default-role', 'title': 'title', 'contents': 'contents', 'sectnum': 'sectnum', 'section-numbering': 'sectnum', 'header': 'header', 'footer': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', 'target-notes': 'target-notes', 'restructuredtext-test-directive': 'restructuredtext-test-directive'} """English name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed 'abbreviation': 'abbreviation', 'ab': 'abbreviation', 'acronym': 'acronym', 'ac': 'acronym', 'index': 'index', 'i': 'index', 'subscript': 'subscript', 'sub': 'subscript', 'superscript': 'superscript', 'sup': 'superscript', 'title-reference': 'title-reference', 'title': 'title-reference', 't': 'title-reference', 'pep-reference': 'pep-reference', 'pep': 'pep-reference', 'rfc-reference': 'rfc-reference', 'rfc': 'rfc-reference', 'emphasis': 'emphasis', 'strong': 'strong', 'literal': 'literal', 'named-reference': 'named-reference', 'anonymous-reference': 'anonymous-reference', 'footnote-reference': 'footnote-reference', 'citation-reference': 'citation-reference', 'substitution-reference': 'substitution-reference', 'target': 'target', 'uri-reference': 'uri-reference', 'uri': 'uri-reference', 'url': 'uri-reference', 'raw': 'raw',} """Mapping of English role names to canonical role names for interpreted text. """
Python
# $Id: fi.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Asko Soukka <asko.soukka@iki.fi> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Finnish-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'huomio': u'attention', u'varo': u'caution', u'vaara': u'danger', u'virhe': u'error', u'vihje': u'hint', u't\u00e4rke\u00e4\u00e4': u'important', u'huomautus': u'note', u'neuvo': u'tip', u'varoitus': u'warning', u'kehotus': u'admonition', u'sivupalkki': u'sidebar', u'aihe': u'topic', u'rivi': u'line-block', u'tasalevyinen': u'parsed-literal', u'ohje': u'rubric', u'epigraafi': u'epigraph', u'kohokohdat': u'highlights', u'lainaus': u'pull-quote', u'taulukko': u'table', u'csv-taulukko': u'csv-table', u'list-table (translation required)': 'list-table', u'compound (translation required)': 'compound', u'container (translation required)': 'container', #u'kysymykset': u'questions', u'meta': u'meta', #u'kuvakartta': u'imagemap', u'kuva': u'image', u'kaavio': u'figure', u'sis\u00e4llyt\u00e4': u'include', u'raaka': u'raw', u'korvaa': u'replace', u'unicode': u'unicode', u'p\u00e4iv\u00e4ys': u'date', u'luokka': u'class', u'rooli': u'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', u'sis\u00e4llys': u'contents', u'kappale': u'sectnum', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #u'alaviitteet': u'footnotes', #u'viitaukset': u'citations', u'target-notes (translation required)': u'target-notes'} """Finnish name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'lyhennys': u'abbreviation', u'akronyymi': u'acronym', u'kirjainsana': u'acronym', u'hakemisto': u'index', u'luettelo': u'index', u'alaindeksi': u'subscript', u'indeksi': u'subscript', u'yl\u00e4indeksi': u'superscript', u'title-reference (translation required)': u'title-reference', u'title (translation required)': u'title-reference', u'pep-reference (translation required)': u'pep-reference', u'rfc-reference (translation required)': u'rfc-reference', u'korostus': u'emphasis', u'vahvistus': u'strong', u'tasalevyinen': u'literal', u'named-reference (translation required)': u'named-reference', u'anonymous-reference (translation required)': u'anonymous-reference', u'footnote-reference (translation required)': u'footnote-reference', u'citation-reference (translation required)': u'citation-reference', u'substitution-reference (translation required)': u'substitution-reference', u'kohde': u'target', u'uri-reference (translation required)': u'uri-reference', u'raw (translation required)': 'raw',} """Mapping of Finnish role names to canonical role names for interpreted text. """
Python
# Author: Meir Kriheli # Id: $Id: he.py 4837 2006-12-26 09:59:41Z sfcben $ # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ English-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'\u05ea\u05e9\u05d5\u05de\u05ea \u05dc\u05d1': 'attention', u'\u05d6\u05d4\u05d9\u05e8\u05d5\u05ea': 'caution', u'\u05e1\u05db\u05e0\u05d4': 'danger', u'\u05e9\u05d2\u05d9\u05d0\u05d4' : 'error', u'\u05e8\u05de\u05d6': 'hint', u'\u05d7\u05e9\u05d5\u05d1': 'important', u'\u05d4\u05e2\u05e8\u05d4': 'note', u'\u05d8\u05d9\u05e4': 'tip', u'\u05d0\u05d6\u05d4\u05e8\u05d4': 'warning', 'admonition': 'admonition', 'sidebar': 'sidebar', 'topic': 'topic', 'line-block': 'line-block', 'parsed-literal': 'parsed-literal', 'rubric': 'rubric', 'epigraph': 'epigraph', 'highlights': 'highlights', 'pull-quote': 'pull-quote', 'compound': 'compound', 'container': 'container', #'questions': 'questions', 'table': 'table', 'csv-table': 'csv-table', 'list-table': 'list-table', #'qa': 'questions', #'faq': 'questions', 'meta': 'meta', #'imagemap': 'imagemap', u'\u05ea\u05de\u05d5\u05e0\u05d4': 'image', 'figure': 'figure', 'include': 'include', 'raw': 'raw', 'replace': 'replace', 'unicode': 'unicode', 'date': 'date', u'\u05e1\u05d2\u05e0\u05d5\u05df': 'class', 'role': 'role', 'default-role': 'default-role', 'title': 'title', u'\u05ea\u05d5\u05db\u05df': 'contents', 'sectnum': 'sectnum', 'section-numbering': 'sectnum', 'header': 'header', 'footer': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', 'target-notes': 'target-notes', 'restructuredtext-test-directive': 'restructuredtext-test-directive'} """English name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed 'abbreviation': 'abbreviation', 'ab': 'abbreviation', 'acronym': 'acronym', 'ac': 'acronym', 'index': 'index', 'i': 'index', u'\u05ea\u05d7\u05ea\u05d9': 'subscript', 'sub': 'subscript', u'\u05e2\u05d9\u05dc\u05d9': 'superscript', 'sup': 'superscript', 'title-reference': 'title-reference', 'title': 'title-reference', 't': 'title-reference', 'pep-reference': 'pep-reference', 'pep': 'pep-reference', 'rfc-reference': 'rfc-reference', 'rfc': 'rfc-reference', 'emphasis': 'emphasis', 'strong': 'strong', 'literal': 'literal', 'named-reference': 'named-reference', 'anonymous-reference': 'anonymous-reference', 'footnote-reference': 'footnote-reference', 'citation-reference': 'citation-reference', 'substitution-reference': 'substitution-reference', 'target': 'target', 'uri-reference': 'uri-reference', 'uri': 'uri-reference', 'url': 'uri-reference', 'raw': 'raw',} """Mapping of English role names to canonical role names for interpreted text. """
Python
# $Id: fr.py 4564 2006-05-21 20:44:42Z wiemann $ # Authors: David Goodger <goodger@python.org>; William Dode # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ French-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { u'attention': 'attention', u'pr\u00E9caution': 'caution', u'danger': 'danger', u'erreur': 'error', u'conseil': 'hint', u'important': 'important', u'note': 'note', u'astuce': 'tip', u'avertissement': 'warning', u'admonition': 'admonition', u'encadr\u00E9': 'sidebar', u'sujet': 'topic', u'bloc-textuel': 'line-block', u'bloc-interpr\u00E9t\u00E9': 'parsed-literal', u'code-interpr\u00E9t\u00E9': 'parsed-literal', u'intertitre': 'rubric', u'exergue': 'epigraph', u'\u00E9pigraphe': 'epigraph', u'chapeau': 'highlights', u'accroche': 'pull-quote', u'compound (translation required)': 'compound', u'container (translation required)': 'container', #u'questions': 'questions', #u'qr': 'questions', #u'faq': 'questions', u'tableau': 'table', u'csv-table (translation required)': 'csv-table', u'list-table (translation required)': 'list-table', u'm\u00E9ta': 'meta', #u'imagemap (translation required)': 'imagemap', u'image': 'image', u'figure': 'figure', u'inclure': 'include', u'brut': 'raw', u'remplacer': 'replace', u'remplace': 'replace', u'unicode': 'unicode', u'date': 'date', u'classe': 'class', u'role (translation required)': 'role', u'default-role (translation required)': 'default-role', u'titre (translation required)': 'title', u'sommaire': 'contents', u'table-des-mati\u00E8res': 'contents', u'sectnum': 'sectnum', u'section-num\u00E9rot\u00E9e': 'sectnum', u'liens': 'target-notes', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #u'footnotes (translation required)': 'footnotes', #u'citations (translation required)': 'citations', } """French name to registered (in directives/__init__.py) directive name mapping.""" roles = { u'abr\u00E9viation': 'abbreviation', u'acronyme': 'acronym', u'sigle': 'acronym', u'index': 'index', u'indice': 'subscript', u'ind': 'subscript', u'exposant': 'superscript', u'exp': 'superscript', u'titre-r\u00E9f\u00E9rence': 'title-reference', u'titre': 'title-reference', u'pep-r\u00E9f\u00E9rence': 'pep-reference', u'rfc-r\u00E9f\u00E9rence': 'rfc-reference', u'emphase': 'emphasis', u'fort': 'strong', u'litt\u00E9ral': 'literal', u'nomm\u00E9e-r\u00E9f\u00E9rence': 'named-reference', u'anonyme-r\u00E9f\u00E9rence': 'anonymous-reference', u'note-r\u00E9f\u00E9rence': 'footnote-reference', u'citation-r\u00E9f\u00E9rence': 'citation-reference', u'substitution-r\u00E9f\u00E9rence': 'substitution-reference', u'lien': 'target', u'uri-r\u00E9f\u00E9rence': 'uri-reference', u'brut': 'raw',} """Mapping of French role names to canonical role names for interpreted text. """
Python
# $Id: nl.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Martijn Pieters <mjpieters@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Dutch-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed 'attentie': 'attention', 'let-op': 'caution', 'gevaar': 'danger', 'fout': 'error', 'hint': 'hint', 'belangrijk': 'important', 'opmerking': 'note', 'tip': 'tip', 'waarschuwing': 'warning', 'aanmaning': 'admonition', 'katern': 'sidebar', 'onderwerp': 'topic', 'lijn-blok': 'line-block', 'letterlijk-ontleed': 'parsed-literal', 'rubriek': 'rubric', 'opschrift': 'epigraph', 'hoogtepunten': 'highlights', 'pull-quote': 'pull-quote', # Dutch printers use the english term 'samenstelling': 'compound', 'verbinding': 'compound', u'container (translation required)': 'container', #'vragen': 'questions', 'tabel': 'table', 'csv-tabel': 'csv-table', 'lijst-tabel': 'list-table', #'veelgestelde-vragen': 'questions', 'meta': 'meta', #'imagemap': 'imagemap', 'beeld': 'image', 'figuur': 'figure', 'opnemen': 'include', 'onbewerkt': 'raw', 'vervang': 'replace', 'vervanging': 'replace', 'unicode': 'unicode', 'datum': 'date', 'klasse': 'class', 'rol': 'role', u'default-role (translation required)': 'default-role', 'title (translation required)': 'title', 'inhoud': 'contents', 'sectnum': 'sectnum', 'sectie-nummering': 'sectnum', 'hoofdstuk-nummering': 'sectnum', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #'voetnoten': 'footnotes', #'citaten': 'citations', 'verwijzing-voetnoten': 'target-notes', 'restructuredtext-test-instructie': 'restructuredtext-test-directive'} """Dutch name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed 'afkorting': 'abbreviation', # 'ab': 'abbreviation', 'acroniem': 'acronym', 'ac': 'acronym', 'index': 'index', 'i': 'index', 'inferieur': 'subscript', 'inf': 'subscript', 'superieur': 'superscript', 'sup': 'superscript', 'titel-referentie': 'title-reference', 'titel': 'title-reference', 't': 'title-reference', 'pep-referentie': 'pep-reference', 'pep': 'pep-reference', 'rfc-referentie': 'rfc-reference', 'rfc': 'rfc-reference', 'nadruk': 'emphasis', 'extra': 'strong', 'extra-nadruk': 'strong', 'vet': 'strong', 'letterlijk': 'literal', 'benoemde-referentie': 'named-reference', 'anonieme-referentie': 'anonymous-reference', 'voetnoot-referentie': 'footnote-reference', 'citaat-referentie': 'citation-reference', 'substitie-reference': 'substitution-reference', 'verwijzing': 'target', 'uri-referentie': 'uri-reference', 'uri': 'uri-reference', 'url': 'uri-reference', 'onbewerkt': 'raw',} """Mapping of Dutch role names to canonical role names for interpreted text. """
Python
# -*- coding: utf-8 -*- # $Id: zh_tw.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Traditional Chinese language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed 'attention (translation required)': 'attention', 'caution (translation required)': 'caution', 'danger (translation required)': 'danger', 'error (translation required)': 'error', 'hint (translation required)': 'hint', 'important (translation required)': 'important', 'note (translation required)': 'note', 'tip (translation required)': 'tip', 'warning (translation required)': 'warning', 'admonition (translation required)': 'admonition', 'sidebar (translation required)': 'sidebar', 'topic (translation required)': 'topic', 'line-block (translation required)': 'line-block', 'parsed-literal (translation required)': 'parsed-literal', 'rubric (translation required)': 'rubric', 'epigraph (translation required)': 'epigraph', 'highlights (translation required)': 'highlights', 'pull-quote (translation required)': 'pull-quote', 'compound (translation required)': 'compound', u'container (translation required)': 'container', #'questions (translation required)': 'questions', 'table (translation required)': 'table', 'csv-table (translation required)': 'csv-table', 'list-table (translation required)': 'list-table', #'qa (translation required)': 'questions', #'faq (translation required)': 'questions', 'meta (translation required)': 'meta', #'imagemap (translation required)': 'imagemap', 'image (translation required)': 'image', 'figure (translation required)': 'figure', 'include (translation required)': 'include', 'raw (translation required)': 'raw', 'replace (translation required)': 'replace', 'unicode (translation required)': 'unicode', u'日期': 'date', 'class (translation required)': 'class', 'role (translation required)': 'role', u'default-role (translation required)': 'default-role', u'title (translation required)': 'title', 'contents (translation required)': 'contents', 'sectnum (translation required)': 'sectnum', 'section-numbering (translation required)': 'sectnum', u'header (translation required)': 'header', u'footer (translation required)': 'footer', #'footnotes (translation required)': 'footnotes', #'citations (translation required)': 'citations', 'target-notes (translation required)': 'target-notes', 'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Traditional Chinese name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed 'abbreviation (translation required)': 'abbreviation', 'ab (translation required)': 'abbreviation', 'acronym (translation required)': 'acronym', 'ac (translation required)': 'acronym', 'index (translation required)': 'index', 'i (translation required)': 'index', 'subscript (translation required)': 'subscript', 'sub (translation required)': 'subscript', 'superscript (translation required)': 'superscript', 'sup (translation required)': 'superscript', 'title-reference (translation required)': 'title-reference', 'title (translation required)': 'title-reference', 't (translation required)': 'title-reference', 'pep-reference (translation required)': 'pep-reference', 'pep (translation required)': 'pep-reference', 'rfc-reference (translation required)': 'rfc-reference', 'rfc (translation required)': 'rfc-reference', 'emphasis (translation required)': 'emphasis', 'strong (translation required)': 'strong', 'literal (translation required)': 'literal', 'named-reference (translation required)': 'named-reference', 'anonymous-reference (translation required)': 'anonymous-reference', 'footnote-reference (translation required)': 'footnote-reference', 'citation-reference (translation required)': 'citation-reference', 'substitution-reference (translation required)': 'substitution-reference', 'target (translation required)': 'target', 'uri-reference (translation required)': 'uri-reference', 'uri (translation required)': 'uri-reference', 'url (translation required)': 'uri-reference', 'raw (translation required)': 'raw',} """Mapping of Traditional Chinese role names to canonical role names for interpreted text."""
Python
# $Id: eo.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Marcelo Huerta San Martin <richieadler@users.sourceforge.net> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Esperanto-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed u'atentu': 'attention', u'zorgu': 'caution', u'dangxero': 'danger', u'dan\u011dero': 'danger', u'eraro': 'error', u'spuro': 'hint', u'grava': 'important', u'noto': 'note', u'helpeto': 'tip', u'averto': 'warning', u'admono': 'admonition', u'flankteksto': 'sidebar', u'temo': 'topic', u'linea-bloko': 'line-block', u'analizota-literalo': 'parsed-literal', u'rubriko': 'rubric', u'epigrafo': 'epigraph', u'elstarajxoj': 'highlights', u'elstara\u0135oj': 'highlights', u'ekstera-citajxo': 'pull-quote', u'ekstera-cita\u0135o': 'pull-quote', u'kombinajxo': 'compound', u'kombina\u0135o': 'compound', u'tekstingo': 'container', u'enhavilo': 'container', #'questions': 'questions', #'qa': 'questions', #'faq': 'questions', u'tabelo': 'table', u'tabelo-vdk': 'csv-table', # "valoroj disigitaj per komoj" u'tabelo-csv': 'csv-table', u'tabelo-lista': 'list-table', u'meta': 'meta', #'imagemap': 'imagemap', u'bildo': 'image', u'figuro': 'figure', u'inkludi': 'include', u'senanaliza': 'raw', u'anstatauxi': 'replace', u'anstata\u016di': 'replace', u'unicode': 'unicode', u'dato': 'date', u'klaso': 'class', u'rolo': 'role', u'preterlasita-rolo': 'default-role', u'titolo': 'title', u'enhavo': 'contents', u'seknum': 'sectnum', u'sekcia-numerado': 'sectnum', u'kapsekcio': 'header', u'piedsekcio': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', u'celaj-notoj': 'target-notes', u'restructuredtext-test-directive': 'restructuredtext-test-directive'} """Esperanto name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed u'mallongigo': 'abbreviation', u'mall': 'abbreviation', u'komenclitero': 'acronym', u'kl': 'acronym', u'indekso': 'index', u'i': 'index', u'subskribo': 'subscript', u'sub': 'subscript', u'supraskribo': 'superscript', u'sup': 'superscript', u'titola-referenco': 'title-reference', u'titolo': 'title-reference', u't': 'title-reference', u'pep-referenco': 'pep-reference', u'pep': 'pep-reference', u'rfc-referenco': 'rfc-reference', u'rfc': 'rfc-reference', u'emfazo': 'emphasis', u'forta': 'strong', u'litera': 'literal', u'nomita-referenco': 'named-reference', u'nenomita-referenco': 'anonymous-reference', u'piednota-referenco': 'footnote-reference', u'citajxo-referenco': 'citation-reference', u'cita\u0135o-referenco': 'citation-reference', u'anstatauxa-referenco': 'substitution-reference', u'anstata\u016da-referenco': 'substitution-reference', u'celo': 'target', u'uri-referenco': 'uri-reference', u'uri': 'uri-reference', u'url': 'uri-reference', u'senanaliza': 'raw', } """Mapping of Esperanto role names to canonical role names for interpreted text. """
Python
# $Id: __init__.py 5618 2008-07-28 08:37:32Z strank $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # Internationalization details are documented in # <http://docutils.sf.net/docs/howto/i18n.html>. """ This package contains modules for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' _languages = {} def get_language(language_code): if language_code in _languages: return _languages[language_code] try: module = __import__(language_code, globals(), locals()) except ImportError: return None _languages[language_code] = module return module
Python
# $Id: tables.py 6107 2009-08-31 02:29:08Z goodger $ # Authors: David Goodger <goodger@python.org>; David Priest # Copyright: This module has been placed in the public domain. """ Directives for table elements. """ __docformat__ = 'reStructuredText' import sys import os.path import csv from docutils import io, nodes, statemachine, utils from docutils.utils import SystemMessagePropagation from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class Table(Directive): """ Generic table base class. """ required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = {'class': directives.class_option} has_content = True def make_title(self): if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: title = None messages = [] return title, messages def process_header_option(self): source = self.state_machine.get_source(self.lineno - 1) table_head = [] max_header_cols = 0 if 'header' in self.options: # separate table header in option rows, max_header_cols = self.parse_csv_data_into_rows( self.options['header'].split('\n'), self.HeaderDialect(), source) table_head.extend(rows) return table_head, max_header_cols def check_table_dimensions(self, rows, header_rows, stub_columns): if len(rows) < header_rows: error = self.state_machine.reporter.error( '%s header row(s) specified but only %s row(s) of data ' 'supplied ("%s" directive).' % (header_rows, len(rows), self.name), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) if len(rows) == header_rows > 0: error = self.state_machine.reporter.error( 'Insufficient data supplied (%s row(s)); no data remaining ' 'for table body, required by "%s" directive.' % (len(rows), self.name), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) for row in rows: if len(row) < stub_columns: error = self.state_machine.reporter.error( '%s stub column(s) specified but only %s columns(s) of ' 'data supplied ("%s" directive).' % (stub_columns, len(row), self.name), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) if len(row) == stub_columns > 0: error = self.state_machine.reporter.error( 'Insufficient data supplied (%s columns(s)); no data remaining ' 'for table body, required by "%s" directive.' % (len(row), self.name), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) def get_column_widths(self, max_cols): if 'widths' in self.options: col_widths = self.options['widths'] if len(col_widths) != max_cols: error = self.state_machine.reporter.error( '"%s" widths do not match the number of columns in table ' '(%s).' % (self.name, max_cols), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) elif max_cols: col_widths = [100 // max_cols] * max_cols else: error = self.state_machine.reporter.error( 'No table data detected in CSV file.', nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) return col_widths def extend_short_rows_with_empty_cells(self, columns, parts): for part in parts: for row in part: if len(row) < columns: row.extend([(0, 0, 0, [])] * (columns - len(row))) class RSTTable(Table): def run(self): if not self.content: warning = self.state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [warning] title, messages = self.make_title() node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) if len(node) != 1 or not isinstance(node[0], nodes.table): error = self.state_machine.reporter.error( 'Error parsing content block for the "%s" directive: exactly ' 'one table expected.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [error] table_node = node[0] table_node['classes'] += self.options.get('class', []) if title: table_node.insert(0, title) return [table_node] + messages class CSVTable(Table): option_spec = {'header-rows': directives.nonnegative_int, 'stub-columns': directives.nonnegative_int, 'header': directives.unchanged, 'widths': directives.positive_int_list, 'file': directives.path, 'url': directives.uri, 'encoding': directives.encoding, 'class': directives.class_option, # field delimiter char 'delim': directives.single_char_or_whitespace_or_unicode, # treat whitespace after delimiter as significant 'keepspace': directives.flag, # text field quote/unquote char: 'quote': directives.single_char_or_unicode, # char used to escape delim & quote as-needed: 'escape': directives.single_char_or_unicode,} class DocutilsDialect(csv.Dialect): """CSV dialect for `csv_table` directive.""" delimiter = ',' quotechar = '"' doublequote = True skipinitialspace = True lineterminator = '\n' quoting = csv.QUOTE_MINIMAL def __init__(self, options): if 'delim' in options: self.delimiter = str(options['delim']) if 'keepspace' in options: self.skipinitialspace = False if 'quote' in options: self.quotechar = str(options['quote']) if 'escape' in options: self.doublequote = False self.escapechar = str(options['escape']) csv.Dialect.__init__(self) class HeaderDialect(csv.Dialect): """CSV dialect to use for the "header" option data.""" delimiter = ',' quotechar = '"' escapechar = '\\' doublequote = False skipinitialspace = True lineterminator = '\n' quoting = csv.QUOTE_MINIMAL def check_requirements(self): pass def run(self): try: if (not self.state.document.settings.file_insertion_enabled and ('file' in self.options or 'url' in self.options)): warning = self.state_machine.reporter.warning( 'File and URL access deactivated; ignoring "%s" ' 'directive.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [warning] self.check_requirements() title, messages = self.make_title() csv_data, source = self.get_csv_data() table_head, max_header_cols = self.process_header_option() rows, max_cols = self.parse_csv_data_into_rows( csv_data, self.DocutilsDialect(self.options), source) max_cols = max(max_cols, max_header_cols) header_rows = self.options.get('header-rows', 0) stub_columns = self.options.get('stub-columns', 0) self.check_table_dimensions(rows, header_rows, stub_columns) table_head.extend(rows[:header_rows]) table_body = rows[header_rows:] col_widths = self.get_column_widths(max_cols) self.extend_short_rows_with_empty_cells(max_cols, (table_head, table_body)) except SystemMessagePropagation, detail: return [detail.args[0]] except csv.Error, detail: error = self.state_machine.reporter.error( 'Error with CSV data in "%s" directive:\n%s' % (self.name, detail), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [error] table = (col_widths, table_head, table_body) table_node = self.state.build_table(table, self.content_offset, stub_columns) table_node['classes'] += self.options.get('class', []) if title: table_node.insert(0, title) return [table_node] + messages def get_csv_data(self): """ Get CSV data from the directive content, from an external file, or from a URL reference. """ encoding = self.options.get( 'encoding', self.state.document.settings.input_encoding) if self.content: # CSV data is from directive content. if 'file' in self.options or 'url' in self.options: error = self.state_machine.reporter.error( '"%s" directive may not both specify an external file and' ' have content.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) source = self.content.source(0) csv_data = self.content elif 'file' in self.options: # CSV data is from an external file. if 'url' in self.options: error = self.state_machine.reporter.error( 'The "file" and "url" options may not be simultaneously' ' specified for the "%s" directive.' % self.name, nodes.literal_block(self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) source_dir = os.path.dirname( os.path.abspath(self.state.document.current_source)) source = os.path.normpath(os.path.join(source_dir, self.options['file'])) source = utils.relative_path(None, source) try: self.state.document.settings.record_dependencies.add(source) csv_file = io.FileInput( source_path=source, encoding=encoding, error_handler=(self.state.document.settings.\ input_encoding_error_handler), handle_io_errors=None) csv_data = csv_file.read().splitlines() except IOError, error: severe = self.state_machine.reporter.severe( 'Problems with "%s" directive path:\n%s.' % (self.name, error), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(severe) elif 'url' in self.options: # CSV data is from a URL. # Do not import urllib2 at the top of the module because # it may fail due to broken SSL dependencies, and it takes # about 0.15 seconds to load. import urllib2 source = self.options['url'] try: csv_text = urllib2.urlopen(source).read() except (urllib2.URLError, IOError, OSError, ValueError), error: severe = self.state_machine.reporter.severe( 'Problems with "%s" directive URL "%s":\n%s.' % (self.name, self.options['url'], error), nodes.literal_block(self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(severe) csv_file = io.StringInput( source=csv_text, source_path=source, encoding=encoding, error_handler=(self.state.document.settings.\ input_encoding_error_handler)) csv_data = csv_file.read().splitlines() else: error = self.state_machine.reporter.warning( 'The "%s" directive requires content; none supplied.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) return csv_data, source if sys.version_info < (3,): # 2.x csv module doesn't do Unicode def decode_from_csv(s): return s.decode('utf-8') def encode_for_csv(s): return s.encode('utf-8') else: def decode_from_csv(s): return s def encode_for_csv(s): return s decode_from_csv = staticmethod(decode_from_csv) encode_for_csv = staticmethod(encode_for_csv) def parse_csv_data_into_rows(self, csv_data, dialect, source): # csv.py doesn't do Unicode; encode temporarily as UTF-8 csv_reader = csv.reader([self.encode_for_csv(line + '\n') for line in csv_data], dialect=dialect) rows = [] max_cols = 0 for row in csv_reader: row_data = [] for cell in row: # decode UTF-8 back to Unicode cell_text = self.decode_from_csv(cell) cell_data = (0, 0, 0, statemachine.StringList( cell_text.splitlines(), source=source)) row_data.append(cell_data) rows.append(row_data) max_cols = max(max_cols, len(row)) return rows, max_cols class ListTable(Table): """ Implement tables whose data is encoded as a uniform two-level bullet list. For further ideas, see http://docutils.sf.net/docs/dev/rst/alternatives.html#list-driven-tables """ option_spec = {'header-rows': directives.nonnegative_int, 'stub-columns': directives.nonnegative_int, 'widths': directives.positive_int_list, 'class': directives.class_option} def run(self): if not self.content: error = self.state_machine.reporter.error( 'The "%s" directive is empty; content required.' % self.name, nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [error] title, messages = self.make_title() node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) try: num_cols, col_widths = self.check_list_content(node) table_data = [[item.children for item in row_list[0]] for row_list in node[0]] header_rows = self.options.get('header-rows', 0) stub_columns = self.options.get('stub-columns', 0) self.check_table_dimensions(table_data, header_rows, stub_columns) except SystemMessagePropagation, detail: return [detail.args[0]] table_node = self.build_table_from_list(table_data, col_widths, header_rows, stub_columns) table_node['classes'] += self.options.get('class', []) if title: table_node.insert(0, title) return [table_node] + messages def check_list_content(self, node): if len(node) != 1 or not isinstance(node[0], nodes.bullet_list): error = self.state_machine.reporter.error( 'Error parsing content block for the "%s" directive: ' 'exactly one bullet list expected.' % self.name, nodes.literal_block(self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) list_node = node[0] # Check for a uniform two-level bullet list: for item_index in range(len(list_node)): item = list_node[item_index] if len(item) != 1 or not isinstance(item[0], nodes.bullet_list): error = self.state_machine.reporter.error( 'Error parsing content block for the "%s" directive: ' 'two-level bullet list expected, but row %s does not ' 'contain a second-level bullet list.' % (self.name, item_index + 1), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) elif item_index: # ATTN pychecker users: num_cols is guaranteed to be set in the # "else" clause below for item_index==0, before this branch is # triggered. if len(item[0]) != num_cols: error = self.state_machine.reporter.error( 'Error parsing content block for the "%s" directive: ' 'uniform two-level bullet list expected, but row %s ' 'does not contain the same number of items as row 1 ' '(%s vs %s).' % (self.name, item_index + 1, len(item[0]), num_cols), nodes.literal_block(self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) else: num_cols = len(item[0]) col_widths = self.get_column_widths(num_cols) return num_cols, col_widths def build_table_from_list(self, table_data, col_widths, header_rows, stub_columns): table = nodes.table() tgroup = nodes.tgroup(cols=len(col_widths)) table += tgroup for col_width in col_widths: colspec = nodes.colspec(colwidth=col_width) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec rows = [] for row in table_data: row_node = nodes.row() for cell in row: entry = nodes.entry() entry += cell row_node += entry rows.append(row_node) if header_rows: thead = nodes.thead() thead.extend(rows[:header_rows]) tgroup += thead tbody = nodes.tbody() tbody.extend(rows[header_rows:]) tgroup += tbody return table
Python
# $Id: body.py 5618 2008-07-28 08:37:32Z strank $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Directives for additional body elements. See `docutils.parsers.rst.directives` for API details. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes from docutils.parsers.rst import Directive from docutils.parsers.rst import directives from docutils.parsers.rst.roles import set_classes class BasePseudoSection(Directive): required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'class': directives.class_option} has_content = True node_class = None """Node class to be used (must be set in subclasses).""" def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) self.assert_has_content() title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) titles = [nodes.title(title_text, '', *textnodes)] # Sidebar uses this code. if 'subtitle' in self.options: textnodes, more_messages = self.state.inline_text( self.options['subtitle'], self.lineno) titles.append(nodes.subtitle(self.options['subtitle'], '', *textnodes)) messages.extend(more_messages) text = '\n'.join(self.content) node = self.node_class(text, *(titles + messages)) node['classes'] += self.options.get('class', []) if text: self.state.nested_parse(self.content, self.content_offset, node) return [node] class Topic(BasePseudoSection): node_class = nodes.topic class Sidebar(BasePseudoSection): node_class = nodes.sidebar option_spec = BasePseudoSection.option_spec.copy() option_spec['subtitle'] = directives.unchanged_required def run(self): if isinstance(self.state_machine.node, nodes.sidebar): raise self.error('The "%s" directive may not be used within a ' 'sidebar element.' % self.name) return BasePseudoSection.run(self) class LineBlock(Directive): option_spec = {'class': directives.class_option} has_content = True def run(self): self.assert_has_content() block = nodes.line_block(classes=self.options.get('class', [])) node_list = [block] for line_text in self.content: text_nodes, messages = self.state.inline_text( line_text.strip(), self.lineno + self.content_offset) line = nodes.line(line_text, '', *text_nodes) if line_text.strip(): line.indent = len(line_text) - len(line_text.lstrip()) block += line node_list.extend(messages) self.content_offset += 1 self.state.nest_line_block_lines(block) return node_list class ParsedLiteral(Directive): option_spec = {'class': directives.class_option} has_content = True def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) text_nodes, messages = self.state.inline_text(text, self.lineno) node = nodes.literal_block(text, '', *text_nodes, **self.options) node.line = self.content_offset + 1 return [node] + messages class Rubric(Directive): required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'class': directives.class_option} def run(self): set_classes(self.options) rubric_text = self.arguments[0] textnodes, messages = self.state.inline_text(rubric_text, self.lineno) rubric = nodes.rubric(rubric_text, '', *textnodes, **self.options) return [rubric] + messages class BlockQuote(Directive): has_content = True classes = [] def run(self): self.assert_has_content() elements = self.state.block_quote(self.content, self.content_offset) for element in elements: if isinstance(element, nodes.block_quote): element['classes'] += self.classes return elements class Epigraph(BlockQuote): classes = ['epigraph'] class Highlights(BlockQuote): classes = ['highlights'] class PullQuote(BlockQuote): classes = ['pull-quote'] class Compound(Directive): option_spec = {'class': directives.class_option} has_content = True def run(self): self.assert_has_content() text = '\n'.join(self.content) node = nodes.compound(text) node['classes'] += self.options.get('class', []) self.state.nested_parse(self.content, self.content_offset, node) return [node] class Container(Directive): required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True has_content = True def run(self): self.assert_has_content() text = '\n'.join(self.content) try: if self.arguments: classes = directives.class_option(self.arguments[0]) else: classes = [] except ValueError: raise self.error( 'Invalid class attribute value for "%s" directive: "%s".' % (self.name, self.arguments[0])) node = nodes.container(text) node['classes'].extend(classes) self.state.nested_parse(self.content, self.content_offset, node) return [node]
Python
# $Id: parts.py 5618 2008-07-28 08:37:32Z strank $ # Authors: David Goodger <goodger@python.org>; Dmitry Jemerov # Copyright: This module has been placed in the public domain. """ Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.transforms import parts from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class Contents(Directive): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, Contents.backlinks_values) if value == 'none': return None else: return value required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) document = self.state_machine.document language = languages.get_language(document.settings.language_code) if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if 'local' in self.options: title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += self.options.get('class', []) if 'local' in self.options: topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=self.block_text) pending.details.update(self.options) document.note_pending(pending) topic += pending return [topic] + messages class Sectnum(Directive): """Automatic section numbering.""" option_spec = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def run(self): pending = nodes.pending(parts.SectNum) pending.details.update(self.options) self.state_machine.document.note_pending(pending) return [pending] class Header(Directive): """Contents of document header.""" has_content = True def run(self): self.assert_has_content() header = self.state_machine.document.get_decoration().get_header() self.state.nested_parse(self.content, self.content_offset, header) return [] class Footer(Directive): """Contents of document footer.""" has_content = True def run(self): self.assert_has_content() footer = self.state_machine.document.get_decoration().get_footer() self.state.nested_parse(self.content, self.content_offset, footer) return []
Python
# $Id: references.py 4667 2006-07-12 21:40:56Z wiemann $ # Authors: David Goodger <goodger@python.org>; Dmitry Jemerov # Copyright: This module has been placed in the public domain. """ Directives for references and targets. """ __docformat__ = 'reStructuredText' from docutils import nodes from docutils.transforms import references from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class TargetNotes(Directive): """Target footnote generation.""" option_spec = {'class': directives.class_option} def run(self): pending = nodes.pending(references.TargetNotes) pending.details.update(self.options) self.state_machine.document.note_pending(pending) nodelist = [pending] return nodelist
Python
# $Id: images.py 5952 2009-05-19 08:45:27Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Directives for figures and simple images. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import Directive from docutils.parsers.rst import directives, states from docutils.nodes import fully_normalize_name, whitespace_normalize_name from docutils.parsers.rst.roles import set_classes try: import Image as PIL # PIL except ImportError: PIL = None class Image(Directive): align_h_values = ('left', 'center', 'right') align_v_values = ('top', 'middle', 'bottom') align_values = align_v_values + align_h_values def align(argument): # This is not callable as self.align. We cannot make it a # staticmethod because we're saving an unbound method in # option_spec below. return directives.choice(argument, Image.align_values) required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.percentage, 'align': align, 'target': directives.unchanged_required, 'class': directives.class_option} def run(self): if 'align' in self.options: if isinstance(self.state, states.SubstitutionDef): # Check for align_v_values. if self.options['align'] not in self.align_v_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value ' 'for the "align" option within a substitution ' 'definition. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_v_values))) elif self.options['align'] not in self.align_h_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_h_values))) messages = [] reference = directives.uri(self.arguments[0]) self.options['uri'] = reference reference_node = None if 'target' in self.options: block = states.escape2null( self.options['target']).splitlines() block = [line for line in block] target_type, data = self.state.parse_target( block, self.block_text, self.lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference( refname=fully_normalize_name(data), name=whitespace_normalize_name(data)) reference_node.indirect_reference_name = data self.state.document.note_refname(reference_node) else: # malformed target messages.append(data) # data is a system message del self.options['target'] set_classes(self.options) image_node = nodes.image(self.block_text, **self.options) if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node] class Figure(Image): def align(argument): return directives.choice(argument, Figure.align_h_values) def figwidth_value(argument): if argument.lower() == 'image': return 'image' else: return directives.length_or_percentage_or_unitless(argument, 'px') option_spec = Image.option_spec.copy() option_spec['figwidth'] = figwidth_value option_spec['figclass'] = directives.class_option option_spec['align'] = align has_content = True def run(self): figwidth = self.options.pop('figwidth', None) figclasses = self.options.pop('figclass', None) align = self.options.pop('align', None) (image_node,) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if PIL and self.state.document.settings.file_insertion_enabled: # PIL doesn't like Unicode paths: try: i = PIL.open(str(image_node['uri'])) except (IOError, UnicodeError): pass else: self.state.document.settings.record_dependencies.add( image_node['uri']) figure_node['width'] = i.size[0] elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if self.content: node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = self.state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node]
Python
# $Id: html.py 4667 2006-07-12 21:40:56Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Directives for typically HTML-specific constructs. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import Directive from docutils.parsers.rst import states from docutils.transforms import components class MetaBody(states.SpecializedBody): class meta(nodes.Special, nodes.PreBibliographic, nodes.Element): """HTML-specific "meta" element.""" pass def field_marker(self, match, context, next_state): """Meta element.""" node, blank_finish = self.parsemeta(match) self.parent += node return [], next_state, [] def parsemeta(self, match): name = self.parse_field_marker(match) indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) node = self.meta() pending = nodes.pending(components.Filter, {'component': 'writer', 'format': 'html', 'nodes': [node]}) node['content'] = ' '.join(indented) if not indented: line = self.state_machine.line msg = self.reporter.info( 'No content for meta tag "%s".' % name, nodes.literal_block(line, line), line=self.state_machine.abs_line_number()) return msg, blank_finish tokens = name.split() try: attname, val = utils.extract_name_value(tokens[0])[0] node[attname.lower()] = val except utils.NameValueError: node['name'] = tokens[0] for token in tokens[1:]: try: attname, val = utils.extract_name_value(token)[0] node[attname.lower()] = val except utils.NameValueError, detail: line = self.state_machine.line msg = self.reporter.error( 'Error parsing meta tag attribute "%s": %s.' % (token, detail), nodes.literal_block(line, line), line=self.state_machine.abs_line_number()) return msg, blank_finish self.document.note_pending(pending) return pending, blank_finish class Meta(Directive): has_content = True SMkwargs = {'state_classes': (MetaBody,)} def run(self): self.assert_has_content() node = nodes.Element() new_line_offset, blank_finish = self.state.nested_list_parse( self.content, self.content_offset, node, initial_state='MetaBody', blank_finish=1, state_machine_kwargs=self.SMkwargs) if (new_line_offset - self.content_offset) != len(self.content): # incomplete parse of block? error = self.state_machine.reporter.error( 'Invalid meta directive.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) node += error return node.children
Python
# $Id: admonitions.py 5618 2008-07-28 08:37:32Z strank $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils import nodes class BaseAdmonition(Directive): required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True option_spec = {} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text) if self.arguments: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) admonition_node += nodes.title(title_text, '', *textnodes) admonition_node += messages if 'class' in self.options: classes = self.options['class'] else: classes = ['admonition-' + nodes.make_id(title_text)] admonition_node['classes'] += classes self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 option_spec = {'class': directives.class_option} node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning
Python
# $Id: __init__.py 5952 2009-05-19 08:45:27Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This package contains directive implementation modules. """ __docformat__ = 'reStructuredText' import re import codecs from docutils import nodes from docutils.parsers.rst.languages import en as _fallback_language_module _directive_registry = { 'attention': ('admonitions', 'Attention'), 'caution': ('admonitions', 'Caution'), 'danger': ('admonitions', 'Danger'), 'error': ('admonitions', 'Error'), 'important': ('admonitions', 'Important'), 'note': ('admonitions', 'Note'), 'tip': ('admonitions', 'Tip'), 'hint': ('admonitions', 'Hint'), 'warning': ('admonitions', 'Warning'), 'admonition': ('admonitions', 'Admonition'), 'sidebar': ('body', 'Sidebar'), 'topic': ('body', 'Topic'), 'line-block': ('body', 'LineBlock'), 'parsed-literal': ('body', 'ParsedLiteral'), 'rubric': ('body', 'Rubric'), 'epigraph': ('body', 'Epigraph'), 'highlights': ('body', 'Highlights'), 'pull-quote': ('body', 'PullQuote'), 'compound': ('body', 'Compound'), 'container': ('body', 'Container'), #'questions': ('body', 'question_list'), 'table': ('tables', 'RSTTable'), 'csv-table': ('tables', 'CSVTable'), 'list-table': ('tables', 'ListTable'), 'image': ('images', 'Image'), 'figure': ('images', 'Figure'), 'contents': ('parts', 'Contents'), 'sectnum': ('parts', 'Sectnum'), 'header': ('parts', 'Header'), 'footer': ('parts', 'Footer'), #'footnotes': ('parts', 'footnotes'), #'citations': ('parts', 'citations'), 'target-notes': ('references', 'TargetNotes'), 'meta': ('html', 'Meta'), #'imagemap': ('html', 'imagemap'), 'raw': ('misc', 'Raw'), 'include': ('misc', 'Include'), 'replace': ('misc', 'Replace'), 'unicode': ('misc', 'Unicode'), 'class': ('misc', 'Class'), 'role': ('misc', 'Role'), 'default-role': ('misc', 'DefaultRole'), 'title': ('misc', 'Title'), 'date': ('misc', 'Date'), 'restructuredtext-test-directive': ('misc', 'TestDirective'),} """Mapping of directive name to (module name, class name). The directive name is canonical & must be lowercase. Language-dependent names are defined in the ``language`` subpackage.""" _directives = {} """Cache of imported directives.""" def directive(directive_name, language_module, document): """ Locate and return a directive function from its language-dependent name. If not found in the current language, check English. Return None if the named directive cannot be found. """ normname = directive_name.lower() messages = [] msg_text = [] if normname in _directives: return _directives[normname], messages canonicalname = None try: canonicalname = language_module.directives[normname] except AttributeError, error: msg_text.append('Problem retrieving directive entry from language ' 'module %r: %s.' % (language_module, error)) except KeyError: msg_text.append('No directive entry for "%s" in module "%s".' % (directive_name, language_module.__name__)) if not canonicalname: try: canonicalname = _fallback_language_module.directives[normname] msg_text.append('Using English fallback for directive "%s".' % directive_name) except KeyError: msg_text.append('Trying "%s" as canonical directive name.' % directive_name) # The canonical name should be an English name, but just in case: canonicalname = normname if msg_text: message = document.reporter.info( '\n'.join(msg_text), line=document.current_line) messages.append(message) try: modulename, classname = _directive_registry[canonicalname] except KeyError: # Error handling done by caller. return None, messages try: module = __import__(modulename, globals(), locals()) except ImportError, detail: messages.append(document.reporter.error( 'Error importing directive module "%s" (directive "%s"):\n%s' % (modulename, directive_name, detail), line=document.current_line)) return None, messages try: directive = getattr(module, classname) _directives[normname] = directive except AttributeError: messages.append(document.reporter.error( 'No directive class "%s" in module "%s" (directive "%s").' % (classname, modulename, directive_name), line=document.current_line)) return None, messages return directive, messages def register_directive(name, directive): """ Register a nonstandard application-defined directive function. Language lookups are not needed for such functions. """ _directives[name] = directive def flag(argument): """ Check for a valid flag option (no argument) and return ``None``. (Directive option conversion function.) Raise ``ValueError`` if an argument is found. """ if argument and argument.strip(): raise ValueError('no argument is allowed; "%s" supplied' % argument) else: return None def unchanged_required(argument): """ Return the argument text, unchanged. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: return argument # unchanged! def unchanged(argument): """ Return the argument text, unchanged. (Directive option conversion function.) No argument implies empty string (""). """ if argument is None: return u'' else: return argument # unchanged! def path(argument): """ Return the path argument unwrapped (with newlines removed). (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: path = ''.join([s.strip() for s in argument.splitlines()]) return path def uri(argument): """ Return the URI argument with whitespace removed. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: uri = ''.join(argument.split()) return uri def nonnegative_int(argument): """ Check for a nonnegative integer argument; raise ``ValueError`` if not. (Directive option conversion function.) """ value = int(argument) if value < 0: raise ValueError('negative value; must be positive or zero') return value def percentage(argument): """ Check for an integer percentage value with optional percent sign. """ try: argument = argument.rstrip(' %') except AttributeError: pass return nonnegative_int(argument) length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc'] def get_measure(argument, units): """ Check for a positive argument of one of the units and return a normalized string of the form "<value><unit>" (without space in between). To be called from directive option conversion functions. """ match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument) try: assert match is not None float(match.group(1)) except (AssertionError, ValueError): raise ValueError( 'not a positive measure of one of the following units:\n%s' % ' '.join(['"%s"' % i for i in units])) return match.group(1) + match.group(2) def length_or_unitless(argument): return get_measure(argument, length_units + ['']) def length_or_percentage_or_unitless(argument, default=''): """ Return normalized string of a length or percentage unit. Add <default> if there is no unit. Raise ValueError if the argument is not a positive measure of one of the valid CSS units (or without unit). >>> length_or_percentage_or_unitless('3 pt') '3pt' >>> length_or_percentage_or_unitless('3%', 'em') '3%' >>> length_or_percentage_or_unitless('3') '3' >>> length_or_percentage_or_unitless('3', 'px') '3px' """ try: return get_measure(argument, length_units + ['%']) except ValueError: return get_measure(argument, ['']) + default def class_option(argument): """ Convert the argument into a list of ID-compatible strings and return it. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') names = argument.split() class_names = [] for name in names: class_name = nodes.make_id(name) if not class_name: raise ValueError('cannot make "%s" into a class name' % name) class_names.append(class_name) return class_names unicode_pattern = re.compile( r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE) def unicode_code(code): r""" Convert a Unicode character code to a Unicode character. (Directive option conversion function.) Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``, ``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style numeric character entities (e.g. ``&#x262E;``). Other text remains as-is. Raise ValueError for illegal Unicode code values. """ try: if code.isdigit(): # decimal number return unichr(int(code)) else: match = unicode_pattern.match(code) if match: # hex number value = match.group(1) or match.group(2) return unichr(int(value, 16)) else: # other text return code except OverflowError, detail: raise ValueError('code too large (%s)' % detail) def single_char_or_unicode(argument): """ A single character is returned as-is. Unicode characters codes are converted as in `unicode_code`. (Directive option conversion function.) """ char = unicode_code(argument) if len(char) > 1: raise ValueError('%r invalid; must be a single character or ' 'a Unicode code' % char) return char def single_char_or_whitespace_or_unicode(argument): """ As with `single_char_or_unicode`, but "tab" and "space" are also supported. (Directive option conversion function.) """ if argument == 'tab': char = '\t' elif argument == 'space': char = ' ' else: char = single_char_or_unicode(argument) return char def positive_int(argument): """ Converts the argument into an integer. Raises ValueError for negative, zero, or non-integer values. (Directive option conversion function.) """ value = int(argument) if value < 1: raise ValueError('negative or zero value; must be positive') return value def positive_int_list(argument): """ Converts a space- or comma-separated list of values into a Python list of integers. (Directive option conversion function.) Raises ValueError for non-positive-integer values. """ if ',' in argument: entries = argument.split(',') else: entries = argument.split() return [positive_int(entry) for entry in entries] def encoding(argument): """ Verfies the encoding argument by lookup. (Directive option conversion function.) Raises ValueError for unknown encodings. """ try: codecs.lookup(argument) except LookupError: raise ValueError('unknown encoding: "%s"' % argument) return argument def choice(argument, values): """ Directive option utility function, supplied to enable options whose argument must be a member of a finite set of possible values (must be lower case). A custom conversion function must be written to use it. For example:: from docutils.parsers.rst import directives def yesno(argument): return directives.choice(argument, ('yes', 'no')) Raise ``ValueError`` if no argument is found or if the argument's value is not valid (not an entry in the supplied list). """ try: value = argument.lower().strip() except AttributeError: raise ValueError('must supply an argument; choose from %s' % format_values(values)) if value in values: return value else: raise ValueError('"%s" unknown; choose from %s' % (argument, format_values(values))) def format_values(values): return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]), values[-1])
Python
# $Id: misc.py 6185 2009-10-25 20:43:42Z milde $ # Authors: David Goodger <goodger@python.org>; Dethe Elza # Copyright: This module has been placed in the public domain. """Miscellaneous directives.""" __docformat__ = 'reStructuredText' import sys import os.path import re import time from docutils import io, nodes, statemachine, utils from docutils.parsers.rst import Directive, convert_directive_function from docutils.parsers.rst import directives, roles, states from docutils.transforms import misc class Include(Directive): """ Include content read from a separate source file. Content may be parsed by the parser, or included as a literal block. The encoding of the included file can be specified. Only a part of the given file argument may be included by specifying start and end line or text to match before and/or after the text to be used. """ required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'literal': directives.flag, 'encoding': directives.encoding, 'tab-width': int, 'start-line': int, 'end-line': int, 'start-after': directives.unchanged_required, 'end-before': directives.unchanged_required} standard_include_path = os.path.join(os.path.dirname(states.__file__), 'include') def run(self): """Include a reST file as part of the content of this reST file.""" if not self.state.document.settings.file_insertion_enabled: raise self.warning('"%s" directive disabled.' % self.name) source = self.state_machine.input_lines.source( self.lineno - self.state_machine.input_offset - 1) source_dir = os.path.dirname(os.path.abspath(source)) path = directives.path(self.arguments[0]) if path.startswith('<') and path.endswith('>'): path = os.path.join(self.standard_include_path, path[1:-1]) path = os.path.normpath(os.path.join(source_dir, path)) path = utils.relative_path(None, path) path = nodes.reprunicode(path) encoding = self.options.get( 'encoding', self.state.document.settings.input_encoding) tab_width = self.options.get( 'tab-width', self.state.document.settings.tab_width) try: self.state.document.settings.record_dependencies.add(path) include_file = io.FileInput( source_path=path, encoding=encoding, error_handler=(self.state.document.settings.\ input_encoding_error_handler), handle_io_errors=None) except IOError, error: raise self.severe('Problems with "%s" directive path:\n%s: %s.' % (self.name, error.__class__.__name__, str(error))) # Hack: Since Python 2.6, the string interpolation returns a # unicode object if one of the supplied %s replacements is a # unicode object. IOError has no `__unicode__` method and the # fallback `__repr__` does not report the file name. Explicitely # converting to str fixes this for now:: # print '%s\n%s\n%s\n' %(error, str(error), repr(error)) startline = self.options.get('start-line', None) endline = self.options.get('end-line', None) try: if startline or (endline is not None): lines = include_file.readlines() rawtext = ''.join(lines[startline:endline]) else: rawtext = include_file.read() except UnicodeError, error: raise self.severe( 'Problem with "%s" directive:\n%s: %s' % (self.name, error.__class__.__name__, error)) # start-after/end-before: no restrictions on newlines in match-text, # and no restrictions on matching inside lines vs. line boundaries after_text = self.options.get('start-after', None) if after_text: # skip content in rawtext before *and incl.* a matching text after_index = rawtext.find(after_text) if after_index < 0: raise self.severe('Problem with "start-after" option of "%s" ' 'directive:\nText not found.' % self.name) rawtext = rawtext[after_index + len(after_text):] before_text = self.options.get('end-before', None) if before_text: # skip content in rawtext after *and incl.* a matching text before_index = rawtext.find(before_text) if before_index < 0: raise self.severe('Problem with "end-before" option of "%s" ' 'directive:\nText not found.' % self.name) rawtext = rawtext[:before_index] if 'literal' in self.options: # Convert tabs to spaces, if `tab_width` is positive. if tab_width >= 0: text = rawtext.expandtabs(tab_width) else: text = rawtext literal_block = nodes.literal_block(rawtext, text, source=path) literal_block.line = 1 return [literal_block] else: include_lines = statemachine.string2lines( rawtext, tab_width, convert_whitespace=1) self.state_machine.insert_input(include_lines, path) return [] class Raw(Directive): """ Pass through content unchanged Content is included in output based on type argument Content may be included inline (content section of directive) or imported from a file or url. """ required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'file': directives.path, 'url': directives.uri, 'encoding': directives.encoding} has_content = True def run(self): if (not self.state.document.settings.raw_enabled or (not self.state.document.settings.file_insertion_enabled and ('file' in self.options or 'url' in self.options))): raise self.warning('"%s" directive disabled.' % self.name) attributes = {'format': ' '.join(self.arguments[0].lower().split())} encoding = self.options.get( 'encoding', self.state.document.settings.input_encoding) if self.content: if 'file' in self.options or 'url' in self.options: raise self.error( '"%s" directive may not both specify an external file ' 'and have content.' % self.name) text = '\n'.join(self.content) elif 'file' in self.options: if 'url' in self.options: raise self.error( 'The "file" and "url" options may not be simultaneously ' 'specified for the "%s" directive.' % self.name) source_dir = os.path.dirname( os.path.abspath(self.state.document.current_source)) path = os.path.normpath(os.path.join(source_dir, self.options['file'])) path = utils.relative_path(None, path) try: self.state.document.settings.record_dependencies.add(path) raw_file = io.FileInput( source_path=path, encoding=encoding, error_handler=(self.state.document.settings.\ input_encoding_error_handler), handle_io_errors=None) except IOError, error: raise self.severe('Problems with "%s" directive path:\n%s.' % (self.name, error)) try: text = raw_file.read() except UnicodeError, error: raise self.severe( 'Problem with "%s" directive:\n%s: %s' % (self.name, error.__class__.__name__, error)) attributes['source'] = path elif 'url' in self.options: source = self.options['url'] # Do not import urllib2 at the top of the module because # it may fail due to broken SSL dependencies, and it takes # about 0.15 seconds to load. import urllib2 try: raw_text = urllib2.urlopen(source).read() except (urllib2.URLError, IOError, OSError), error: raise self.severe( 'Problems with "%s" directive URL "%s":\n%s.' % (self.name, self.options['url'], error)) raw_file = io.StringInput( source=raw_text, source_path=source, encoding=encoding, error_handler=(self.state.document.settings.\ input_encoding_error_handler)) try: text = raw_file.read() except UnicodeError, error: raise self.severe( 'Problem with "%s" directive:\n%s: %s' % (self.name, error.__class__.__name__, error)) attributes['source'] = source else: # This will always fail because there is no content. self.assert_has_content() raw_node = nodes.raw('', text, **attributes) return [raw_node] class Replace(Directive): has_content = True def run(self): if not isinstance(self.state, states.SubstitutionDef): raise self.error( 'Invalid context: the "%s" directive can only be used within ' 'a substitution definition.' % self.name) self.assert_has_content() text = '\n'.join(self.content) element = nodes.Element(text) self.state.nested_parse(self.content, self.content_offset, element) if ( len(element) != 1 or not isinstance(element[0], nodes.paragraph)): messages = [] for node in element: if isinstance(node, nodes.system_message): node['backrefs'] = [] messages.append(node) error = self.state_machine.reporter.error( 'Error in "%s" directive: may contain a single paragraph ' 'only.' % (self.name), line=self.lineno) messages.append(error) return messages else: return element[0].children class Unicode(Directive): r""" Convert Unicode character codes (numbers) to characters. Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``, ``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style numeric character entities (e.g. ``&#x262E;``). Text following ".." is a comment and is ignored. Spaces are ignored, and any other text remains as-is. """ required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'trim': directives.flag, 'ltrim': directives.flag, 'rtrim': directives.flag} comment_pattern = re.compile(r'( |\n|^)\.\. ') def run(self): if not isinstance(self.state, states.SubstitutionDef): raise self.error( 'Invalid context: the "%s" directive can only be used within ' 'a substitution definition.' % self.name) substitution_definition = self.state_machine.node if 'trim' in self.options: substitution_definition.attributes['ltrim'] = 1 substitution_definition.attributes['rtrim'] = 1 if 'ltrim' in self.options: substitution_definition.attributes['ltrim'] = 1 if 'rtrim' in self.options: substitution_definition.attributes['rtrim'] = 1 codes = self.comment_pattern.split(self.arguments[0])[0].split() element = nodes.Element() for code in codes: try: decoded = directives.unicode_code(code) except ValueError, err: raise self.error( 'Invalid character code: %s\n%s: %s' % (code, err.__class__.__name__, err)) element += nodes.Text(decoded) return element.children class Class(Directive): """ Set a "class" attribute on the directive content or the next element. When applied to the next element, a "pending" element is inserted, and a transform does the work later. """ required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True has_content = True def run(self): try: class_value = directives.class_option(self.arguments[0]) except ValueError: raise self.error( 'Invalid class attribute value for "%s" directive: "%s".' % (self.name, self.arguments[0])) node_list = [] if self.content: container = nodes.Element() self.state.nested_parse(self.content, self.content_offset, container) for node in container: node['classes'].extend(class_value) node_list.extend(container.children) else: pending = nodes.pending( misc.ClassAttribute, {'class': class_value, 'directive': self.name}, self.block_text) self.state_machine.document.note_pending(pending) node_list.append(pending) return node_list class Role(Directive): has_content = True argument_pattern = re.compile(r'(%s)\s*(\(\s*(%s)\s*\)\s*)?$' % ((states.Inliner.simplename,) * 2)) def run(self): """Dynamically create and register a custom interpreted text role.""" if self.content_offset > self.lineno or not self.content: raise self.error('"%s" directive requires arguments on the first ' 'line.' % self.name) args = self.content[0] match = self.argument_pattern.match(args) if not match: raise self.error('"%s" directive arguments not valid role names: ' '"%s".' % (self.name, args)) new_role_name = match.group(1) base_role_name = match.group(3) messages = [] if base_role_name: base_role, messages = roles.role( base_role_name, self.state_machine.language, self.lineno, self.state.reporter) if base_role is None: error = self.state.reporter.error( 'Unknown interpreted text role "%s".' % base_role_name, nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return messages + [error] else: base_role = roles.generic_custom_role assert not hasattr(base_role, 'arguments'), ( 'Supplemental directive arguments for "%s" directive not ' 'supported (specified by "%r" role).' % (self.name, base_role)) try: converted_role = convert_directive_function(base_role) (arguments, options, content, content_offset) = ( self.state.parse_directive_block( self.content[1:], self.content_offset, converted_role, option_presets={})) except states.MarkupError, detail: error = self.state_machine.reporter.error( 'Error in "%s" directive:\n%s.' % (self.name, detail), nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return messages + [error] if 'class' not in options: try: options['class'] = directives.class_option(new_role_name) except ValueError, detail: error = self.state_machine.reporter.error( 'Invalid argument for "%s" directive:\n%s.' % (self.name, detail), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return messages + [error] role = roles.CustomRole(new_role_name, base_role, options, content) roles.register_local_role(new_role_name, role) return messages class DefaultRole(Directive): """Set the default interpreted text role.""" required_arguments = 0 optional_arguments = 1 final_argument_whitespace = False def run(self): if not self.arguments: if '' in roles._roles: # restore the "default" default role del roles._roles[''] return [] role_name = self.arguments[0] role, messages = roles.role(role_name, self.state_machine.language, self.lineno, self.state.reporter) if role is None: error = self.state.reporter.error( 'Unknown interpreted text role "%s".' % role_name, nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return messages + [error] roles._roles[''] = role # @@@ should this be local to the document, not the parser? return messages class Title(Directive): required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True def run(self): self.state_machine.document['title'] = self.arguments[0] return [] class Date(Directive): has_content = True def run(self): if not isinstance(self.state, states.SubstitutionDef): raise self.error( 'Invalid context: the "%s" directive can only be used within ' 'a substitution definition.' % self.name) format = '\n'.join(self.content) or '%Y-%m-%d' text = time.strftime(format) return [nodes.Text(text)] class TestDirective(Directive): """This directive is useful only for testing purposes.""" required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = {'option': directives.unchanged_required} has_content = True def run(self): if self.content: text = '\n'.join(self.content) info = self.state_machine.reporter.info( 'Directive processed. Type="%s", arguments=%r, options=%r, ' 'content:' % (self.name, self.arguments, self.options), nodes.literal_block(text, text), line=self.lineno) else: info = self.state_machine.reporter.info( 'Directive processed. Type="%s", arguments=%r, options=%r, ' 'content: None' % (self.name, self.arguments, self.options), line=self.lineno) return [info] # Old-style, functional definition: # # def directive_test_function(name, arguments, options, content, lineno, # content_offset, block_text, state, state_machine): # """This directive is useful only for testing purposes.""" # if content: # text = '\n'.join(content) # info = state_machine.reporter.info( # 'Directive processed. Type="%s", arguments=%r, options=%r, ' # 'content:' % (name, arguments, options), # nodes.literal_block(text, text), line=lineno) # else: # info = state_machine.reporter.info( # 'Directive processed. Type="%s", arguments=%r, options=%r, ' # 'content: None' % (name, arguments, options), line=lineno) # return [info] # # directive_test_function.arguments = (0, 1, 1) # directive_test_function.options = {'option': directives.unchanged_required} # directive_test_function.content = 1
Python
# $Id: __init__.py 6314 2010-04-26 10:04:17Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This is ``docutils.parsers.rst`` package. It exports a single class, `Parser`, the reStructuredText parser. Usage ===== 1. Create a parser:: parser = docutils.parsers.rst.Parser() Several optional arguments may be passed to modify the parser's behavior. Please see `Customizing the Parser`_ below for details. 2. Gather input (a multi-line string), by reading a file or the standard input:: input = sys.stdin.read() 3. Create a new empty `docutils.nodes.document` tree:: document = docutils.utils.new_document(source, settings) See `docutils.utils.new_document()` for parameter details. 4. Run the parser, populating the document tree:: parser.parse(input, document) Parser Overview =============== The reStructuredText parser is implemented as a state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module, then see the `states` module. Customizing the Parser ---------------------- Anything that isn't already customizable is that way simply because that type of customizability hasn't been implemented yet. Patches welcome! When instantiating an object of the `Parser` class, two parameters may be passed: ``rfc2822`` and ``inliner``. Pass ``rfc2822=1`` to enable an initial RFC-2822 style header block, parsed as a "field_list" element (with "class" attribute set to "rfc2822"). Currently this is the only body-level element which is customizable without subclassing. (Tip: subclass `Parser` and change its "state_classes" and "initial_state" attributes to refer to new classes. Contact the author if you need more details.) The ``inliner`` parameter takes an instance of `states.Inliner` or a subclass. It handles inline markup recognition. A common extension is the addition of further implicit hyperlinks, like "RFC 2822". This can be done by subclassing `states.Inliner`, adding a new method for the implicit markup, and adding a ``(pattern, method)`` pair to the "implicit_dispatch" attribute of the subclass. See `states.Inliner.implicit_inline()` for details. Explicit inline markup can be customized in a `states.Inliner` subclass via the ``patterns.initial`` and ``dispatch`` attributes (and new methods as appropriate). """ __docformat__ = 'reStructuredText' import docutils.parsers import docutils.statemachine from docutils.parsers.rst import states from docutils import frontend, nodes class Parser(docutils.parsers.Parser): """The reStructuredText parser.""" supported = ('restructuredtext', 'rst', 'rest', 'restx', 'rtxt', 'rstx') """Aliases this parser supports.""" settings_spec = ( 'reStructuredText Parser Options', None, (('Recognize and link to standalone PEP references (like "PEP 258").', ['--pep-references'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Base URL for PEP references ' '(default "http://www.python.org/dev/peps/").', ['--pep-base-url'], {'metavar': '<URL>', 'default': 'http://www.python.org/dev/peps/', 'validator': frontend.validate_url_trailing_slash}), ('Template for PEP file part of URL. (default "pep-%04d")', ['--pep-file-url-template'], {'metavar': '<URL>', 'default': 'pep-%04d'}), ('Recognize and link to standalone RFC references (like "RFC 822").', ['--rfc-references'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Base URL for RFC references (default "http://www.faqs.org/rfcs/").', ['--rfc-base-url'], {'metavar': '<URL>', 'default': 'http://www.faqs.org/rfcs/', 'validator': frontend.validate_url_trailing_slash}), ('Set number of spaces for tab expansion (default 8).', ['--tab-width'], {'metavar': '<width>', 'type': 'int', 'default': 8, 'validator': frontend.validate_nonnegative_int}), ('Remove spaces before footnote references.', ['--trim-footnote-reference-space'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Leave spaces before footnote references.', ['--leave-footnote-reference-space'], {'action': 'store_false', 'dest': 'trim_footnote_reference_space'}), ('Disable directives that insert the contents of external file ' '("include" & "raw"); replaced with a "warning" system message.', ['--no-file-insertion'], {'action': 'store_false', 'default': 1, 'dest': 'file_insertion_enabled', 'validator': frontend.validate_boolean}), ('Enable directives that insert the contents of external file ' '("include" & "raw"). Enabled by default.', ['--file-insertion-enabled'], {'action': 'store_true'}), ('Disable the "raw" directives; replaced with a "warning" ' 'system message.', ['--no-raw'], {'action': 'store_false', 'default': 1, 'dest': 'raw_enabled', 'validator': frontend.validate_boolean}), ('Enable the "raw" directive. Enabled by default.', ['--raw-enabled'], {'action': 'store_true'}),)) config_section = 'restructuredtext parser' config_section_dependencies = ('parsers',) def __init__(self, rfc2822=None, inliner=None): if rfc2822: self.initial_state = 'RFC2822Body' else: self.initial_state = 'Body' self.state_classes = states.state_classes self.inliner = inliner def parse(self, inputstring, document): """Parse `inputstring` and populate `document`, a document tree.""" self.setup_parse(inputstring, document) self.statemachine = states.RSTStateMachine( state_classes=self.state_classes, initial_state=self.initial_state, debug=document.reporter.debug_flag) inputlines = docutils.statemachine.string2lines( inputstring, tab_width=document.settings.tab_width, convert_whitespace=1) self.statemachine.run(inputlines, document, inliner=self.inliner) self.finish_parse() class DirectiveError(Exception): """ Store a message and a system message level. To be thrown from inside directive code. Do not instantiate directly -- use `Directive.directive_error()` instead! """ def __init__(self, level, message): """Set error `message` and `level`""" Exception.__init__(self) self.level = level self.msg = message class Directive(object): """ Base class for reStructuredText directives. The following attributes may be set by subclasses. They are interpreted by the directive parser (which runs the directive class): - `required_arguments`: The number of required arguments (default: 0). - `optional_arguments`: The number of optional arguments (default: 0). - `final_argument_whitespace`: A boolean, indicating if the final argument may contain whitespace (default: False). - `option_spec`: A dictionary, mapping known option names to conversion functions such as `int` or `float` (default: {}, no options). Several conversion functions are defined in the directives/__init__.py module. Option conversion functions take a single parameter, the option argument (a string or ``None``), validate it and/or convert it to the appropriate form. Conversion functions may raise `ValueError` and `TypeError` exceptions. - `has_content`: A boolean; True if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Arguments are normally single whitespace-separated words. The final argument may contain whitespace and/or newlines if `final_argument_whitespace` is True. If the form of the arguments is more complex, specify only one argument (either required or optional) and set `final_argument_whitespace` to True; the client code must do any context-sensitive parsing. When a directive implementation is being run, the directive class is instantiated, and the `run()` method is executed. During instantiation, the following instance variables are set: - ``name`` is the directive type or name (string). - ``arguments`` is the list of positional arguments (strings). - ``options`` is a dictionary mapping option names (strings) to values (type depends on option conversion functions; see `option_spec` above). - ``content`` is a list of strings, the directive content line by line. - ``lineno`` is the absolute line number of the first line of the directive. - ``src`` is the name (or path) of the rst source of the directive. - ``srcline`` is the line number of the first line of the directive in its source. It may differ from ``lineno``, if the main source includes other sources with the ``.. include::`` directive. - ``content_offset`` is the line offset of the first line of the content from the beginning of the current input. Used when initiating a nested parse. - ``block_text`` is a string containing the entire directive. - ``state`` is the state which called the directive function. - ``state_machine`` is the state machine which controls the state which called the directive function. Directive functions return a list of nodes which will be inserted into the document tree at the point where the directive was encountered. This can be an empty list if there is nothing to insert. For ordinary directives, the list must contain body elements or structural elements. Some directives are intended specifically for substitution definitions, and must return a list of `Text` nodes and/or inline elements (suitable for inline insertion, in place of the substitution reference). Such directives must verify substitution definition context, typically using code like this:: if not isinstance(state, states.SubstitutionDef): error = state_machine.reporter.error( 'Invalid context: the "%s" directive can only be used ' 'within a substitution definition.' % (name), nodes.literal_block(block_text, block_text), line=lineno) return [error] """ # There is a "Creating reStructuredText Directives" how-to at # <http://docutils.sf.net/docs/howto/rst-directives.html>. If you # update this docstring, please update the how-to as well. required_arguments = 0 """Number of required directive arguments.""" optional_arguments = 0 """Number of optional arguments after the required arguments.""" final_argument_whitespace = False """May the final argument contain whitespace?""" option_spec = None """Mapping of option names to validator functions.""" has_content = False """May the directive have content?""" def __init__(self, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): self.name = name self.arguments = arguments self.options = options self.content = content self.lineno = lineno self.content_offset = content_offset self.block_text = block_text self.state = state self.state_machine = state_machine self.src, self.scrline = state_machine.get_source_and_line(lineno) def run(self): raise NotImplementedError('Must override run() is subclass.') # Directive errors: def directive_error(self, level, message): """ Return a DirectiveError suitable for being thrown as an exception. Call "raise self.directive_error(level, message)" from within a directive implementation to return one single system message at level `level`, which automatically gets the directive block and the line number added. You'd often use self.error(message) instead, which will generate an ERROR-level directive error. """ return DirectiveError(level, message) def debug(self, message): return self.directive_error(0, message) def info(self, message): return self.directive_error(1, message) def warning(self, message): return self.directive_error(2, message) def error(self, message): return self.directive_error(3, message) def severe(self, message): return self.directive_error(4, message) # Convenience methods: def assert_has_content(self): """ Throw an ERROR-level DirectiveError if the directive doesn't have contents. """ if not self.content: raise self.error('Content block expected for the "%s" directive; ' 'none found.' % self.name) def convert_directive_function(directive_fn): """ Define & return a directive class generated from `directive_fn`. `directive_fn` uses the old-style, functional interface. """ class FunctionalDirective(Directive): option_spec = getattr(directive_fn, 'options', None) has_content = getattr(directive_fn, 'content', False) _argument_spec = getattr(directive_fn, 'arguments', (0, 0, False)) required_arguments, optional_arguments, final_argument_whitespace \ = _argument_spec def run(self): return directive_fn( self.name, self.arguments, self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) # Return new-style directive. return FunctionalDirective
Python
# $Id: states.py 6314 2010-04-26 10:04:17Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This is the ``docutils.parsers.restructuredtext.states`` module, the core of the reStructuredText parser. It defines the following: :Classes: - `RSTStateMachine`: reStructuredText parser's entry point. - `NestedStateMachine`: recursive StateMachine. - `RSTState`: reStructuredText State superclass. - `Inliner`: For parsing inline markup. - `Body`: Generic classifier of the first line of a block. - `SpecializedBody`: Superclass for compound element members. - `BulletList`: Second and subsequent bullet_list list_items - `DefinitionList`: Second+ definition_list_items. - `EnumeratedList`: Second+ enumerated_list list_items. - `FieldList`: Second+ fields. - `OptionList`: Second+ option_list_items. - `RFC2822List`: Second+ RFC2822-style fields. - `ExtensionOptions`: Parses directive option fields. - `Explicit`: Second+ explicit markup constructs. - `SubstitutionDef`: For embedded directives in substitution definitions. - `Text`: Classifier of second line of a text block. - `SpecializedText`: Superclass for continuation lines of Text-variants. - `Definition`: Second line of potential definition_list_item. - `Line`: Second line of overlined section title or transition marker. - `Struct`: An auxiliary collection class. :Exception classes: - `MarkupError` - `ParserError` - `MarkupMismatch` :Functions: - `escape2null()`: Return a string, escape-backslashes converted to nulls. - `unescape()`: Return a string, nulls removed or restored to backslashes. :Attributes: - `state_classes`: set of State classes used with `RSTStateMachine`. Parser Overview =============== The reStructuredText parser is implemented as a recursive state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module. In the description below, references are made to classes defined in this module; please see the individual classes for details. Parsing proceeds as follows: 1. The state machine examines each line of input, checking each of the transition patterns of the state `Body`, in order, looking for a match. The implicit transitions (blank lines and indentation) are checked before any others. The 'text' transition is a catch-all (matches anything). 2. The method associated with the matched transition pattern is called. A. Some transition methods are self-contained, appending elements to the document tree (`Body.doctest` parses a doctest block). The parser's current line index is advanced to the end of the element, and parsing continues with step 1. B. Other transition methods trigger the creation of a nested state machine, whose job is to parse a compound construct ('indent' does a block quote, 'bullet' does a bullet list, 'overline' does a section [first checking for a valid section header], etc.). - In the case of lists and explicit markup, a one-off state machine is created and run to parse contents of the first item. - A new state machine is created and its initial state is set to the appropriate specialized state (`BulletList` in the case of the 'bullet' transition; see `SpecializedBody` for more detail). This state machine is run to parse the compound element (or series of explicit markup elements), and returns as soon as a non-member element is encountered. For example, the `BulletList` state machine ends as soon as it encounters an element which is not a list item of that bullet list. The optional omission of inter-element blank lines is enabled by this nested state machine. - The current line index is advanced to the end of the elements parsed, and parsing continues with step 1. C. The result of the 'text' transition depends on the next line of text. The current state is changed to `Text`, under which the second line is examined. If the second line is: - Indented: The element is a definition list item, and parsing proceeds similarly to step 2.B, using the `DefinitionList` state. - A line of uniform punctuation characters: The element is a section header; again, parsing proceeds as in step 2.B, and `Body` is still used. - Anything else: The element is a paragraph, which is examined for inline markup and appended to the parent element. Processing continues with step 1. """ __docformat__ = 'reStructuredText' import sys import re import roman from types import FunctionType, MethodType from docutils import nodes, statemachine, utils, urischemes from docutils import ApplicationError, DataError from docutils.statemachine import StateMachineWS, StateWS from docutils.nodes import fully_normalize_name as normalize_name from docutils.nodes import whitespace_normalize_name from docutils.utils import escape2null, unescape, column_width import docutils.parsers.rst from docutils.parsers.rst import directives, languages, tableparser, roles from docutils.parsers.rst.languages import en as _fallback_language_module class MarkupError(DataError): pass class UnknownInterpretedRoleError(DataError): pass class InterpretedRoleNotImplementedError(DataError): pass class ParserError(ApplicationError): pass class MarkupMismatch(Exception): pass class Struct: """Stores data attributes for dotted-attribute access.""" def __init__(self, **keywordargs): self.__dict__.update(keywordargs) class RSTStateMachine(StateMachineWS): """ reStructuredText's master StateMachine. The entry point to reStructuredText parsing is the `run()` method. """ def run(self, input_lines, document, input_offset=0, match_titles=1, inliner=None): """ Parse `input_lines` and modify the `document` node in place. Extend `StateMachineWS.run()`: set up parse-global data and run the StateMachine. """ self.language = languages.get_language( document.settings.language_code) self.match_titles = match_titles if inliner is None: inliner = Inliner() inliner.init_customizations(document.settings) self.memo = Struct(document=document, reporter=document.reporter, language=self.language, title_styles=[], section_level=0, section_bubble_up_kludge=0, inliner=inliner) self.document = document self.attach_observer(document.note_source) self.reporter = self.memo.reporter self.node = document results = StateMachineWS.run(self, input_lines, input_offset, input_source=document['source']) assert results == [], 'RSTStateMachine.run() results should be empty!' self.node = self.memo = None # remove unneeded references class NestedStateMachine(StateMachineWS): """ StateMachine run from within other StateMachine runs, to parse nested document structures. """ def run(self, input_lines, input_offset, memo, node, match_titles=1): """ Parse `input_lines` and populate a `docutils.nodes.document` instance. Extend `StateMachineWS.run()`: set up document-wide data. """ self.match_titles = match_titles self.memo = memo self.document = memo.document self.attach_observer(self.document.note_source) self.reporter = memo.reporter self.language = memo.language self.node = node results = StateMachineWS.run(self, input_lines, input_offset) assert results == [], ('NestedStateMachine.run() results should be ' 'empty!') return results class RSTState(StateWS): """ reStructuredText State superclass. Contains methods used by all State subclasses. """ nested_sm = NestedStateMachine nested_sm_cache = [] def __init__(self, state_machine, debug=0): self.nested_sm_kwargs = {'state_classes': state_classes, 'initial_state': 'Body'} StateWS.__init__(self, state_machine, debug) def runtime_init(self): StateWS.runtime_init(self) memo = self.state_machine.memo self.memo = memo self.reporter = memo.reporter self.inliner = memo.inliner self.document = memo.document self.parent = self.state_machine.node # enable the reporter to determine source and source-line if not hasattr(self.reporter, 'locator'): self.reporter.locator = self.state_machine.get_source_and_line # print "adding locator to reporter", self.state_machine.input_offset def goto_line(self, abs_line_offset): """ Jump to input line `abs_line_offset`, ignoring jumps past the end. """ try: self.state_machine.goto_line(abs_line_offset) except EOFError: pass def no_match(self, context, transitions): """ Override `StateWS.no_match` to generate a system message. This code should never be run. """ src, srcline = self.state_machine.get_source_and_line() self.reporter.severe( 'Internal error: no transition pattern match. State: "%s"; ' 'transitions: %s; context: %s; current line: %r.' % (self.__class__.__name__, transitions, context, self.state_machine.line), source=src, line=srcline) return context, None, [] def bof(self, context): """Called at beginning of file.""" return [], [] def nested_parse(self, block, input_offset, node, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. """ use_default = 0 if state_machine_class is None: state_machine_class = self.nested_sm use_default += 1 if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs use_default += 1 block_length = len(block) state_machine = None if use_default == 2: try: state_machine = self.nested_sm_cache.pop() except IndexError: pass if not state_machine: state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) if use_default == 2: self.nested_sm_cache.append(state_machine) else: state_machine.unlink() new_offset = state_machine.abs_line_offset() # No `block.parent` implies disconnected -- lines aren't in sync: if block.parent and (len(block) - block_length) != 0: # Adjustment for block if modified in nested parse: self.state_machine.next_line(len(block) - block_length) return new_offset def nested_list_parse(self, block, input_offset, node, initial_state, blank_finish, blank_finish_state=None, extra_settings={}, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. Also keep track of optional intermediate blank lines and the required final one. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs.copy() state_machine_kwargs['initial_state'] = initial_state state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) if blank_finish_state is None: blank_finish_state = initial_state state_machine.states[blank_finish_state].blank_finish = blank_finish for key, value in extra_settings.items(): setattr(state_machine.states[initial_state], key, value) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) blank_finish = state_machine.states[blank_finish_state].blank_finish state_machine.unlink() return state_machine.abs_line_offset(), blank_finish def section(self, title, source, style, lineno, messages): """Check for a valid subsection and create one if it checks out.""" if self.check_subsection(source, style, lineno): self.new_subsection(title, lineno, messages) def check_subsection(self, source, style, lineno): """ Check for a valid subsection header. Return 1 (true) or None (false). When a new section is reached that isn't a subsection of the current section, back up the line count (use ``previous_line(-x)``), then ``raise EOFError``. The current StateMachine will finish, then the calling StateMachine can re-examine the title. This will work its way back up the calling chain until the correct section level isreached. @@@ Alternative: Evaluate the title, store the title info & level, and back up the chain until that level is reached. Store in memo? Or return in results? :Exception: `EOFError` when a sibling or supersection encountered. """ memo = self.memo title_styles = memo.title_styles mylevel = memo.section_level try: # check for existing title style level = title_styles.index(style) + 1 except ValueError: # new title style if len(title_styles) == memo.section_level: # new subsection title_styles.append(style) return 1 else: # not at lowest level self.parent += self.title_inconsistent(source, lineno) return None if level <= mylevel: # sibling or supersection memo.section_level = level # bubble up to parent section if len(style) == 2: memo.section_bubble_up_kludge = 1 # back up 2 lines for underline title, 3 for overline title self.state_machine.previous_line(len(style) + 1) raise EOFError # let parent section re-evaluate if level == mylevel + 1: # immediate subsection return 1 else: # invalid subsection self.parent += self.title_inconsistent(source, lineno) return None def title_inconsistent(self, sourcetext, lineno): src, srcline = self.state_machine.get_source_and_line(lineno) error = self.reporter.severe( 'Title level inconsistent:', nodes.literal_block('', sourcetext), source=src, line=srcline) return error def new_subsection(self, title, lineno, messages): """Append new subsection to document tree. On return, check level.""" memo = self.memo mylevel = memo.section_level memo.section_level += 1 section_node = nodes.section() self.parent += section_node textnodes, title_messages = self.inline_text(title, lineno) titlenode = nodes.title(title, '', *textnodes) name = normalize_name(titlenode.astext()) section_node['names'].append(name) section_node += titlenode section_node += messages section_node += title_messages self.document.note_implicit_target(section_node, section_node) offset = self.state_machine.line_offset + 1 absoffset = self.state_machine.abs_line_offset() + 1 newabsoffset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=absoffset, node=section_node, match_titles=1) self.goto_line(newabsoffset) if memo.section_level <= mylevel: # can't handle next section? raise EOFError # bubble up to supersection # reset section_level; next pass will detect it properly memo.section_level = mylevel def paragraph(self, lines, lineno): """ Return a list (paragraph & messages) & a boolean: literal_block next? """ data = '\n'.join(lines).rstrip() if re.search(r'(?<!\\)(\\\\)*::$', data): if len(data) == 2: return [], 1 elif data[-3] in ' \n': text = data[:-3].rstrip() else: text = data[:-1] literalnext = 1 else: text = data literalnext = 0 textnodes, messages = self.inline_text(text, lineno) p = nodes.paragraph(data, '', *textnodes) p.source, p.line = self.state_machine.get_source_and_line(lineno) return [p] + messages, literalnext def inline_text(self, text, lineno): """ Return 2 lists: nodes (text and inline elements), and system_messages. """ return self.inliner.parse(text, lineno, self.memo, self.parent) def unindent_warning(self, node_name): # the actual problem is one line below the current line src, srcline = self.state_machine.get_source_and_line() return self.reporter.warning('%s ends without a blank line; ' 'unexpected unindent.' % node_name, source=src, line=srcline+1) def build_regexp(definition, compile=1): """ Build, compile and return a regular expression based on `definition`. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts), where "parts" is a list of regular expressions and/or regular expression definitions to be joined into an or-group. """ name, prefix, suffix, parts = definition part_strings = [] for part in parts: if type(part) is tuple: part_strings.append(build_regexp(part, None)) else: part_strings.append(part) or_group = '|'.join(part_strings) regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals() if compile: return re.compile(regexp, re.UNICODE) else: return regexp class Inliner: """ Parse inline markup; call the `parse()` method. """ def __init__(self): self.implicit_dispatch = [(self.patterns.uri, self.standalone_uri),] """List of (pattern, bound method) tuples, used by `self.implicit_inline`.""" def init_customizations(self, settings): """Setting-based customizations; run when parsing begins.""" if settings.pep_references: self.implicit_dispatch.append((self.patterns.pep, self.pep_reference)) if settings.rfc_references: self.implicit_dispatch.append((self.patterns.rfc, self.rfc_reference)) def parse(self, text, lineno, memo, parent): # Needs to be refactored for nested inline markup. # Add nested_parse() method? """ Return 2 lists: nodes (text and inline elements), and system_messages. Using `self.patterns.initial`, a pattern which matches start-strings (emphasis, strong, interpreted, phrase reference, literal, substitution reference, and inline target) and complete constructs (simple reference, footnote reference), search for a candidate. When one is found, check for validity (e.g., not a quoted '*' character). If valid, search for the corresponding end string if applicable, and check it for validity. If not found or invalid, generate a warning and ignore the start-string. Implicit inline markup (e.g. standalone URIs) is found last. """ self.reporter = memo.reporter self.document = memo.document self.language = memo.language self.parent = parent pattern_search = self.patterns.initial.search dispatch = self.dispatch remaining = escape2null(text) processed = [] unprocessed = [] messages = [] while remaining: match = pattern_search(remaining) if match: groups = match.groupdict() method = dispatch[groups['start'] or groups['backquote'] or groups['refend'] or groups['fnend']] before, inlines, remaining, sysmessages = method(self, match, lineno) unprocessed.append(before) messages += sysmessages if inlines: processed += self.implicit_inline(''.join(unprocessed), lineno) processed += inlines unprocessed = [] else: break remaining = ''.join(unprocessed) + remaining if remaining: processed += self.implicit_inline(remaining, lineno) return processed, messages openers = u'\'"([{<\u2018\u201c\xab\u00a1\u00bf' # see quoted_start below closers = u'\'")]}>\u2019\u201d\xbb!?' unicode_delimiters = u'\u2010\u2011\u2012\u2013\u2014\u00a0' start_string_prefix = (u'((?<=^)|(?<=[-/: \\n\u2019%s%s]))' % (re.escape(unicode_delimiters), re.escape(openers))) end_string_suffix = (r'((?=$)|(?=[-/:.,; \n\x00%s%s]))' % (re.escape(unicode_delimiters), re.escape(closers))) non_whitespace_before = r'(?<![ \n])' non_whitespace_escape_before = r'(?<![ \n\x00])' non_whitespace_after = r'(?![ \n])' # Alphanumerics with isolated internal [-._+:] chars (i.e. not 2 together): simplename = r'(?:(?!_)\w)+(?:[-._+:](?:(?!_)\w)+)*' # Valid URI characters (see RFC 2396 & RFC 2732); # final \x00 allows backslash escapes in URIs: uric = r"""[-_.!~*'()[\];/:@&=+$,%a-zA-Z0-9\x00]""" # Delimiter indicating the end of a URI (not part of the URI): uri_end_delim = r"""[>]""" # Last URI character; same as uric but no punctuation: urilast = r"""[_~*/=+a-zA-Z0-9]""" # End of a URI (either 'urilast' or 'uric followed by a # uri_end_delim'): uri_end = r"""(?:%(urilast)s|%(uric)s(?=%(uri_end_delim)s))""" % locals() emailc = r"""[-_!~*'{|}/#?^`&=+$%a-zA-Z0-9\x00]""" email_pattern = r""" %(emailc)s+(?:\.%(emailc)s+)* # name (?<!\x00)@ # at %(emailc)s+(?:\.%(emailc)s*)* # host %(uri_end)s # final URI char """ parts = ('initial_inline', start_string_prefix, '', [('start', '', non_whitespace_after, # simple start-strings [r'\*\*', # strong r'\*(?!\*)', # emphasis but not strong r'``', # literal r'_`', # inline internal target r'\|(?!\|)'] # substitution reference ), ('whole', '', end_string_suffix, # whole constructs [# reference name & end-string r'(?P<refname>%s)(?P<refend>__?)' % simplename, ('footnotelabel', r'\[', r'(?P<fnend>\]_)', [r'[0-9]+', # manually numbered r'\#(%s)?' % simplename, # auto-numbered (w/ label?) r'\*', # auto-symbol r'(?P<citationlabel>%s)' % simplename] # citation reference ) ] ), ('backquote', # interpreted text or phrase reference '(?P<role>(:%s:)?)' % simplename, # optional role non_whitespace_after, ['`(?!`)'] # but not literal ) ] ) patterns = Struct( initial=build_regexp(parts), emphasis=re.compile(non_whitespace_escape_before + r'(\*)' + end_string_suffix), strong=re.compile(non_whitespace_escape_before + r'(\*\*)' + end_string_suffix), interpreted_or_phrase_ref=re.compile( r""" %(non_whitespace_escape_before)s ( ` (?P<suffix> (?P<role>:%(simplename)s:)? (?P<refend>__?)? ) ) %(end_string_suffix)s """ % locals(), re.VERBOSE | re.UNICODE), embedded_uri=re.compile( r""" ( (?:[ \n]+|^) # spaces or beginning of line/string < # open bracket %(non_whitespace_after)s ([^<>\x00]+) # anything but angle brackets & nulls %(non_whitespace_before)s > # close bracket w/o whitespace before ) $ # end of string """ % locals(), re.VERBOSE), literal=re.compile(non_whitespace_before + '(``)' + end_string_suffix), target=re.compile(non_whitespace_escape_before + r'(`)' + end_string_suffix), substitution_ref=re.compile(non_whitespace_escape_before + r'(\|_{0,2})' + end_string_suffix), email=re.compile(email_pattern % locals() + '$', re.VERBOSE), uri=re.compile( (r""" %(start_string_prefix)s (?P<whole> (?P<absolute> # absolute URI (?P<scheme> # scheme (http, ftp, mailto) [a-zA-Z][a-zA-Z0-9.+-]* ) : ( ( # either: (//?)? # hierarchical URI %(uric)s* # URI characters %(uri_end)s # final URI char ) ( # optional query \?%(uric)s* %(uri_end)s )? ( # optional fragment \#%(uric)s* %(uri_end)s )? ) ) | # *OR* (?P<email> # email address """ + email_pattern + r""" ) ) %(end_string_suffix)s """) % locals(), re.VERBOSE), pep=re.compile( r""" %(start_string_prefix)s ( (pep-(?P<pepnum1>\d+)(.txt)?) # reference to source file | (PEP\s+(?P<pepnum2>\d+)) # reference by name ) %(end_string_suffix)s""" % locals(), re.VERBOSE), rfc=re.compile( r""" %(start_string_prefix)s (RFC(-|\s+)?(?P<rfcnum>\d+)) %(end_string_suffix)s""" % locals(), re.VERBOSE)) def quoted_start(self, match): """Return 1 if inline markup start-string is 'quoted', 0 if not.""" string = match.string start = match.start() end = match.end() if start == 0: # start-string at beginning of text return 0 prestart = string[start - 1] try: poststart = string[end] if self.openers.index(prestart) \ == self.closers.index(poststart): # quoted return 1 except IndexError: # start-string at end of text return 1 except ValueError: # not quoted pass return 0 def inline_obj(self, match, lineno, end_pattern, nodeclass, restore_backslashes=0): string = match.string matchstart = match.start('start') matchend = match.end('start') if self.quoted_start(match): return (string[:matchend], [], string[matchend:], [], '') endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars text = unescape(endmatch.string[:endmatch.start(1)], restore_backslashes) textend = matchend + endmatch.end(1) rawsource = unescape(string[matchstart:textend], 1) return (string[:matchstart], [nodeclass(rawsource, text)], string[textend:], [], endmatch.group(1)) msg = self.reporter.warning( 'Inline %s start-string without end-string.' % nodeclass.__name__, line=lineno) text = unescape(string[matchstart:matchend], 1) rawsource = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, rawsource, msg) return string[:matchstart], [prb], string[matchend:], [msg], '' def problematic(self, text, rawsource, message): msgid = self.document.set_id(message, self.parent) problematic = nodes.problematic(rawsource, text, refid=msgid) prbid = self.document.set_id(problematic) message.add_backref(prbid) return problematic def emphasis(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.emphasis, nodes.emphasis) return before, inlines, remaining, sysmessages def strong(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.strong, nodes.strong) return before, inlines, remaining, sysmessages def interpreted_or_phrase_ref(self, match, lineno): end_pattern = self.patterns.interpreted_or_phrase_ref string = match.string matchstart = match.start('backquote') matchend = match.end('backquote') rolestart = match.start('role') role = match.group('role') position = '' if role: role = role[1:-1] position = 'prefix' elif self.quoted_start(match): return (string[:matchend], [], string[matchend:], []) endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars textend = matchend + endmatch.end() if endmatch.group('role'): if role: msg = self.reporter.warning( 'Multiple roles in interpreted text (both ' 'prefix and suffix present; only one allowed).', line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] role = endmatch.group('suffix')[1:-1] position = 'suffix' escaped = endmatch.string[:endmatch.start(1)] rawsource = unescape(string[matchstart:textend], 1) if rawsource[-1:] == '_': if role: msg = self.reporter.warning( 'Mismatch: both interpreted text role %s and ' 'reference suffix.' % position, line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] return self.phrase_ref(string[:matchstart], string[textend:], rawsource, escaped, unescape(escaped)) else: rawsource = unescape(string[rolestart:textend], 1) nodelist, messages = self.interpreted(rawsource, escaped, role, lineno) return (string[:rolestart], nodelist, string[textend:], messages) msg = self.reporter.warning( 'Inline interpreted text or phrase reference start-string ' 'without end-string.', line=lineno) text = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, text, msg) return string[:matchstart], [prb], string[matchend:], [msg] def phrase_ref(self, before, after, rawsource, escaped, text): match = self.patterns.embedded_uri.search(escaped) if match: text = unescape(escaped[:match.start(0)]) uri_text = match.group(2) uri = ''.join(uri_text.split()) uri = self.adjust_uri(uri) if uri: target = nodes.target(match.group(1), refuri=uri) else: raise ApplicationError('problem with URI: %r' % uri_text) if not text: text = uri else: target = None refname = normalize_name(text) reference = nodes.reference(rawsource, text, name=whitespace_normalize_name(text)) node_list = [reference] if rawsource[-2:] == '__': if target: reference['refuri'] = uri else: reference['anonymous'] = 1 else: if target: reference['refuri'] = uri target['names'].append(refname) self.document.note_explicit_target(target, self.parent) node_list.append(target) else: reference['refname'] = refname self.document.note_refname(reference) return before, node_list, after, [] def adjust_uri(self, uri): match = self.patterns.email.match(uri) if match: return 'mailto:' + uri else: return uri def interpreted(self, rawsource, text, role, lineno): role_fn, messages = roles.role(role, self.language, lineno, self.reporter) if role_fn: nodes, messages2 = role_fn(role, rawsource, text, lineno, self) return nodes, messages + messages2 else: msg = self.reporter.error( 'Unknown interpreted text role "%s".' % role, line=lineno) return ([self.problematic(rawsource, rawsource, msg)], messages + [msg]) def literal(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.literal, nodes.literal, restore_backslashes=1) return before, inlines, remaining, sysmessages def inline_internal_target(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.target, nodes.target) if inlines and isinstance(inlines[0], nodes.target): assert len(inlines) == 1 target = inlines[0] name = normalize_name(target.astext()) target['names'].append(name) self.document.note_explicit_target(target, self.parent) return before, inlines, remaining, sysmessages def substitution_reference(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.substitution_ref, nodes.substitution_reference) if len(inlines) == 1: subref_node = inlines[0] if isinstance(subref_node, nodes.substitution_reference): subref_text = subref_node.astext() self.document.note_substitution_ref(subref_node, subref_text) if endstring[-1:] == '_': reference_node = nodes.reference( '|%s%s' % (subref_text, endstring), '') if endstring[-2:] == '__': reference_node['anonymous'] = 1 else: reference_node['refname'] = normalize_name(subref_text) self.document.note_refname(reference_node) reference_node += subref_node inlines = [reference_node] return before, inlines, remaining, sysmessages def footnote_reference(self, match, lineno): """ Handles `nodes.footnote_reference` and `nodes.citation_reference` elements. """ label = match.group('footnotelabel') refname = normalize_name(label) string = match.string before = string[:match.start('whole')] remaining = string[match.end('whole'):] if match.group('citationlabel'): refnode = nodes.citation_reference('[%s]_' % label, refname=refname) refnode += nodes.Text(label) self.document.note_citation_ref(refnode) else: refnode = nodes.footnote_reference('[%s]_' % label) if refname[0] == '#': refname = refname[1:] refnode['auto'] = 1 self.document.note_autofootnote_ref(refnode) elif refname == '*': refname = '' refnode['auto'] = '*' self.document.note_symbol_footnote_ref( refnode) else: refnode += nodes.Text(label) if refname: refnode['refname'] = refname self.document.note_footnote_ref(refnode) if utils.get_trim_footnote_ref_space(self.document.settings): before = before.rstrip() return (before, [refnode], remaining, []) def reference(self, match, lineno, anonymous=None): referencename = match.group('refname') refname = normalize_name(referencename) referencenode = nodes.reference( referencename + match.group('refend'), referencename, name=whitespace_normalize_name(referencename)) if anonymous: referencenode['anonymous'] = 1 else: referencenode['refname'] = refname self.document.note_refname(referencenode) string = match.string matchstart = match.start('whole') matchend = match.end('whole') return (string[:matchstart], [referencenode], string[matchend:], []) def anonymous_reference(self, match, lineno): return self.reference(match, lineno, anonymous=1) def standalone_uri(self, match, lineno): if (not match.group('scheme') or match.group('scheme').lower() in urischemes.schemes): if match.group('email'): addscheme = 'mailto:' else: addscheme = '' text = match.group('whole') unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=addscheme + unescaped)] else: # not a valid scheme raise MarkupMismatch def pep_reference(self, match, lineno): text = match.group(0) if text.startswith('pep-'): pepnum = int(match.group('pepnum1')) elif text.startswith('PEP'): pepnum = int(match.group('pepnum2')) else: raise MarkupMismatch ref = (self.document.settings.pep_base_url + self.document.settings.pep_file_url_template % pepnum) unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] rfc_url = 'rfc%d.html' def rfc_reference(self, match, lineno): text = match.group(0) if text.startswith('RFC'): rfcnum = int(match.group('rfcnum')) ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum else: raise MarkupMismatch unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] def implicit_inline(self, text, lineno): """ Check each of the patterns in `self.implicit_dispatch` for a match, and dispatch to the stored method for the pattern. Recursively check the text before and after the match. Return a list of `nodes.Text` and inline element nodes. """ if not text: return [] for pattern, method in self.implicit_dispatch: match = pattern.search(text) if match: try: # Must recurse on strings before *and* after the match; # there may be multiple patterns. return (self.implicit_inline(text[:match.start()], lineno) + method(match, lineno) + self.implicit_inline(text[match.end():], lineno)) except MarkupMismatch: pass return [nodes.Text(unescape(text), rawsource=unescape(text, 1))] dispatch = {'*': emphasis, '**': strong, '`': interpreted_or_phrase_ref, '``': literal, '_`': inline_internal_target, ']_': footnote_reference, '|': substitution_reference, '_': reference, '__': anonymous_reference} def _loweralpha_to_int(s, _zero=(ord('a')-1)): return ord(s) - _zero def _upperalpha_to_int(s, _zero=(ord('A')-1)): return ord(s) - _zero def _lowerroman_to_int(s): return roman.fromRoman(s.upper()) class Body(RSTState): """ Generic classifier of the first line of a block. """ double_width_pad_char = tableparser.TableParser.double_width_pad_char """Padding character for East Asian double-width text.""" enum = Struct() """Enumerated list parsing information.""" enum.formatinfo = { 'parens': Struct(prefix='(', suffix=')', start=1, end=-1), 'rparen': Struct(prefix='', suffix=')', start=0, end=-1), 'period': Struct(prefix='', suffix='.', start=0, end=-1)} enum.formats = enum.formatinfo.keys() enum.sequences = ['arabic', 'loweralpha', 'upperalpha', 'lowerroman', 'upperroman'] # ORDERED! enum.sequencepats = {'arabic': '[0-9]+', 'loweralpha': '[a-z]', 'upperalpha': '[A-Z]', 'lowerroman': '[ivxlcdm]+', 'upperroman': '[IVXLCDM]+',} enum.converters = {'arabic': int, 'loweralpha': _loweralpha_to_int, 'upperalpha': _upperalpha_to_int, 'lowerroman': _lowerroman_to_int, 'upperroman': roman.fromRoman} enum.sequenceregexps = {} for sequence in enum.sequences: enum.sequenceregexps[sequence] = re.compile( enum.sequencepats[sequence] + '$') grid_table_top_pat = re.compile(r'\+-[-+]+-\+ *$') """Matches the top (& bottom) of a full table).""" simple_table_top_pat = re.compile('=+( +=+)+ *$') """Matches the top of a simple table.""" simple_table_border_pat = re.compile('=+[ =]*$') """Matches the bottom & header bottom of a simple table.""" pats = {} """Fragments of patterns used by transitions.""" pats['nonalphanum7bit'] = '[!-/:-@[-`{-~]' pats['alpha'] = '[a-zA-Z]' pats['alphanum'] = '[a-zA-Z0-9]' pats['alphanumplus'] = '[a-zA-Z0-9_-]' pats['enum'] = ('(%(arabic)s|%(loweralpha)s|%(upperalpha)s|%(lowerroman)s' '|%(upperroman)s|#)' % enum.sequencepats) pats['optname'] = '%(alphanum)s%(alphanumplus)s*' % pats # @@@ Loosen up the pattern? Allow Unicode? pats['optarg'] = '(%(alpha)s%(alphanumplus)s*|<[^<>]+>)' % pats pats['shortopt'] = r'(-|\+)%(alphanum)s( ?%(optarg)s)?' % pats pats['longopt'] = r'(--|/)%(optname)s([ =]%(optarg)s)?' % pats pats['option'] = r'(%(shortopt)s|%(longopt)s)' % pats for format in enum.formats: pats[format] = '(?P<%s>%s%s%s)' % ( format, re.escape(enum.formatinfo[format].prefix), pats['enum'], re.escape(enum.formatinfo[format].suffix)) patterns = { 'bullet': u'[-+*\u2022\u2023\u2043]( +|$)', 'enumerator': r'(%(parens)s|%(rparen)s|%(period)s)( +|$)' % pats, 'field_marker': r':(?![: ])([^:\\]|\\.)*(?<! ):( +|$)', 'option_marker': r'%(option)s(, %(option)s)*( +| ?$)' % pats, 'doctest': r'>>>( +|$)', 'line_block': r'\|( +|$)', 'grid_table_top': grid_table_top_pat, 'simple_table_top': simple_table_top_pat, 'explicit_markup': r'\.\.( +|$)', 'anonymous': r'__( +|$)', 'line': r'(%(nonalphanum7bit)s)\1* *$' % pats, 'text': r''} initial_transitions = ( 'bullet', 'enumerator', 'field_marker', 'option_marker', 'doctest', 'line_block', 'grid_table_top', 'simple_table_top', 'explicit_markup', 'anonymous', 'line', 'text') def indent(self, match, context, next_state): """Block quote.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() elements = self.block_quote(indented, line_offset) self.parent += elements if not blank_finish: self.parent += self.unindent_warning('Block quote') return context, next_state, [] def block_quote(self, indented, line_offset): elements = [] while indented: (blockquote_lines, attribution_lines, attribution_offset, indented, new_line_offset) = self.split_attribution(indented, line_offset) blockquote = nodes.block_quote() self.nested_parse(blockquote_lines, line_offset, blockquote) elements.append(blockquote) if attribution_lines: attribution, messages = self.parse_attribution( attribution_lines, attribution_offset) blockquote += attribution elements += messages line_offset = new_line_offset while indented and not indented[0]: indented = indented[1:] line_offset += 1 return elements # U+2014 is an em-dash: attribution_pattern = re.compile(u'(---?(?!-)|\u2014) *(?=[^ \\n])') def split_attribution(self, indented, line_offset): """ Check for a block quote attribution and split it off: * First line after a blank line must begin with a dash ("--", "---", em-dash; matches `self.attribution_pattern`). * Every line after that must have consistent indentation. * Attributions must be preceded by block quote content. Return a tuple of: (block quote content lines, content offset, attribution lines, attribution offset, remaining indented lines). """ blank = None nonblank_seen = False for i in range(len(indented)): line = indented[i].rstrip() if line: if nonblank_seen and blank == i - 1: # last line blank match = self.attribution_pattern.match(line) if match: attribution_end, indent = self.check_attribution( indented, i) if attribution_end: a_lines = indented[i:attribution_end] a_lines.trim_left(match.end(), end=1) a_lines.trim_left(indent, start=1) return (indented[:i], a_lines, i, indented[attribution_end:], line_offset + attribution_end) nonblank_seen = True else: blank = i else: return (indented, None, None, None, None) def check_attribution(self, indented, attribution_start): """ Check attribution shape. Return the index past the end of the attribution, and the indent. """ indent = None i = attribution_start + 1 for i in range(attribution_start + 1, len(indented)): line = indented[i].rstrip() if not line: break if indent is None: indent = len(line) - len(line.lstrip()) elif len(line) - len(line.lstrip()) != indent: return None, None # bad shape; not an attribution else: # return index of line after last attribution line: i += 1 return i, (indent or 0) def parse_attribution(self, indented, line_offset): text = '\n'.join(indented).rstrip() lineno = self.state_machine.abs_line_number() + line_offset textnodes, messages = self.inline_text(text, lineno) node = nodes.attribution(text, '', *textnodes) node.line = lineno # report with source and source-line results in # ``IndexError: list index out of range`` # node.source, node.line = self.state_machine.get_source_and_line(lineno) return node, messages def bullet(self, match, context, next_state): """Bullet list item.""" bulletlist = nodes.bullet_list() self.parent += bulletlist bulletlist['bullet'] = match.string[0] i, blank_finish = self.list_item(match.end()) bulletlist += i offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=bulletlist, initial_state='BulletList', blank_finish=blank_finish) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.unindent_warning('Bullet list') return [], next_state, [] def list_item(self, indent): if self.state_machine.line[indent:]: indented, line_offset, blank_finish = ( self.state_machine.get_known_indented(indent)) else: indented, indent, line_offset, blank_finish = ( self.state_machine.get_first_known_indented(indent)) listitem = nodes.list_item('\n'.join(indented)) if indented: self.nested_parse(indented, input_offset=line_offset, node=listitem) return listitem, blank_finish def enumerator(self, match, context, next_state): """Enumerated List Item""" format, sequence, text, ordinal = self.parse_enumerator(match) if not self.is_enumerated_list_item(ordinal, sequence, format): raise statemachine.TransitionCorrection('text') enumlist = nodes.enumerated_list() self.parent += enumlist if sequence == '#': enumlist['enumtype'] = 'arabic' else: enumlist['enumtype'] = sequence enumlist['prefix'] = self.enum.formatinfo[format].prefix enumlist['suffix'] = self.enum.formatinfo[format].suffix if ordinal != 1: enumlist['start'] = ordinal src, srcline = self.state_machine.get_source_and_line() msg = self.reporter.info( 'Enumerated list start value not ordinal-1: "%s" (ordinal %s)' % (text, ordinal), source=src, line=srcline) self.parent += msg listitem, blank_finish = self.list_item(match.end()) enumlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=enumlist, initial_state='EnumeratedList', blank_finish=blank_finish, extra_settings={'lastordinal': ordinal, 'format': format, 'auto': sequence == '#'}) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Enumerated list') return [], next_state, [] def parse_enumerator(self, match, expected_sequence=None): """ Analyze an enumerator and return the results. :Return: - the enumerator format ('period', 'parens', or 'rparen'), - the sequence used ('arabic', 'loweralpha', 'upperroman', etc.), - the text of the enumerator, stripped of formatting, and - the ordinal value of the enumerator ('a' -> 1, 'ii' -> 2, etc.; ``None`` is returned for invalid enumerator text). The enumerator format has already been determined by the regular expression match. If `expected_sequence` is given, that sequence is tried first. If not, we check for Roman numeral 1. This way, single-character Roman numerals (which are also alphabetical) can be matched. If no sequence has been matched, all sequences are checked in order. """ groupdict = match.groupdict() sequence = '' for format in self.enum.formats: if groupdict[format]: # was this the format matched? break # yes; keep `format` else: # shouldn't happen raise ParserError('enumerator format not matched') text = groupdict[format][self.enum.formatinfo[format].start :self.enum.formatinfo[format].end] if text == '#': sequence = '#' elif expected_sequence: try: if self.enum.sequenceregexps[expected_sequence].match(text): sequence = expected_sequence except KeyError: # shouldn't happen raise ParserError('unknown enumerator sequence: %s' % sequence) elif text == 'i': sequence = 'lowerroman' elif text == 'I': sequence = 'upperroman' if not sequence: for sequence in self.enum.sequences: if self.enum.sequenceregexps[sequence].match(text): break else: # shouldn't happen raise ParserError('enumerator sequence not matched') if sequence == '#': ordinal = 1 else: try: ordinal = self.enum.converters[sequence](text) except roman.InvalidRomanNumeralError: ordinal = None return format, sequence, text, ordinal def is_enumerated_list_item(self, ordinal, sequence, format): """ Check validity based on the ordinal value and the second line. Return true if the ordinal is valid and the second line is blank, indented, or starts with the next enumerator or an auto-enumerator. """ if ordinal is None: return None try: next_line = self.state_machine.next_line() except EOFError: # end of input lines self.state_machine.previous_line() return 1 else: self.state_machine.previous_line() if not next_line[:1].strip(): # blank or indented return 1 result = self.make_enumerator(ordinal + 1, sequence, format) if result: next_enumerator, auto_enumerator = result try: if ( next_line.startswith(next_enumerator) or next_line.startswith(auto_enumerator) ): return 1 except TypeError: pass return None def make_enumerator(self, ordinal, sequence, format): """ Construct and return the next enumerated list item marker, and an auto-enumerator ("#" instead of the regular enumerator). Return ``None`` for invalid (out of range) ordinals. """ #" if sequence == '#': enumerator = '#' elif sequence == 'arabic': enumerator = str(ordinal) else: if sequence.endswith('alpha'): if ordinal > 26: return None enumerator = chr(ordinal + ord('a') - 1) elif sequence.endswith('roman'): try: enumerator = roman.toRoman(ordinal) except roman.RomanError: return None else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) if sequence.startswith('lower'): enumerator = enumerator.lower() elif sequence.startswith('upper'): enumerator = enumerator.upper() else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) formatinfo = self.enum.formatinfo[format] next_enumerator = (formatinfo.prefix + enumerator + formatinfo.suffix + ' ') auto_enumerator = formatinfo.prefix + '#' + formatinfo.suffix + ' ' return next_enumerator, auto_enumerator def field_marker(self, match, context, next_state): """Field list item.""" field_list = nodes.field_list() self.parent += field_list field, blank_finish = self.field(match) field_list += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=field_list, initial_state='FieldList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Field list') return [], next_state, [] def field(self, match): name = self.parse_field_marker(match) src, srcline = self.state_machine.get_source_and_line() lineno = self.state_machine.abs_line_number() indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) field_node = nodes.field() field_node.source = src field_node.line = srcline name_nodes, name_messages = self.inline_text(name, lineno) field_node += nodes.field_name(name, '', *name_nodes) field_body = nodes.field_body('\n'.join(indented), *name_messages) field_node += field_body if indented: self.parse_field_body(indented, line_offset, field_body) return field_node, blank_finish def parse_field_marker(self, match): """Extract & return field name from a field marker match.""" field = match.group()[1:] # strip off leading ':' field = field[:field.rfind(':')] # strip off trailing ':' etc. return field def parse_field_body(self, indented, offset, node): self.nested_parse(indented, input_offset=offset, node=node) def option_marker(self, match, context, next_state): """Option list item.""" optionlist = nodes.option_list() try: listitem, blank_finish = self.option_list_item(match) except MarkupError, error: # This shouldn't happen; pattern won't match. src, srcline = self.state_machine.get_source_and_line() msg = self.reporter.error('Invalid option list marker: %s' % str(error), source=src, line=srcline) self.parent += msg indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) elements = self.block_quote(indented, line_offset) self.parent += elements if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] self.parent += optionlist optionlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=optionlist, initial_state='OptionList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] def option_list_item(self, match): offset = self.state_machine.abs_line_offset() options = self.parse_option_marker(match) indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) if not indented: # not an option list item self.goto_line(offset) raise statemachine.TransitionCorrection('text') option_group = nodes.option_group('', *options) description = nodes.description('\n'.join(indented)) option_list_item = nodes.option_list_item('', option_group, description) if indented: self.nested_parse(indented, input_offset=line_offset, node=description) return option_list_item, blank_finish def parse_option_marker(self, match): """ Return a list of `node.option` and `node.option_argument` objects, parsed from an option marker match. :Exception: `MarkupError` for invalid option markers. """ optlist = [] optionstrings = match.group().rstrip().split(', ') for optionstring in optionstrings: tokens = optionstring.split() delimiter = ' ' firstopt = tokens[0].split('=') if len(firstopt) > 1: # "--opt=value" form tokens[:1] = firstopt delimiter = '=' elif (len(tokens[0]) > 2 and ((tokens[0].startswith('-') and not tokens[0].startswith('--')) or tokens[0].startswith('+'))): # "-ovalue" form tokens[:1] = [tokens[0][:2], tokens[0][2:]] delimiter = '' if len(tokens) > 1 and (tokens[1].startswith('<') and tokens[-1].endswith('>')): # "-o <value1 value2>" form; join all values into one token tokens[1:] = [' '.join(tokens[1:])] if 0 < len(tokens) <= 2: option = nodes.option(optionstring) option += nodes.option_string(tokens[0], tokens[0]) if len(tokens) > 1: option += nodes.option_argument(tokens[1], tokens[1], delimiter=delimiter) optlist.append(option) else: raise MarkupError( 'wrong number of option tokens (=%s), should be 1 or 2: ' '"%s"' % (len(tokens), optionstring)) return optlist def doctest(self, match, context, next_state): data = '\n'.join(self.state_machine.get_text_block()) self.parent += nodes.doctest_block(data, data) return [], next_state, [] def line_block(self, match, context, next_state): """First line of a line block.""" block = nodes.line_block() self.parent += block lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) block += line self.parent += messages if not blank_finish: offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=block, initial_state='LineBlock', blank_finish=0) self.goto_line(new_line_offset) if not blank_finish: src, srcline = self.state_machine.get_source_and_line() self.parent += self.reporter.warning( 'Line block ends without a blank line.', source=src, line=srcline+1) if len(block): if block[0].indent is None: block[0].indent = 0 self.nest_line_block_lines(block) return [], next_state, [] def line_block_line(self, match, lineno): """Return one line element of a line_block.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) text = u'\n'.join(indented) text_nodes, messages = self.inline_text(text, lineno) line = nodes.line(text, '', *text_nodes) if match.string.rstrip() != '|': # not empty line.indent = len(match.group(1)) - 1 return line, messages, blank_finish def nest_line_block_lines(self, block): for index in range(1, len(block)): if block[index].indent is None: block[index].indent = block[index - 1].indent self.nest_line_block_segment(block) def nest_line_block_segment(self, block): indents = [item.indent for item in block] least = min(indents) new_items = [] new_block = nodes.line_block() for item in block: if item.indent > least: new_block.append(item) else: if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) new_block = nodes.line_block() new_items.append(item) if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) block[:] = new_items def grid_table_top(self, match, context, next_state): """Top border of a full table.""" return self.table_top(match, context, next_state, self.isolate_grid_table, tableparser.GridTableParser) def simple_table_top(self, match, context, next_state): """Top border of a simple table.""" return self.table_top(match, context, next_state, self.isolate_simple_table, tableparser.SimpleTableParser) def table_top(self, match, context, next_state, isolate_function, parser_class): """Top border of a generic table.""" nodelist, blank_finish = self.table(isolate_function, parser_class) self.parent += nodelist if not blank_finish: src, srcline = self.state_machine.get_source_and_line() msg = self.reporter.warning( 'Blank line required after table.', source=src, line=srcline+1) self.parent += msg return [], next_state, [] def table(self, isolate_function, parser_class): """Parse a table.""" block, messages, blank_finish = isolate_function() if block: try: parser = parser_class() tabledata = parser.parse(block) tableline = (self.state_machine.abs_line_number() - len(block) + 1) table = self.build_table(tabledata, tableline) nodelist = [table] + messages except tableparser.TableMarkupError, detail: nodelist = self.malformed_table( block, ' '.join(detail.args)) + messages else: nodelist = messages return nodelist, blank_finish def isolate_grid_table(self): messages = [] blank_finish = 1 try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, src, srcline = instance.args messages.append(self.reporter.error('Unexpected indentation.', source=src, line=srcline)) blank_finish = 0 block.disconnect() # for East Asian chars: block.pad_double_width(self.double_width_pad_char) width = len(block[0].strip()) for i in range(len(block)): block[i] = block[i].strip() if block[i][0] not in '+|': # check left edge blank_finish = 0 self.state_machine.previous_line(len(block) - i) del block[i:] break if not self.grid_table_top_pat.match(block[-1]): # find bottom blank_finish = 0 # from second-last to third line of table: for i in range(len(block) - 2, 1, -1): if self.grid_table_top_pat.match(block[i]): self.state_machine.previous_line(len(block) - i + 1) del block[i+1:] break else: messages.extend(self.malformed_table(block)) return [], messages, blank_finish for i in range(len(block)): # check right edge if len(block[i]) != width or block[i][-1] not in '+|': messages.extend(self.malformed_table(block)) return [], messages, blank_finish return block, messages, blank_finish def isolate_simple_table(self): start = self.state_machine.line_offset lines = self.state_machine.input_lines limit = len(lines) - 1 toplen = len(lines[start].strip()) pattern_match = self.simple_table_border_pat.match found = 0 found_at = None i = start + 1 while i <= limit: line = lines[i] match = pattern_match(line) if match: if len(line.strip()) != toplen: self.state_machine.next_line(i - start) messages = self.malformed_table( lines[start:i+1], 'Bottom/header table border does ' 'not match top border.') return [], messages, i == limit or not lines[i+1].strip() found += 1 found_at = i if found == 2 or i == limit or not lines[i+1].strip(): end = i break i += 1 else: # reached end of input_lines if found: extra = ' or no blank line after table bottom' self.state_machine.next_line(found_at - start) block = lines[start:found_at+1] else: extra = '' self.state_machine.next_line(i - start - 1) block = lines[start:] messages = self.malformed_table( block, 'No bottom table border found%s.' % extra) return [], messages, not extra self.state_machine.next_line(end - start) block = lines[start:end+1] # for East Asian chars: block.pad_double_width(self.double_width_pad_char) return block, [], end == limit or not lines[end+1].strip() def malformed_table(self, block, detail=''): block.replace(self.double_width_pad_char, '') data = '\n'.join(block) message = 'Malformed table.' startline = self.state_machine.abs_line_number() - len(block) + 1 src, srcline = self.state_machine.get_source_and_line(startline) if detail: message += '\n' + detail error = self.reporter.error(message, nodes.literal_block(data, data), source=src, line=srcline) return [error] def build_table(self, tabledata, tableline, stub_columns=0): colwidths, headrows, bodyrows = tabledata table = nodes.table() tgroup = nodes.tgroup(cols=len(colwidths)) table += tgroup for colwidth in colwidths: colspec = nodes.colspec(colwidth=colwidth) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec if headrows: thead = nodes.thead() tgroup += thead for row in headrows: thead += self.build_table_row(row, tableline) tbody = nodes.tbody() tgroup += tbody for row in bodyrows: tbody += self.build_table_row(row, tableline) return table def build_table_row(self, rowdata, tableline): row = nodes.row() for cell in rowdata: if cell is None: continue morerows, morecols, offset, cellblock = cell attributes = {} if morerows: attributes['morerows'] = morerows if morecols: attributes['morecols'] = morecols entry = nodes.entry(**attributes) row += entry if ''.join(cellblock): self.nested_parse(cellblock, input_offset=tableline+offset, node=entry) return row explicit = Struct() """Patterns and constants used for explicit markup recognition.""" explicit.patterns = Struct( target=re.compile(r""" ( _ # anonymous target | # *OR* (?!_) # no underscore at the beginning (?P<quote>`?) # optional open quote (?![ `]) # first char. not space or # backquote (?P<name> # reference name .+? ) %(non_whitespace_escape_before)s (?P=quote) # close quote if open quote used ) (?<!(?<!\x00):) # no unescaped colon at end %(non_whitespace_escape_before)s [ ]? # optional space : # end of reference name ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE), reference=re.compile(r""" ( (?P<simple>%(simplename)s)_ | # *OR* ` # open backquote (?![ ]) # not space (?P<phrase>.+?) # hyperlink phrase %(non_whitespace_escape_before)s `_ # close backquote, # reference mark ) $ # end of string """ % vars(Inliner), re.VERBOSE | re.UNICODE), substitution=re.compile(r""" ( (?![ ]) # first char. not space (?P<name>.+?) # substitution text %(non_whitespace_escape_before)s \| # close delimiter ) ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE),) def footnote(self, match): src, srcline = self.state_machine.get_source_and_line() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) footnote = nodes.footnote('\n'.join(indented)) footnote.source = src footnote.line = srcline if name[0] == '#': # auto-numbered name = name[1:] # autonumber label footnote['auto'] = 1 if name: footnote['names'].append(name) self.document.note_autofootnote(footnote) elif name == '*': # auto-symbol name = '' footnote['auto'] = '*' self.document.note_symbol_footnote(footnote) else: # manually numbered footnote += nodes.label('', label) footnote['names'].append(name) self.document.note_footnote(footnote) if name: self.document.note_explicit_target(footnote, footnote) else: self.document.set_id(footnote, footnote) if indented: self.nested_parse(indented, input_offset=offset, node=footnote) return [footnote], blank_finish def citation(self, match): src, srcline = self.state_machine.get_source_and_line() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) citation = nodes.citation('\n'.join(indented)) citation.source = src citation.line = srcline citation += nodes.label('', label) citation['names'].append(name) self.document.note_citation(citation) self.document.note_explicit_target(citation, citation) if indented: self.nested_parse(indented, input_offset=offset, node=citation) return [citation], blank_finish def hyperlink_target(self, match): pattern = self.explicit.patterns.target lineno = self.state_machine.abs_line_number() src, srcline = self.state_machine.get_source_and_line() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented( match.end(), until_blank=1, strip_indent=0) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] escaped = block[0] blockindex = 0 while 1: targetmatch = pattern.match(escaped) if targetmatch: break blockindex += 1 try: escaped += block[blockindex] except IndexError: raise MarkupError('malformed hyperlink target.') del block[:blockindex] block[0] = (block[0] + ' ')[targetmatch.end()-len(escaped)-1:].strip() target = self.make_target(block, blocktext, lineno, targetmatch.group('name')) return [target], blank_finish def make_target(self, block, block_text, lineno, target_name): target_type, data = self.parse_target(block, block_text, lineno) if target_type == 'refname': target = nodes.target(block_text, '', refname=normalize_name(data)) target.indirect_reference_name = data self.add_target(target_name, '', target, lineno) self.document.note_indirect_target(target) return target elif target_type == 'refuri': target = nodes.target(block_text, '') self.add_target(target_name, data, target, lineno) return target else: return data def parse_target(self, block, block_text, lineno): """ Determine the type of reference of a target. :Return: A 2-tuple, one of: - 'refname' and the indirect reference name - 'refuri' and the URI - 'malformed' and a system_message node """ if block and block[-1].strip()[-1:] == '_': # possible indirect target reference = ' '.join([line.strip() for line in block]) refname = self.is_reference(reference) if refname: return 'refname', refname reference = ''.join([''.join(line.split()) for line in block]) return 'refuri', unescape(reference) def is_reference(self, reference): match = self.explicit.patterns.reference.match( whitespace_normalize_name(reference)) if not match: return None return unescape(match.group('simple') or match.group('phrase')) def add_target(self, targetname, refuri, target, lineno): target.line = lineno if targetname: name = normalize_name(unescape(targetname)) target['names'].append(name) if refuri: uri = self.inliner.adjust_uri(refuri) if uri: target['refuri'] = uri else: raise ApplicationError('problem with URI: %r' % refuri) self.document.note_explicit_target(target, self.parent) else: # anonymous target if refuri: target['refuri'] = refuri target['anonymous'] = 1 self.document.note_anonymous_target(target) def substitution_def(self, match): pattern = self.explicit.patterns.substitution src, srcline = self.state_machine.get_source_and_line() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), strip_indent=0) blocktext = (match.string[:match.end()] + '\n'.join(block)) block.disconnect() escaped = escape2null(block[0].rstrip()) blockindex = 0 while 1: subdefmatch = pattern.match(escaped) if subdefmatch: break blockindex += 1 try: escaped = escaped + ' ' + escape2null(block[blockindex].strip()) except IndexError: raise MarkupError('malformed substitution definition.') del block[:blockindex] # strip out the substitution marker block[0] = (block[0].strip() + ' ')[subdefmatch.end()-len(escaped)-1:-1] if not block[0]: del block[0] offset += 1 while block and not block[-1].strip(): block.pop() subname = subdefmatch.group('name') substitution_node = nodes.substitution_definition(blocktext) substitution_node.source = src substitution_node.line = srcline if not block: msg = self.reporter.warning( 'Substitution definition "%s" missing contents.' % subname, nodes.literal_block(blocktext, blocktext), source=src, line=srcline) return [msg], blank_finish block[0] = block[0].strip() substitution_node['names'].append( nodes.whitespace_normalize_name(subname)) new_abs_offset, blank_finish = self.nested_list_parse( block, input_offset=offset, node=substitution_node, initial_state='SubstitutionDef', blank_finish=blank_finish) i = 0 for node in substitution_node[:]: if not (isinstance(node, nodes.Inline) or isinstance(node, nodes.Text)): self.parent += substitution_node[i] del substitution_node[i] else: i += 1 for node in substitution_node.traverse(nodes.Element): if self.disallowed_inside_substitution_definitions(node): pformat = nodes.literal_block('', node.pformat().rstrip()) msg = self.reporter.error( 'Substitution definition contains illegal element:', pformat, nodes.literal_block(blocktext, blocktext), source=src, line=srcline) return [msg], blank_finish if len(substitution_node) == 0: msg = self.reporter.warning( 'Substitution definition "%s" empty or invalid.' % subname, nodes.literal_block(blocktext, blocktext), source=src, line=srcline) return [msg], blank_finish self.document.note_substitution_def( substitution_node, subname, self.parent) return [substitution_node], blank_finish def disallowed_inside_substitution_definitions(self, node): if (node['ids'] or isinstance(node, nodes.reference) and node.get('anonymous') or isinstance(node, nodes.footnote_reference) and node.get('auto')): return 1 else: return 0 def directive(self, match, **option_presets): """Returns a 2-tuple: list of nodes, and a "blank finish" boolean.""" type_name = match.group(1) directive_class, messages = directives.directive( type_name, self.memo.language, self.document) self.parent += messages if directive_class: return self.run_directive( directive_class, match, type_name, option_presets) else: return self.unknown_directive(type_name) def run_directive(self, directive, match, type_name, option_presets): """ Parse a directive then run its directive function. Parameters: - `directive`: The class implementing the directive. Must be a subclass of `rst.Directive`. - `match`: A regular expression match object which matched the first line of the directive. - `type_name`: The directive name, as used in the source text. - `option_presets`: A dictionary of preset options, defaults for the directive options. Currently, only an "alt" option is passed by substitution definitions (value: the substitution name), which may be used by an embedded image directive. Returns a 2-tuple: list of nodes, and a "blank finish" boolean. """ if isinstance(directive, (FunctionType, MethodType)): from docutils.parsers.rst import convert_directive_function directive = convert_directive_function(directive) lineno = self.state_machine.abs_line_number() src, srcline = self.state_machine.get_source_and_line() initial_line_offset = self.state_machine.line_offset indented, indent, line_offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), strip_top=0) block_text = '\n'.join(self.state_machine.input_lines[ initial_line_offset : self.state_machine.line_offset + 1]) try: arguments, options, content, content_offset = ( self.parse_directive_block(indented, line_offset, directive, option_presets)) except MarkupError, detail: error = self.reporter.error( 'Error in "%s" directive:\n%s.' % (type_name, ' '.join(detail.args)), nodes.literal_block(block_text, block_text), source=src, line=srcline) return [error], blank_finish directive_instance = directive( type_name, arguments, options, content, lineno, content_offset, block_text, self, self.state_machine) try: result = directive_instance.run() except docutils.parsers.rst.DirectiveError, error: msg_node = self.reporter.system_message(error.level, error.msg, source=src, line=srcline) msg_node += nodes.literal_block(block_text, block_text) result = [msg_node] assert isinstance(result, list), \ 'Directive "%s" must return a list of nodes.' % type_name for i in range(len(result)): assert isinstance(result[i], nodes.Node), \ ('Directive "%s" returned non-Node object (index %s): %r' % (type_name, i, result[i])) return (result, blank_finish or self.state_machine.is_next_line_blank()) def parse_directive_block(self, indented, line_offset, directive, option_presets): option_spec = directive.option_spec has_content = directive.has_content if indented and not indented[0].strip(): indented.trim_start() line_offset += 1 while indented and not indented[-1].strip(): indented.trim_end() if indented and (directive.required_arguments or directive.optional_arguments or option_spec): for i in range(len(indented)): if not indented[i].strip(): break else: i += 1 arg_block = indented[:i] content = indented[i+1:] content_offset = line_offset + i + 1 else: content = indented content_offset = line_offset arg_block = [] while content and not content[0].strip(): content.trim_start() content_offset += 1 if option_spec: options, arg_block = self.parse_directive_options( option_presets, option_spec, arg_block) if arg_block and not (directive.required_arguments or directive.optional_arguments): raise MarkupError('no arguments permitted; blank line ' 'required before content block') else: options = {} if directive.required_arguments or directive.optional_arguments: arguments = self.parse_directive_arguments( directive, arg_block) else: arguments = [] if content and not has_content: raise MarkupError('no content permitted') return (arguments, options, content, content_offset) def parse_directive_options(self, option_presets, option_spec, arg_block): options = option_presets.copy() for i in range(len(arg_block)): if arg_block[i][:1] == ':': opt_block = arg_block[i:] arg_block = arg_block[:i] break else: opt_block = [] if opt_block: success, data = self.parse_extension_options(option_spec, opt_block) if success: # data is a dict of options options.update(data) else: # data is an error string raise MarkupError(data) return options, arg_block def parse_directive_arguments(self, directive, arg_block): required = directive.required_arguments optional = directive.optional_arguments arg_text = '\n'.join(arg_block) arguments = arg_text.split() if len(arguments) < required: raise MarkupError('%s argument(s) required, %s supplied' % (required, len(arguments))) elif len(arguments) > required + optional: if directive.final_argument_whitespace: arguments = arg_text.split(None, required + optional - 1) else: raise MarkupError( 'maximum %s argument(s) allowed, %s supplied' % (required + optional, len(arguments))) return arguments def parse_extension_options(self, option_spec, datalines): """ Parse `datalines` for a field list containing extension options matching `option_spec`. :Parameters: - `option_spec`: a mapping of option name to conversion function, which should raise an exception on bad input. - `datalines`: a list of input strings. :Return: - Success value, 1 or 0. - An option dictionary on success, an error string on failure. """ node = nodes.field_list() newline_offset, blank_finish = self.nested_list_parse( datalines, 0, node, initial_state='ExtensionOptions', blank_finish=1) if newline_offset != len(datalines): # incomplete parse of block return 0, 'invalid option block' try: options = utils.extract_extension_options(node, option_spec) except KeyError, detail: return 0, ('unknown option: "%s"' % detail.args[0]) except (ValueError, TypeError), detail: return 0, ('invalid option value: %s' % ' '.join(detail.args)) except utils.ExtensionOptionError, detail: return 0, ('invalid option data: %s' % ' '.join(detail.args)) if blank_finish: return 1, options else: return 0, 'option data incompletely parsed' def unknown_directive(self, type_name): src, srcline = self.state_machine.get_source_and_line() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(0, strip_indent=0) text = '\n'.join(indented) error = self.reporter.error( 'Unknown directive type "%s".' % type_name, nodes.literal_block(text, text), source=src, line=srcline) return [error], blank_finish def comment(self, match): if not match.string[match.end():].strip() \ and self.state_machine.is_next_line_blank(): # an empty comment? return [nodes.comment()], 1 # "A tiny but practical wart." indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) while indented and not indented[-1].strip(): indented.trim_end() text = '\n'.join(indented) return [nodes.comment(text, text)], blank_finish explicit.constructs = [ (footnote, re.compile(r""" \.\.[ ]+ # explicit markup start \[ ( # footnote label: [0-9]+ # manually numbered footnote | # *OR* \# # anonymous auto-numbered footnote | # *OR* \#%s # auto-number ed?) footnote label | # *OR* \* # auto-symbol footnote ) \] ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (citation, re.compile(r""" \.\.[ ]+ # explicit markup start \[(%s)\] # citation label ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (hyperlink_target, re.compile(r""" \.\.[ ]+ # explicit markup start _ # target indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (substitution_def, re.compile(r""" \.\.[ ]+ # explicit markup start \| # substitution indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (directive, re.compile(r""" \.\.[ ]+ # explicit markup start (%s) # directive name [ ]? # optional space :: # directive delimiter ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE))] def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def explicit_construct(self, match): """Determine which explicit construct this is, parse & return it.""" errors = [] for method, pattern in self.explicit.constructs: expmatch = pattern.match(match.string) if expmatch: try: return method(self, expmatch) except MarkupError, error: # never reached? message = ' '.join(error.args) src, srcline = self.state_machine.get_source_and_line() errors.append(self.reporter.warning( message, source=src, line=srcline)) break nodelist, blank_finish = self.comment(match) return nodelist + errors, blank_finish def explicit_list(self, blank_finish): """ Create a nested state machine for a series of explicit markup constructs (including anonymous hyperlink targets). """ offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=self.parent, initial_state='Explicit', blank_finish=blank_finish, match_titles=self.state_machine.match_titles) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Explicit markup') def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def anonymous_target(self, match): lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), until_blank=1) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] target = self.make_target(block, blocktext, lineno, '') return [target], blank_finish def line(self, match, context, next_state): """Section title overline or transition marker.""" if self.state_machine.match_titles: return [match.string], 'Line', [] elif match.string.strip() == '::': raise statemachine.TransitionCorrection('text') elif len(match.string.strip()) < 4: msg = self.reporter.info( 'Unexpected possible title overline or transition.\n' "Treating it as ordinary text because it's so short.", line=self.state_machine.abs_line_number()) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = self.state_machine.line msg = self.reporter.severe( 'Unexpected section title or transition.', nodes.literal_block(blocktext, blocktext), line=self.state_machine.abs_line_number()) self.parent += msg return [], next_state, [] def text(self, match, context, next_state): """Titles, definition lists, paragraphs.""" return [match.string], 'Text', [] class RFC2822Body(Body): """ RFC2822 headers are only valid as the first constructs in documents. As soon as anything else appears, the `Body` state should take over. """ patterns = Body.patterns.copy() # can't modify the original patterns['rfc2822'] = r'[!-9;-~]+:( +|$)' initial_transitions = [(name, 'Body') for name in Body.initial_transitions] initial_transitions.insert(-1, ('rfc2822', 'Body')) # just before 'text' def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" fieldlist = nodes.field_list(classes=['rfc2822']) self.parent += fieldlist field, blank_finish = self.rfc2822_field(match) fieldlist += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=fieldlist, initial_state='RFC2822List', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning( 'RFC2822-style field list') return [], next_state, [] def rfc2822_field(self, match): name = match.string[:match.string.find(':')] indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) fieldnode = nodes.field() fieldnode += nodes.field_name(name, name) fieldbody = nodes.field_body('\n'.join(indented)) fieldnode += fieldbody if indented: self.nested_parse(indented, input_offset=line_offset, node=fieldbody) return fieldnode, blank_finish class SpecializedBody(Body): """ Superclass for second and subsequent compound element members. Compound elements are lists and list-like constructs. All transition methods are disabled (redefined as `invalid_input`). Override individual methods in subclasses to re-enable. For example, once an initial bullet list item, say, is recognized, the `BulletList` subclass takes over, with a "bullet_list" node as its container. Upon encountering the initial bullet list item, `Body.bullet` calls its ``self.nested_list_parse`` (`RSTState.nested_list_parse`), which starts up a nested parsing session with `BulletList` as the initial state. Only the ``bullet`` transition method is enabled in `BulletList`; as long as only bullet list items are encountered, they are parsed and inserted into the container. The first construct which is *not* a bullet list item triggers the `invalid_input` method, which ends the nested parse and closes the container. `BulletList` needs to recognize input that is invalid in the context of a bullet list, which means everything *other than* bullet list items, so it inherits the transition list created in `Body`. """ def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" self.state_machine.previous_line() # back up so parent SM can reassess raise EOFError indent = invalid_input bullet = invalid_input enumerator = invalid_input field_marker = invalid_input option_marker = invalid_input doctest = invalid_input line_block = invalid_input grid_table_top = invalid_input simple_table_top = invalid_input explicit_markup = invalid_input anonymous = invalid_input line = invalid_input text = invalid_input class BulletList(SpecializedBody): """Second and subsequent bullet_list list_items.""" def bullet(self, match, context, next_state): """Bullet list item.""" if match.string[0] != self.parent['bullet']: # different bullet: new list self.invalid_input() listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish return [], next_state, [] class DefinitionList(SpecializedBody): """Second and subsequent definition_list_items.""" def text(self, match, context, next_state): """Definition lists.""" return [match.string], 'Definition', [] class EnumeratedList(SpecializedBody): """Second and subsequent enumerated_list list_items.""" def enumerator(self, match, context, next_state): """Enumerated list item.""" format, sequence, text, ordinal = self.parse_enumerator( match, self.parent['enumtype']) if ( format != self.format or (sequence != '#' and (sequence != self.parent['enumtype'] or self.auto or ordinal != (self.lastordinal + 1))) or not self.is_enumerated_list_item(ordinal, sequence, format)): # different enumeration: new list self.invalid_input() if sequence == '#': self.auto = 1 listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish self.lastordinal = ordinal return [], next_state, [] class FieldList(SpecializedBody): """Second and subsequent field_list fields.""" def field_marker(self, match, context, next_state): """Field list field.""" field, blank_finish = self.field(match) self.parent += field self.blank_finish = blank_finish return [], next_state, [] class OptionList(SpecializedBody): """Second and subsequent option_list option_list_items.""" def option_marker(self, match, context, next_state): """Option list item.""" try: option_list_item, blank_finish = self.option_list_item(match) except MarkupError: self.invalid_input() self.parent += option_list_item self.blank_finish = blank_finish return [], next_state, [] class RFC2822List(SpecializedBody, RFC2822Body): """Second and subsequent RFC2822-style field_list fields.""" patterns = RFC2822Body.patterns initial_transitions = RFC2822Body.initial_transitions def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" field, blank_finish = self.rfc2822_field(match) self.parent += field self.blank_finish = blank_finish return [], 'RFC2822List', [] blank = SpecializedBody.invalid_input class ExtensionOptions(FieldList): """ Parse field_list fields for extension options. No nested parsing is done (including inline markup parsing). """ def parse_field_body(self, indented, offset, node): """Override `Body.parse_field_body` for simpler parsing.""" lines = [] for line in list(indented) + ['']: if line.strip(): lines.append(line) elif lines: text = '\n'.join(lines) node += nodes.paragraph(text, text) lines = [] class LineBlock(SpecializedBody): """Second and subsequent lines of a line_block.""" blank = SpecializedBody.invalid_input def line_block(self, match, context, next_state): """New line of line block.""" lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) self.parent += line self.parent.parent += messages self.blank_finish = blank_finish return [], next_state, [] class Explicit(SpecializedBody): """Second and subsequent explicit markup construct.""" def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] blank = SpecializedBody.invalid_input class SubstitutionDef(Body): """ Parser for the contents of a substitution_definition element. """ patterns = { 'embedded_directive': re.compile(r'(%s)::( +|$)' % Inliner.simplename, re.UNICODE), 'text': r''} initial_transitions = ['embedded_directive', 'text'] def embedded_directive(self, match, context, next_state): nodelist, blank_finish = self.directive(match, alt=self.parent['names'][0]) self.parent += nodelist if not self.state_machine.at_eof(): self.blank_finish = blank_finish raise EOFError def text(self, match, context, next_state): if not self.state_machine.at_eof(): self.blank_finish = self.state_machine.is_next_line_blank() raise EOFError class Text(RSTState): """ Classifier of second line of a text block. Could be a paragraph, a definition list item, or a title. """ patterns = {'underline': Body.patterns['line'], 'text': r''} initial_transitions = [('underline', 'Body'), ('text', 'Body')] def blank(self, match, context, next_state): """End of paragraph.""" paragraph, literalnext = self.paragraph( context, self.state_machine.abs_line_number() - 1) self.parent += paragraph if literalnext: self.parent += self.literal_block() return [], 'Body', [] def eof(self, context): if context: self.blank(None, context, None) return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlist = nodes.definition_list() definitionlistitem, blank_finish = self.definition_list_item(context) definitionlist += definitionlistitem self.parent += definitionlist offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=definitionlist, initial_state='DefinitionList', blank_finish=blank_finish, blank_finish_state='Definition') self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Definition list') return [], 'Body', [] def underline(self, match, context, next_state): """Section title.""" lineno = self.state_machine.abs_line_number() src, srcline = self.state_machine.get_source_and_line() title = context[0].rstrip() underline = match.string.rstrip() source = title + '\n' + underline messages = [] if column_width(title) > len(underline): if len(underline) < 4: if self.state_machine.match_titles: msg = self.reporter.info( 'Possible title underline, too short for the title.\n' "Treating it as ordinary text because it's so short.", source=src, line=srcline) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.warning( 'Title underline too short.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline) messages.append(msg) if not self.state_machine.match_titles: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.severe( 'Unexpected section title.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline) self.parent += messages self.parent += msg return [], next_state, [] style = underline[0] context[:] = [] self.section(title, source, style, lineno - 1, messages) return [], next_state, [] def text(self, match, context, next_state): """Paragraph.""" startline = self.state_machine.abs_line_number() - 1 msg = None try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, src, srcline = instance.args msg = self.reporter.error('Unexpected indentation.', source=src, line=srcline) lines = context + list(block) paragraph, literalnext = self.paragraph(lines, startline) self.parent += paragraph self.parent += msg if literalnext: try: self.state_machine.next_line() except EOFError: pass self.parent += self.literal_block() return [], next_state, [] def literal_block(self): """Return a list of nodes.""" indented, indent, offset, blank_finish = \ self.state_machine.get_indented() while indented and not indented[-1].strip(): indented.trim_end() if not indented: return self.quoted_literal_block() data = '\n'.join(indented) literal_block = nodes.literal_block(data, data) literal_block.line = offset + 1 nodelist = [literal_block] if not blank_finish: nodelist.append(self.unindent_warning('Literal block')) return nodelist def quoted_literal_block(self): abs_line_offset = self.state_machine.abs_line_offset() offset = self.state_machine.line_offset parent_node = nodes.Element() new_abs_offset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=abs_line_offset, node=parent_node, match_titles=0, state_machine_kwargs={'state_classes': (QuotedLiteralBlock,), 'initial_state': 'QuotedLiteralBlock'}) self.goto_line(new_abs_offset) return parent_node.children def definition_list_item(self, termline): indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() definitionlistitem = nodes.definition_list_item( '\n'.join(termline + list(indented))) lineno = self.state_machine.abs_line_number() - 1 src, srcline = self.state_machine.get_source_and_line() definitionlistitem.source = src definitionlistitem.line = srcline - 1 termlist, messages = self.term(termline, lineno) definitionlistitem += termlist definition = nodes.definition('', *messages) definitionlistitem += definition if termline[0][-2:] == '::': definition += self.reporter.info( 'Blank line missing before literal block (after the "::")? ' 'Interpreted as a definition list item.', source=src, line=srcline) self.nested_parse(indented, input_offset=line_offset, node=definition) return definitionlistitem, blank_finish classifier_delimiter = re.compile(' +: +') def term(self, lines, lineno): """Return a definition_list's term and optional classifiers.""" assert len(lines) == 1 text_nodes, messages = self.inline_text(lines[0], lineno) term_node = nodes.term() node_list = [term_node] for i in range(len(text_nodes)): node = text_nodes[i] if isinstance(node, nodes.Text): parts = self.classifier_delimiter.split(node.rawsource) if len(parts) == 1: node_list[-1] += node else: node_list[-1] += nodes.Text(parts[0].rstrip()) for part in parts[1:]: classifier_node = nodes.classifier('', part) node_list.append(classifier_node) else: node_list[-1] += node return node_list, messages class SpecializedText(Text): """ Superclass for second and subsequent lines of Text-variants. All transition methods are disabled. Override individual methods in subclasses to re-enable. """ def eof(self, context): """Incomplete construct.""" return [] def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" raise EOFError blank = invalid_input indent = invalid_input underline = invalid_input text = invalid_input class Definition(SpecializedText): """Second line of potential definition_list_item.""" def eof(self, context): """Not a definition.""" self.state_machine.previous_line(2) # so parent SM can reassess return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlistitem, blank_finish = self.definition_list_item(context) self.parent += definitionlistitem self.blank_finish = blank_finish return [], 'DefinitionList', [] class Line(SpecializedText): """ Second line of over- & underlined section title or transition marker. """ eofcheck = 1 # @@@ ??? """Set to 0 while parsing sections, so that we don't catch the EOF.""" def eof(self, context): """Transition marker at end of section or document.""" marker = context[0].strip() if self.memo.section_bubble_up_kludge: self.memo.section_bubble_up_kludge = 0 elif len(marker) < 4: self.state_correction(context) if self.eofcheck: # ignore EOFError with sections lineno = self.state_machine.abs_line_number() - 1 transition = nodes.transition(rawsource=context[0]) transition.line = lineno self.parent += transition self.eofcheck = 1 return [] def blank(self, match, context, next_state): """Transition marker.""" src, srcline = self.state_machine.get_source_and_line() marker = context[0].strip() if len(marker) < 4: self.state_correction(context) transition = nodes.transition(rawsource=marker) transition.source = src transition.line = srcline - 1 self.parent += transition return [], 'Body', [] def text(self, match, context, next_state): """Potential over- & underlined title.""" lineno = self.state_machine.abs_line_number() - 1 src, srcline = self.state_machine.get_source_and_line() overline = context[0] title = match.string underline = '' try: underline = self.state_machine.next_line() except EOFError: blocktext = overline + '\n' + title if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Incomplete section title.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline-1) self.parent += msg return [], 'Body', [] source = '%s\n%s\n%s' % (overline, title, underline) overline = overline.rstrip() underline = underline.rstrip() if not self.transitions['underline'][0].match(underline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Missing matching underline for section title overline.', nodes.literal_block(source, source), source=src, line=srcline-1) self.parent += msg return [], 'Body', [] elif overline != underline: blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Title overline & underline mismatch.', nodes.literal_block(source, source), source=src, line=srcline-1) self.parent += msg return [], 'Body', [] title = title.rstrip() messages = [] if column_width(title) > len(overline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.warning( 'Title overline too short.', nodes.literal_block(source, source), source=src, line=srcline-1) messages.append(msg) style = (overline[0], underline[0]) self.eofcheck = 0 # @@@ not sure this is correct self.section(title.lstrip(), source, style, lineno + 1, messages) self.eofcheck = 1 return [], 'Body', [] indent = text # indented title def underline(self, match, context, next_state): overline = context[0] blocktext = overline + '\n' + self.state_machine.line lineno = self.state_machine.abs_line_number() - 1 src, srcline = self.state_machine.get_source_and_line() if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 1) msg = self.reporter.error( 'Invalid section title or transition marker.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline-1) self.parent += msg return [], 'Body', [] def short_overline(self, context, blocktext, lineno, lines=1): src, srcline = self.state_machine.get_source_and_line(lineno) msg = self.reporter.info( 'Possible incomplete section title.\nTreating the overline as ' "ordinary text because it's so short.", source=src, line=srcline) self.parent += msg self.state_correction(context, lines) def state_correction(self, context, lines=1): self.state_machine.previous_line(lines) context[:] = [] raise statemachine.StateCorrection('Body', 'text') class QuotedLiteralBlock(RSTState): """ Nested parse handler for quoted (unindented) literal blocks. Special-purpose. Not for inclusion in `state_classes`. """ patterns = {'initial_quoted': r'(%(nonalphanum7bit)s)' % Body.pats, 'text': r''} initial_transitions = ('initial_quoted', 'text') def __init__(self, state_machine, debug=0): RSTState.__init__(self, state_machine, debug) self.messages = [] self.initial_lineno = None def blank(self, match, context, next_state): if context: raise EOFError else: return context, next_state, [] def eof(self, context): if context: src, srcline = self.state_machine.get_source_and_line( self.initial_lineno) text = '\n'.join(context) literal_block = nodes.literal_block(text, text) literal_block.source = src literal_block.line = srcline self.parent += literal_block else: self.parent += self.reporter.warning( 'Literal block expected; none found.', line=self.state_machine.abs_line_number()) # src not available, because statemachine.input_lines is empty self.state_machine.previous_line() self.parent += self.messages return [] def indent(self, match, context, next_state): assert context, ('QuotedLiteralBlock.indent: context should not ' 'be empty!') self.messages.append( self.reporter.error('Unexpected indentation.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError def initial_quoted(self, match, context, next_state): """Match arbitrary quote character on the first line only.""" self.remove_transition('initial_quoted') quote = match.string[0] pattern = re.compile(re.escape(quote)) # New transition matches consistent quotes only: self.add_transition('quoted', (pattern, self.quoted, self.__class__.__name__)) self.initial_lineno = self.state_machine.abs_line_number() return [match.string], next_state, [] def quoted(self, match, context, next_state): """Match consistent quotes on subsequent lines.""" context.append(match.string) return context, next_state, [] def text(self, match, context, next_state): if context: src, srcline = self.state_machine.get_source_and_line() self.messages.append( self.reporter.error('Inconsistent literal block quoting.', source=src, line=srcline)) self.state_machine.previous_line() raise EOFError state_classes = (Body, BulletList, DefinitionList, EnumeratedList, FieldList, OptionList, LineBlock, ExtensionOptions, Explicit, Text, Definition, Line, SubstitutionDef, RFC2822Body, RFC2822List) """Standard set of State classes used to start `RSTStateMachine`."""
Python
# $Id: tableparser.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This module defines table parser classes,which parse plaintext-graphic tables and produce a well-formed data structure suitable for building a CALS table. :Classes: - `GridTableParser`: Parse fully-formed tables represented with a grid. - `SimpleTableParser`: Parse simple tables, delimited by top & bottom borders. :Exception class: `TableMarkupError` :Function: `update_dict_of_lists()`: Merge two dictionaries containing list values. """ __docformat__ = 'reStructuredText' import re import sys from docutils import DataError class TableMarkupError(DataError): pass class TableParser: """ Abstract superclass for the common parts of the syntax-specific parsers. """ head_body_separator_pat = None """Matches the row separator between head rows and body rows.""" double_width_pad_char = '\x00' """Padding character for East Asian double-width text.""" def parse(self, block): """ Analyze the text `block` and return a table data structure. Given a plaintext-graphic table in `block` (list of lines of text; no whitespace padding), parse the table, construct and return the data necessary to construct a CALS table or equivalent. Raise `TableMarkupError` if there is any problem with the markup. """ self.setup(block) self.find_head_body_sep() self.parse_table() structure = self.structure_from_cells() return structure def find_head_body_sep(self): """Look for a head/body row separator line; store the line index.""" for i in range(len(self.block)): line = self.block[i] if self.head_body_separator_pat.match(line): if self.head_body_sep: raise TableMarkupError( 'Multiple head/body row separators in table (at line ' 'offset %s and %s); only one allowed.' % (self.head_body_sep, i)) else: self.head_body_sep = i self.block[i] = line.replace('=', '-') if self.head_body_sep == 0 or self.head_body_sep == (len(self.block) - 1): raise TableMarkupError('The head/body row separator may not be ' 'the first or last line of the table.') class GridTableParser(TableParser): """ Parse a grid table using `parse()`. Here's an example of a grid table:: +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | +------------------------+------------+---------------------+ Intersections use '+', row separators use '-' (except for one optional head/body row separator, which uses '='), and column separators use '|'. Passing the above table to the `parse()` method will result in the following data structure:: ([24, 12, 10, 10], [[(0, 0, 1, ['Header row, column 1']), (0, 0, 1, ['Header 2']), (0, 0, 1, ['Header 3']), (0, 0, 1, ['Header 4'])]], [[(0, 0, 3, ['body row 1, column 1']), (0, 0, 3, ['column 2']), (0, 0, 3, ['column 3']), (0, 0, 3, ['column 4'])], [(0, 0, 5, ['body row 2']), (0, 2, 5, ['Cells may span columns.']), None, None], [(0, 0, 7, ['body row 3']), (1, 0, 7, ['Cells may', 'span rows.', '']), (1, 1, 7, ['- Table cells', '- contain', '- body elements.']), None], [(0, 0, 9, ['body row 4']), None, None, None]]) The first item is a list containing column widths (colspecs). The second item is a list of head rows, and the third is a list of body rows. Each row contains a list of cells. Each cell is either None (for a cell unused because of another cell's span), or a tuple. A cell tuple contains four items: the number of extra rows used by the cell in a vertical span (morerows); the number of extra columns used by the cell in a horizontal span (morecols); the line offset of the first line of the cell contents; and the cell contents, a list of lines of text. """ head_body_separator_pat = re.compile(r'\+=[=+]+=\+ *$') def setup(self, block): self.block = block[:] # make a copy; it may be modified self.block.disconnect() # don't propagate changes to parent self.bottom = len(block) - 1 self.right = len(block[0]) - 1 self.head_body_sep = None self.done = [-1] * len(block[0]) self.cells = [] self.rowseps = {0: [0]} self.colseps = {0: [0]} def parse_table(self): """ Start with a queue of upper-left corners, containing the upper-left corner of the table itself. Trace out one rectangular cell, remember it, and add its upper-right and lower-left corners to the queue of potential upper-left corners of further cells. Process the queue in top-to-bottom order, keeping track of how much of each text column has been seen. We'll end up knowing all the row and column boundaries, cell positions and their dimensions. """ corners = [(0, 0)] while corners: top, left = corners.pop(0) if top == self.bottom or left == self.right \ or top <= self.done[left]: continue result = self.scan_cell(top, left) if not result: continue bottom, right, rowseps, colseps = result update_dict_of_lists(self.rowseps, rowseps) update_dict_of_lists(self.colseps, colseps) self.mark_done(top, left, bottom, right) cellblock = self.block.get_2D_block(top + 1, left + 1, bottom, right) cellblock.disconnect() # lines in cell can't sync with parent cellblock.replace(self.double_width_pad_char, '') self.cells.append((top, left, bottom, right, cellblock)) corners.extend([(top, right), (bottom, left)]) corners.sort() if not self.check_parse_complete(): raise TableMarkupError('Malformed table; parse incomplete.') def mark_done(self, top, left, bottom, right): """For keeping track of how much of each text column has been seen.""" before = top - 1 after = bottom - 1 for col in range(left, right): assert self.done[col] == before self.done[col] = after def check_parse_complete(self): """Each text column should have been completely seen.""" last = self.bottom - 1 for col in range(self.right): if self.done[col] != last: return None return 1 def scan_cell(self, top, left): """Starting at the top-left corner, start tracing out a cell.""" assert self.block[top][left] == '+' result = self.scan_right(top, left) return result def scan_right(self, top, left): """ Look for the top-right corner of the cell, and make note of all column boundaries ('+'). """ colseps = {} line = self.block[top] for i in range(left + 1, self.right + 1): if line[i] == '+': colseps[i] = [top] result = self.scan_down(top, left, i) if result: bottom, rowseps, newcolseps = result update_dict_of_lists(colseps, newcolseps) return bottom, i, rowseps, colseps elif line[i] != '-': return None return None def scan_down(self, top, left, right): """ Look for the bottom-right corner of the cell, making note of all row boundaries. """ rowseps = {} for i in range(top + 1, self.bottom + 1): if self.block[i][right] == '+': rowseps[i] = [right] result = self.scan_left(top, left, i, right) if result: newrowseps, colseps = result update_dict_of_lists(rowseps, newrowseps) return i, rowseps, colseps elif self.block[i][right] != '|': return None return None def scan_left(self, top, left, bottom, right): """ Noting column boundaries, look for the bottom-left corner of the cell. It must line up with the starting point. """ colseps = {} line = self.block[bottom] for i in range(right - 1, left, -1): if line[i] == '+': colseps[i] = [bottom] elif line[i] != '-': return None if line[left] != '+': return None result = self.scan_up(top, left, bottom, right) if result is not None: rowseps = result return rowseps, colseps return None def scan_up(self, top, left, bottom, right): """ Noting row boundaries, see if we can return to the starting point. """ rowseps = {} for i in range(bottom - 1, top, -1): if self.block[i][left] == '+': rowseps[i] = [left] elif self.block[i][left] != '|': return None return rowseps def structure_from_cells(self): """ From the data collected by `scan_cell()`, convert to the final data structure. """ rowseps = self.rowseps.keys() # list of row boundaries rowseps.sort() rowindex = {} for i in range(len(rowseps)): rowindex[rowseps[i]] = i # row boundary -> row number mapping colseps = self.colseps.keys() # list of column boundaries colseps.sort() colindex = {} for i in range(len(colseps)): colindex[colseps[i]] = i # column boundary -> col number map colspecs = [(colseps[i] - colseps[i - 1] - 1) for i in range(1, len(colseps))] # list of column widths # prepare an empty table with the correct number of rows & columns onerow = [None for i in range(len(colseps) - 1)] rows = [onerow[:] for i in range(len(rowseps) - 1)] # keep track of # of cells remaining; should reduce to zero remaining = (len(rowseps) - 1) * (len(colseps) - 1) for top, left, bottom, right, block in self.cells: rownum = rowindex[top] colnum = colindex[left] assert rows[rownum][colnum] is None, ( 'Cell (row %s, column %s) already used.' % (rownum + 1, colnum + 1)) morerows = rowindex[bottom] - rownum - 1 morecols = colindex[right] - colnum - 1 remaining -= (morerows + 1) * (morecols + 1) # write the cell into the table rows[rownum][colnum] = (morerows, morecols, top + 1, block) assert remaining == 0, 'Unused cells remaining.' if self.head_body_sep: # separate head rows from body rows numheadrows = rowindex[self.head_body_sep] headrows = rows[:numheadrows] bodyrows = rows[numheadrows:] else: headrows = [] bodyrows = rows return (colspecs, headrows, bodyrows) class SimpleTableParser(TableParser): """ Parse a simple table using `parse()`. Here's an example of a simple table:: ===== ===== col 1 col 2 ===== ===== 1 Second column of row 1. 2 Second column of row 2. Second line of paragraph. 3 - Second column of row 3. - Second item in bullet list (row 3, column 2). 4 is a span ------------ 5 ===== ===== Top and bottom borders use '=', column span underlines use '-', column separation is indicated with spaces. Passing the above table to the `parse()` method will result in the following data structure, whose interpretation is the same as for `GridTableParser`:: ([5, 25], [[(0, 0, 1, ['col 1']), (0, 0, 1, ['col 2'])]], [[(0, 0, 3, ['1']), (0, 0, 3, ['Second column of row 1.'])], [(0, 0, 4, ['2']), (0, 0, 4, ['Second column of row 2.', 'Second line of paragraph.'])], [(0, 0, 6, ['3']), (0, 0, 6, ['- Second column of row 3.', '', '- Second item in bullet', ' list (row 3, column 2).'])], [(0, 1, 10, ['4 is a span'])], [(0, 0, 12, ['5']), (0, 0, 12, [''])]]) """ head_body_separator_pat = re.compile('=[ =]*$') span_pat = re.compile('-[ -]*$') def setup(self, block): self.block = block[:] # make a copy; it will be modified self.block.disconnect() # don't propagate changes to parent # Convert top & bottom borders to column span underlines: self.block[0] = self.block[0].replace('=', '-') self.block[-1] = self.block[-1].replace('=', '-') self.head_body_sep = None self.columns = [] self.border_end = None self.table = [] self.done = [-1] * len(block[0]) self.rowseps = {0: [0]} self.colseps = {0: [0]} def parse_table(self): """ First determine the column boundaries from the top border, then process rows. Each row may consist of multiple lines; accumulate lines until a row is complete. Call `self.parse_row` to finish the job. """ # Top border must fully describe all table columns. self.columns = self.parse_columns(self.block[0], 0) self.border_end = self.columns[-1][1] firststart, firstend = self.columns[0] offset = 1 # skip top border start = 1 text_found = None while offset < len(self.block): line = self.block[offset] if self.span_pat.match(line): # Column span underline or border; row is complete. self.parse_row(self.block[start:offset], start, (line.rstrip(), offset)) start = offset + 1 text_found = None elif line[firststart:firstend].strip(): # First column not blank, therefore it's a new row. if text_found and offset != start: self.parse_row(self.block[start:offset], start) start = offset text_found = 1 elif not text_found: start = offset + 1 offset += 1 def parse_columns(self, line, offset): """ Given a column span underline, return a list of (begin, end) pairs. """ cols = [] end = 0 while 1: begin = line.find('-', end) end = line.find(' ', begin) if begin < 0: break if end < 0: end = len(line) cols.append((begin, end)) if self.columns: if cols[-1][1] != self.border_end: raise TableMarkupError('Column span incomplete at line ' 'offset %s.' % offset) # Allow for an unbounded rightmost column: cols[-1] = (cols[-1][0], self.columns[-1][1]) return cols def init_row(self, colspec, offset): i = 0 cells = [] for start, end in colspec: morecols = 0 try: assert start == self.columns[i][0] while end != self.columns[i][1]: i += 1 morecols += 1 except (AssertionError, IndexError): raise TableMarkupError('Column span alignment problem at ' 'line offset %s.' % (offset + 1)) cells.append([0, morecols, offset, []]) i += 1 return cells def parse_row(self, lines, start, spanline=None): """ Given the text `lines` of a row, parse it and append to `self.table`. The row is parsed according to the current column spec (either `spanline` if provided or `self.columns`). For each column, extract text from each line, and check for text in column margins. Finally, adjust for insigificant whitespace. """ if not (lines or spanline): # No new row, just blank lines. return if spanline: columns = self.parse_columns(*spanline) span_offset = spanline[1] else: columns = self.columns[:] span_offset = start self.check_columns(lines, start, columns) row = self.init_row(columns, start) for i in range(len(columns)): start, end = columns[i] cellblock = lines.get_2D_block(0, start, len(lines), end) cellblock.disconnect() # lines in cell can't sync with parent cellblock.replace(self.double_width_pad_char, '') row[i][3] = cellblock self.table.append(row) def check_columns(self, lines, first_line, columns): """ Check for text in column margins and text overflow in the last column. Raise TableMarkupError if anything but whitespace is in column margins. Adjust the end value for the last column if there is text overflow. """ # "Infinite" value for a dummy last column's beginning, used to # check for text overflow: columns.append((sys.maxint, None)) lastcol = len(columns) - 2 for i in range(len(columns) - 1): start, end = columns[i] nextstart = columns[i+1][0] offset = 0 for line in lines: if i == lastcol and line[end:].strip(): text = line[start:].rstrip() new_end = start + len(text) columns[i] = (start, new_end) main_start, main_end = self.columns[-1] if new_end > main_end: self.columns[-1] = (main_start, new_end) elif line[end:nextstart].strip(): raise TableMarkupError('Text in column margin at line ' 'offset %s.' % (first_line + offset)) offset += 1 columns.pop() def structure_from_cells(self): colspecs = [end - start for start, end in self.columns] first_body_row = 0 if self.head_body_sep: for i in range(len(self.table)): if self.table[i][0][2] > self.head_body_sep: first_body_row = i break return (colspecs, self.table[:first_body_row], self.table[first_body_row:]) def update_dict_of_lists(master, newdata): """ Extend the list values of `master` with those from `newdata`. Both parameters must be dictionaries containing list values. """ for key, values in newdata.items(): master.setdefault(key, []).extend(values)
Python
# $Id: __init__.py 5618 2008-07-28 08:37:32Z strank $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This package contains Docutils parser modules. """ __docformat__ = 'reStructuredText' from docutils import Component class Parser(Component): component_type = 'parser' config_section = 'parsers' def parse(self, inputstring, document): """Override to parse `inputstring` into document tree `document`.""" raise NotImplementedError('subclass must override this method') def setup_parse(self, inputstring, document): """Initial parse setup. Call at start of `self.parse()`.""" self.inputstring = inputstring self.document = document document.reporter.attach_observer(document.note_parse_message) def finish_parse(self): """Finalize parse details. Call at end of `self.parse()`.""" self.document.reporter.detach_observer( self.document.note_parse_message) _parser_aliases = { 'restructuredtext': 'rst', 'rest': 'rst', 'restx': 'rst', 'rtxt': 'rst',} def get_parser_class(parser_name): """Return the Parser class from the `parser_name` module.""" parser_name = parser_name.lower() if parser_name in _parser_aliases: parser_name = _parser_aliases[parser_name] module = __import__(parser_name, globals(), locals()) return module.Parser
Python
# $Id: core.py 6294 2010-03-26 10:47:00Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Calling the ``publish_*`` convenience functions (or instantiating a `Publisher` object) with component names will result in default behavior. For custom behavior (setting component options), create custom component objects first, and pass *them* to ``publish_*``/`Publisher`. See `The Docutils Publisher`_. .. _The Docutils Publisher: http://docutils.sf.net/docs/api/publisher.html """ __docformat__ = 'reStructuredText' import sys import pprint from docutils import __version__, __version_details__, SettingsSpec from docutils import frontend, io, utils, readers, writers from docutils.frontend import OptionParser from docutils.transforms import Transformer import docutils.readers.doctree class Publisher: """ A facade encapsulating the high-level logic of a Docutils system. """ def __init__(self, reader=None, parser=None, writer=None, source=None, source_class=io.FileInput, destination=None, destination_class=io.FileOutput, settings=None): """ Initial setup. If any of `reader`, `parser`, or `writer` are not specified, the corresponding ``set_...`` method should be called with a component name (`set_reader` sets the parser as well). """ self.document = None """The document tree (`docutils.nodes` objects).""" self.reader = reader """A `docutils.readers.Reader` instance.""" self.parser = parser """A `docutils.parsers.Parser` instance.""" self.writer = writer """A `docutils.writers.Writer` instance.""" for component in 'reader', 'parser', 'writer': assert not isinstance(getattr(self, component), str), ( 'passed string "%s" as "%s" parameter; pass an instance, ' 'or use the "%s_name" parameter instead (in ' 'docutils.core.publish_* convenience functions).' % (getattr(self, component), component, component)) self.source = source """The source of input data, a `docutils.io.Input` instance.""" self.source_class = source_class """The class for dynamically created source objects.""" self.destination = destination """The destination for docutils output, a `docutils.io.Output` instance.""" self.destination_class = destination_class """The class for dynamically created destination objects.""" self.settings = settings """An object containing Docutils settings as instance attributes. Set by `self.process_command_line()` or `self.get_settings()`.""" def set_reader(self, reader_name, parser, parser_name): """Set `self.reader` by name.""" reader_class = readers.get_reader_class(reader_name) self.reader = reader_class(parser, parser_name) self.parser = self.reader.parser def set_writer(self, writer_name): """Set `self.writer` by name.""" writer_class = writers.get_writer_class(writer_name) self.writer = writer_class() def set_components(self, reader_name, parser_name, writer_name): if self.reader is None: self.set_reader(reader_name, self.parser, parser_name) if self.parser is None: if self.reader.parser is None: self.reader.set_parser(parser_name) self.parser = self.reader.parser if self.writer is None: self.set_writer(writer_name) def setup_option_parser(self, usage=None, description=None, settings_spec=None, config_section=None, **defaults): if config_section: if not settings_spec: settings_spec = SettingsSpec() settings_spec.config_section = config_section parts = config_section.split() if len(parts) > 1 and parts[-1] == 'application': settings_spec.config_section_dependencies = ['applications'] #@@@ Add self.source & self.destination to components in future? option_parser = OptionParser( components=(self.parser, self.reader, self.writer, settings_spec), defaults=defaults, read_config_files=1, usage=usage, description=description) return option_parser def get_settings(self, usage=None, description=None, settings_spec=None, config_section=None, **defaults): """ Set and return default settings (overrides in `defaults` dict). Set components first (`self.set_reader` & `self.set_writer`). Explicitly setting `self.settings` disables command line option processing from `self.publish()`. """ option_parser = self.setup_option_parser( usage, description, settings_spec, config_section, **defaults) self.settings = option_parser.get_default_values() return self.settings def process_programmatic_settings(self, settings_spec, settings_overrides, config_section): if self.settings is None: defaults = (settings_overrides or {}).copy() # Propagate exceptions by default when used programmatically: defaults.setdefault('traceback', 1) self.get_settings(settings_spec=settings_spec, config_section=config_section, **defaults) def process_command_line(self, argv=None, usage=None, description=None, settings_spec=None, config_section=None, **defaults): """ Pass an empty list to `argv` to avoid reading `sys.argv` (the default). Set components first (`self.set_reader` & `self.set_writer`). """ option_parser = self.setup_option_parser( usage, description, settings_spec, config_section, **defaults) if argv is None: argv = sys.argv[1:] self.settings = option_parser.parse_args(argv) def set_io(self, source_path=None, destination_path=None): if self.source is None: self.set_source(source_path=source_path) if self.destination is None: self.set_destination(destination_path=destination_path) def set_source(self, source=None, source_path=None): if source_path is None: source_path = self.settings._source else: self.settings._source = source_path self.source = self.source_class( source=source, source_path=source_path, encoding=self.settings.input_encoding) def set_destination(self, destination=None, destination_path=None): if destination_path is None: destination_path = self.settings._destination else: self.settings._destination = destination_path self.destination = self.destination_class( destination=destination, destination_path=destination_path, encoding=self.settings.output_encoding, error_handler=self.settings.output_encoding_error_handler) def apply_transforms(self): self.document.transformer.populate_from_components( (self.source, self.reader, self.reader.parser, self.writer, self.destination)) self.document.transformer.apply_transforms() def publish(self, argv=None, usage=None, description=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=None): """ Process command line options and arguments (if `self.settings` not already set), run `self.reader` and then `self.writer`. Return `self.writer`'s output. """ exit = None try: if self.settings is None: self.process_command_line( argv, usage, description, settings_spec, config_section, **(settings_overrides or {})) self.set_io() self.document = self.reader.read(self.source, self.parser, self.settings) self.apply_transforms() output = self.writer.write(self.document, self.destination) self.writer.assemble_parts() except SystemExit, error: exit = 1 exit_status = error.code except Exception, error: if not self.settings: # exception too early to report nicely raise if self.settings.traceback: # Propagate exceptions? self.debugging_dumps() raise self.report_Exception(error) exit = 1 exit_status = 1 self.debugging_dumps() if (enable_exit_status and self.document and (self.document.reporter.max_level >= self.settings.exit_status_level)): sys.exit(self.document.reporter.max_level + 10) elif exit: sys.exit(exit_status) return output def debugging_dumps(self): if not self.document: return if self.settings.dump_settings: print >>sys.stderr, '\n::: Runtime settings:' print >>sys.stderr, pprint.pformat(self.settings.__dict__) if self.settings.dump_internals: print >>sys.stderr, '\n::: Document internals:' print >>sys.stderr, pprint.pformat(self.document.__dict__) if self.settings.dump_transforms: print >>sys.stderr, '\n::: Transforms applied:' print >>sys.stderr, (' (priority, transform class, ' 'pending node details, keyword args)') print >>sys.stderr, pprint.pformat( [(priority, '%s.%s' % (xclass.__module__, xclass.__name__), pending and pending.details, kwargs) for priority, xclass, pending, kwargs in self.document.transformer.applied]) if self.settings.dump_pseudo_xml: print >>sys.stderr, '\n::: Pseudo-XML:' print >>sys.stderr, self.document.pformat().encode( 'raw_unicode_escape') def report_Exception(self, error): if isinstance(error, utils.SystemMessage): self.report_SystemMessage(error) elif isinstance(error, UnicodeEncodeError): self.report_UnicodeError(error) else: print >>sys.stderr, '%s: %s' % (error.__class__.__name__, error) print >>sys.stderr, ("""\ Exiting due to error. Use "--traceback" to diagnose. Please report errors to <docutils-users@lists.sf.net>. Include "--traceback" output, Docutils version (%s [%s]), Python version (%s), your OS type & version, and the command line used.""" % (__version__, __version_details__, sys.version.split()[0])) def report_SystemMessage(self, error): print >>sys.stderr, ('Exiting due to level-%s (%s) system message.' % (error.level, utils.Reporter.levels[error.level])) def report_UnicodeError(self, error): data = error.object[error.start:error.end] sys.stderr.write( '%s: %s\n' '\n' 'The specified output encoding (%s) cannot\n' 'handle all of the output.\n' 'Try setting "--output-encoding-error-handler" to\n' '\n' '* "xmlcharrefreplace" (for HTML & XML output);\n' ' the output will contain "%s" and should be usable.\n' '* "backslashreplace" (for other output formats);\n' ' look for "%s" in the output.\n' '* "replace"; look for "?" in the output.\n' '\n' '"--output-encoding-error-handler" is currently set to "%s".\n' '\n' 'Exiting due to error. Use "--traceback" to diagnose.\n' 'If the advice above doesn\'t eliminate the error,\n' 'please report it to <docutils-users@lists.sf.net>.\n' 'Include "--traceback" output, Docutils version (%s),\n' 'Python version (%s), your OS type & version, and the\n' 'command line used.\n' % (error.__class__.__name__, error, self.settings.output_encoding, data.encode('ascii', 'xmlcharrefreplace'), data.encode('ascii', 'backslashreplace'), self.settings.output_encoding_error_handler, __version__, sys.version.split()[0])) default_usage = '%prog [options] [<source> [<destination>]]' default_description = ('Reads from <source> (default is stdin) and writes to ' '<destination> (default is stdout). See ' '<http://docutils.sf.net/docs/user/config.html> for ' 'the full reference.') def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=1, argv=None, usage=default_usage, description=default_description): """ Set up & run a `Publisher` for command-line-based file I/O (input and output file paths taken automatically from the command line). Return the encoded string output also. Parameters: see `publish_programmatically` for the remainder. - `argv`: Command-line argument list to use instead of ``sys.argv[1:]``. - `usage`: Usage string, output if there's a problem parsing the command line. - `description`: Program description, output for the "--help" option (along with command-line option descriptions). """ pub = Publisher(reader, parser, writer, settings=settings) pub.set_components(reader_name, parser_name, writer_name) output = pub.publish( argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return output def publish_file(source=None, source_path=None, destination=None, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=None): """ Set up & run a `Publisher` for programmatic use with file-like I/O. Return the encoded string output also. Parameters: see `publish_programmatically`. """ output, pub = publish_programmatically( source_class=io.FileInput, source=source, source_path=source_path, destination_class=io.FileOutput, destination=destination, destination_path=destination_path, reader=reader, reader_name=reader_name, parser=parser, parser_name=parser_name, writer=writer, writer_name=writer_name, settings=settings, settings_spec=settings_spec, settings_overrides=settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return output def publish_string(source, source_path=None, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=None): """ Set up & run a `Publisher` for programmatic use with string I/O. Return the encoded string or Unicode string output. For encoded string output, be sure to set the 'output_encoding' setting to the desired encoding. Set it to 'unicode' for unencoded Unicode string output. Here's one way:: publish_string(..., settings_overrides={'output_encoding': 'unicode'}) Similarly for Unicode string input (`source`):: publish_string(..., settings_overrides={'input_encoding': 'unicode'}) Parameters: see `publish_programmatically`. """ output, pub = publish_programmatically( source_class=io.StringInput, source=source, source_path=source_path, destination_class=io.StringOutput, destination=None, destination_path=destination_path, reader=reader, reader_name=reader_name, parser=parser, parser_name=parser_name, writer=writer, writer_name=writer_name, settings=settings, settings_spec=settings_spec, settings_overrides=settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return output def publish_parts(source, source_path=None, source_class=io.StringInput, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=None): """ Set up & run a `Publisher`, and return a dictionary of document parts. Dictionary keys are the names of parts, and values are Unicode strings; encoding is up to the client. For programmatic use with string I/O. For encoded string input, be sure to set the 'input_encoding' setting to the desired encoding. Set it to 'unicode' for unencoded Unicode string input. Here's how:: publish_parts(..., settings_overrides={'input_encoding': 'unicode'}) Parameters: see `publish_programmatically`. """ output, pub = publish_programmatically( source=source, source_path=source_path, source_class=source_class, destination_class=io.StringOutput, destination=None, destination_path=destination_path, reader=reader, reader_name=reader_name, parser=parser, parser_name=parser_name, writer=writer, writer_name=writer_name, settings=settings, settings_spec=settings_spec, settings_overrides=settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return pub.writer.parts def publish_doctree(source, source_path=None, source_class=io.StringInput, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=None): """ Set up & run a `Publisher` for programmatic use with string I/O. Return the document tree. For encoded string input, be sure to set the 'input_encoding' setting to the desired encoding. Set it to 'unicode' for unencoded Unicode string input. Here's one way:: publish_doctree(..., settings_overrides={'input_encoding': 'unicode'}) Parameters: see `publish_programmatically`. """ pub = Publisher(reader=reader, parser=parser, writer=None, settings=settings, source_class=source_class, destination_class=io.NullOutput) pub.set_components(reader_name, parser_name, 'null') pub.process_programmatic_settings( settings_spec, settings_overrides, config_section) pub.set_source(source, source_path) pub.set_destination(None, None) output = pub.publish(enable_exit_status=enable_exit_status) return pub.document def publish_from_doctree(document, destination_path=None, writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=None): """ Set up & run a `Publisher` to render from an existing document tree data structure, for programmatic use with string I/O. Return the encoded string output. Note that document.settings is overridden; if you want to use the settings of the original `document`, pass settings=document.settings. Also, new document.transformer and document.reporter objects are generated. For encoded string output, be sure to set the 'output_encoding' setting to the desired encoding. Set it to 'unicode' for unencoded Unicode string output. Here's one way:: publish_from_doctree( ..., settings_overrides={'output_encoding': 'unicode'}) Parameters: `document` is a `docutils.nodes.document` object, an existing document tree. Other parameters: see `publish_programmatically`. """ reader = docutils.readers.doctree.Reader(parser_name='null') pub = Publisher(reader, None, writer, source=io.DocTreeInput(document), destination_class=io.StringOutput, settings=settings) if not writer and writer_name: pub.set_writer(writer_name) pub.process_programmatic_settings( settings_spec, settings_overrides, config_section) pub.set_destination(None, destination_path) return pub.publish(enable_exit_status=enable_exit_status) def publish_cmdline_to_binary(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=1, argv=None, usage=default_usage, description=default_description, destination=None, destination_class=io.BinaryFileOutput ): """ Set up & run a `Publisher` for command-line-based file I/O (input and output file paths taken automatically from the command line). Return the encoded string output also. This is just like publish_cmdline, except that it uses io.BinaryFileOutput instead of io.FileOutput. Parameters: see `publish_programmatically` for the remainder. - `argv`: Command-line argument list to use instead of ``sys.argv[1:]``. - `usage`: Usage string, output if there's a problem parsing the command line. - `description`: Program description, output for the "--help" option (along with command-line option descriptions). """ pub = Publisher(reader, parser, writer, settings=settings, destination_class=destination_class) pub.set_components(reader_name, parser_name, writer_name) output = pub.publish( argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return output def publish_programmatically(source_class, source, source_path, destination_class, destination, destination_path, reader, reader_name, parser, parser_name, writer, writer_name, settings, settings_spec, settings_overrides, config_section, enable_exit_status): """ Set up & run a `Publisher` for custom programmatic use. Return the encoded string output and the Publisher object. Applications should not need to call this function directly. If it does seem to be necessary to call this function directly, please write to the Docutils-develop mailing list <http://docutils.sf.net/docs/user/mailing-lists.html#docutils-develop>. Parameters: * `source_class` **required**: The class for dynamically created source objects. Typically `io.FileInput` or `io.StringInput`. * `source`: Type depends on `source_class`: - If `source_class` is `io.FileInput`: Either a file-like object (must have 'read' and 'close' methods), or ``None`` (`source_path` is opened). If neither `source` nor `source_path` are supplied, `sys.stdin` is used. - If `source_class` is `io.StringInput` **required**: The input string, either an encoded 8-bit string (set the 'input_encoding' setting to the correct encoding) or a Unicode string (set the 'input_encoding' setting to 'unicode'). * `source_path`: Type depends on `source_class`: - `io.FileInput`: Path to the input file, opened if no `source` supplied. - `io.StringInput`: Optional. Path to the file or object that produced `source`. Only used for diagnostic output. * `destination_class` **required**: The class for dynamically created destination objects. Typically `io.FileOutput` or `io.StringOutput`. * `destination`: Type depends on `destination_class`: - `io.FileOutput`: Either a file-like object (must have 'write' and 'close' methods), or ``None`` (`destination_path` is opened). If neither `destination` nor `destination_path` are supplied, `sys.stdout` is used. - `io.StringOutput`: Not used; pass ``None``. * `destination_path`: Type depends on `destination_class`: - `io.FileOutput`: Path to the output file. Opened if no `destination` supplied. - `io.StringOutput`: Path to the file or object which will receive the output; optional. Used for determining relative paths (stylesheets, source links, etc.). * `reader`: A `docutils.readers.Reader` object. * `reader_name`: Name or alias of the Reader class to be instantiated if no `reader` supplied. * `parser`: A `docutils.parsers.Parser` object. * `parser_name`: Name or alias of the Parser class to be instantiated if no `parser` supplied. * `writer`: A `docutils.writers.Writer` object. * `writer_name`: Name or alias of the Writer class to be instantiated if no `writer` supplied. * `settings`: A runtime settings (`docutils.frontend.Values`) object, for dotted-attribute access to runtime settings. It's the end result of the `SettingsSpec`, config file, and option processing. If `settings` is passed, it's assumed to be complete and no further setting/config/option processing is done. * `settings_spec`: A `docutils.SettingsSpec` subclass or object. Provides extra application-specific settings definitions independently of components. In other words, the application becomes a component, and its settings data is processed along with that of the other components. Used only if no `settings` specified. * `settings_overrides`: A dictionary containing application-specific settings defaults that override the defaults of other components. Used only if no `settings` specified. * `config_section`: A string, the name of the configuration file section for this application. Overrides the ``config_section`` attribute defined by `settings_spec`. Used only if no `settings` specified. * `enable_exit_status`: Boolean; enable exit status at end of processing? """ pub = Publisher(reader, parser, writer, settings=settings, source_class=source_class, destination_class=destination_class) pub.set_components(reader_name, parser_name, writer_name) pub.process_programmatic_settings( settings_spec, settings_overrides, config_section) pub.set_source(source, source_path) pub.set_destination(destination, destination_path) output = pub.publish(enable_exit_status=enable_exit_status) return output, pub
Python
# $Id: _compat.py 5908 2009-04-21 13:43:23Z goodger $ # Author: Georg Brandl <georg@python.org> # Copyright: This module has been placed in the public domain. """ Python 2/3 compatibility definitions. This module currently provides the following helper symbols: * bytes (name of byte string type; str in 2.x, bytes in 3.x) * b (function converting a string literal to an ASCII byte string; can be also used to convert a Unicode string into a byte string) * u_prefix (unicode repr prefix, 'u' in 2.x, nothing in 3.x) * BytesIO (a StringIO class that works with bytestrings) """ import sys if sys.version_info < (3,0): b = bytes = str u_prefix = 'u' from StringIO import StringIO as BytesIO else: import builtins bytes = builtins.bytes u_prefix = '' def b(s): if isinstance(s, str): return s.encode('latin1') elif isinstance(s, bytes): return s else: raise TypeError("Invalid argument %r for b()" % (s,)) # using this hack since 2to3 "fixes" the relative import # when using ``from io import BytesIO`` BytesIO = __import__('io').BytesIO
Python
# $Id: statemachine.py 6314 2010-04-26 10:04:17Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ A finite state machine specialized for regular-expression-based text filters, this module defines the following classes: - `StateMachine`, a state machine - `State`, a state superclass - `StateMachineWS`, a whitespace-sensitive version of `StateMachine` - `StateWS`, a state superclass for use with `StateMachineWS` - `SearchStateMachine`, uses `re.search()` instead of `re.match()` - `SearchStateMachineWS`, uses `re.search()` instead of `re.match()` - `ViewList`, extends standard Python lists. - `StringList`, string-specific ViewList. Exception classes: - `StateMachineError` - `UnknownStateError` - `DuplicateStateError` - `UnknownTransitionError` - `DuplicateTransitionError` - `TransitionPatternNotFound` - `TransitionMethodNotFound` - `UnexpectedIndentationError` - `TransitionCorrection`: Raised to switch to another transition. - `StateCorrection`: Raised to switch to another state & transition. Functions: - `string2lines()`: split a multi-line string into a list of one-line strings How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``import statemachine`` or ``from statemachine import ...``. You will also need to ``import re``. 2. Derive a subclass of `State` (or `StateWS`) for each state in your state machine:: class MyState(statemachine.State): Within the state's class definition: a) Include a pattern for each transition, in `State.patterns`:: patterns = {'atransition': r'pattern', ...} b) Include a list of initial transitions to be set up automatically, in `State.initial_transitions`:: initial_transitions = ['atransition', ...] c) Define a method for each transition, with the same name as the transition pattern:: def atransition(self, match, context, next_state): # do something result = [...] # a list return context, next_state, result # context, next_state may be altered Transition methods may raise an `EOFError` to cut processing short. d) You may wish to override the `State.bof()` and/or `State.eof()` implicit transition methods, which handle the beginning- and end-of-file. e) In order to handle nested processing, you may wish to override the attributes `State.nested_sm` and/or `State.nested_sm_kwargs`. If you are using `StateWS` as a base class, in order to handle nested indented blocks, you may wish to: - override the attributes `StateWS.indent_sm`, `StateWS.indent_sm_kwargs`, `StateWS.known_indent_sm`, and/or `StateWS.known_indent_sm_kwargs`; - override the `StateWS.blank()` method; and/or - override or extend the `StateWS.indent()`, `StateWS.known_indent()`, and/or `StateWS.firstknown_indent()` methods. 3. Create a state machine object:: sm = StateMachine(state_classes=[MyState, ...], initial_state='MyState') 4. Obtain the input text, which needs to be converted into a tab-free list of one-line strings. For example, to read text from a file called 'inputfile':: input_string = open('inputfile').read() input_lines = statemachine.string2lines(input_string) 5. Run the state machine on the input text and collect the results, a list:: results = sm.run(input_lines) 6. Remove any lingering circular references:: sm.unlink() """ __docformat__ = 'restructuredtext' import sys import re import types import unicodedata class StateMachine: """ A finite state machine for text filters using regular expressions. The input is provided in the form of a list of one-line strings (no newlines). States are subclasses of the `State` class. Transitions consist of regular expression patterns and transition methods, and are defined in each state. The state machine is started with the `run()` method, which returns the results of processing in a list. """ def __init__(self, state_classes, initial_state, debug=0): """ Initialize a `StateMachine` object; add state objects. Parameters: - `state_classes`: a list of `State` (sub)classes. - `initial_state`: a string, the class name of the initial state. - `debug`: a boolean; produce verbose output if true (nonzero). """ self.input_lines = None """`StringList` of input lines (without newlines). Filled by `self.run()`.""" self.input_offset = 0 """Offset of `self.input_lines` from the beginning of the file.""" self.line = None """Current input line.""" self.line_offset = -1 """Current input line offset from beginning of `self.input_lines`.""" self.debug = debug """Debugging mode on/off.""" self.initial_state = initial_state """The name of the initial state (key to `self.states`).""" self.current_state = initial_state """The name of the current state (key to `self.states`).""" self.states = {} """Mapping of {state_name: State_object}.""" self.add_states(state_classes) self.observers = [] """List of bound methods or functions to call whenever the current line changes. Observers are called with one argument, ``self``. Cleared at the end of `run()`.""" def unlink(self): """Remove circular references to objects no longer required.""" for state in self.states.values(): state.unlink() self.states = None def run(self, input_lines, input_offset=0, context=None, input_source=None, initial_state=None): """ Run the state machine on `input_lines`. Return results (a list). Reset `self.line_offset` and `self.current_state`. Run the beginning-of-file transition. Input one line at a time and check for a matching transition. If a match is found, call the transition method and possibly change the state. Store the context returned by the transition method to be passed on to the next transition matched. Accumulate the results returned by the transition methods in a list. Run the end-of-file transition. Finally, return the accumulated results. Parameters: - `input_lines`: a list of strings without newlines, or `StringList`. - `input_offset`: the line offset of `input_lines` from the beginning of the file. - `context`: application-specific storage. - `input_source`: name or path of source of `input_lines`. - `initial_state`: name of initial state. """ self.runtime_init() if isinstance(input_lines, StringList): self.input_lines = input_lines else: self.input_lines = StringList(input_lines, source=input_source) self.input_offset = input_offset self.line_offset = -1 self.current_state = initial_state or self.initial_state if self.debug: print >>sys.stderr, ( '\nStateMachine.run: input_lines (line_offset=%s):\n| %s' % (self.line_offset, '\n| '.join(self.input_lines))) transitions = None results = [] state = self.get_state() try: if self.debug: print >>sys.stderr, ('\nStateMachine.run: bof transition') context, result = state.bof(context) results.extend(result) while 1: try: try: self.next_line() if self.debug: source, offset = self.input_lines.info( self.line_offset) print >>sys.stderr, ( '\nStateMachine.run: line (source=%r, ' 'offset=%r):\n| %s' % (source, offset, self.line)) context, next_state, result = self.check_line( context, state, transitions) except EOFError: if self.debug: print >>sys.stderr, ( '\nStateMachine.run: %s.eof transition' % state.__class__.__name__) result = state.eof(context) results.extend(result) break else: results.extend(result) except TransitionCorrection, exception: self.previous_line() # back up for another try transitions = (exception.args[0],) if self.debug: print >>sys.stderr, ( '\nStateMachine.run: TransitionCorrection to ' 'state "%s", transition %s.' % (state.__class__.__name__, transitions[0])) continue except StateCorrection, exception: self.previous_line() # back up for another try next_state = exception.args[0] if len(exception.args) == 1: transitions = None else: transitions = (exception.args[1],) if self.debug: print >>sys.stderr, ( '\nStateMachine.run: StateCorrection to state ' '"%s", transition %s.' % (next_state, transitions[0])) else: transitions = None state = self.get_state(next_state) except: if self.debug: self.error() raise self.observers = [] return results def get_state(self, next_state=None): """ Return current state object; set it first if `next_state` given. Parameter `next_state`: a string, the name of the next state. Exception: `UnknownStateError` raised if `next_state` unknown. """ if next_state: if self.debug and next_state != self.current_state: print >>sys.stderr, \ ('\nStateMachine.get_state: Changing state from ' '"%s" to "%s" (input line %s).' % (self.current_state, next_state, self.abs_line_number())) self.current_state = next_state try: return self.states[self.current_state] except KeyError: raise UnknownStateError(self.current_state) def next_line(self, n=1): """Load `self.line` with the `n`'th next line and return it.""" try: try: self.line_offset += n self.line = self.input_lines[self.line_offset] except IndexError: self.line = None raise EOFError return self.line finally: self.notify_observers() def is_next_line_blank(self): """Return 1 if the next line is blank or non-existant.""" try: return not self.input_lines[self.line_offset + 1].strip() except IndexError: return 1 def at_eof(self): """Return 1 if the input is at or past end-of-file.""" return self.line_offset >= len(self.input_lines) - 1 def at_bof(self): """Return 1 if the input is at or before beginning-of-file.""" return self.line_offset <= 0 def previous_line(self, n=1): """Load `self.line` with the `n`'th previous line and return it.""" self.line_offset -= n if self.line_offset < 0: self.line = None else: self.line = self.input_lines[self.line_offset] self.notify_observers() return self.line def goto_line(self, line_offset): """Jump to absolute line offset `line_offset`, load and return it.""" try: try: self.line_offset = line_offset - self.input_offset self.line = self.input_lines[self.line_offset] except IndexError: self.line = None raise EOFError return self.line finally: self.notify_observers() def get_source(self, line_offset): """Return source of line at absolute line offset `line_offset`.""" return self.input_lines.source(line_offset - self.input_offset) def abs_line_offset(self): """Return line offset of current line, from beginning of file.""" return self.line_offset + self.input_offset def abs_line_number(self): """Return line number of current line (counting from 1).""" return self.line_offset + self.input_offset + 1 def get_source_and_line(self, lineno=None): """Return (source, line) tuple for current or given line number. Looks up the source and line number in the `self.input_lines` StringList instance to count for included source files. If the optional argument `lineno` is given, convert it from an absolute line number to the corresponding (source, line) pair. """ if lineno is None: offset = self.line_offset else: offset = lineno - self.input_offset - 1 try: src, srcoffset = self.input_lines.info(offset) srcline = srcoffset + 1 except (TypeError): # line is None if index is "Just past the end" src, line = self.get_source_and_line(offset + self.input_offset) return src, line + 1 except (IndexError): # `offset` is off the list src, srcline = None, None # raise AssertionError('cannot find line %d in %s lines' % # (offset, len(self.input_lines))) # # list(self.input_lines.lines()))) # assert offset == srcoffset, str(self.input_lines) # print "get_source_and_line(%s):" % lineno, # print offset + 1, '->', src, srcline # print self.input_lines return (src, srcline) def insert_input(self, input_lines, source): self.input_lines.insert(self.line_offset + 1, '', source='internal padding after '+source, offset=len(input_lines)) self.input_lines.insert(self.line_offset + 1, '', source='internal padding before '+source, offset=-1) self.input_lines.insert(self.line_offset + 2, StringList(input_lines, source)) def get_text_block(self, flush_left=0): """ Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). """ try: block = self.input_lines.get_text_block(self.line_offset, flush_left) self.next_line(len(block) - 1) return block except UnexpectedIndentationError, error: block, source, lineno = error.args self.next_line(len(block) - 1) # advance to last line of block raise def check_line(self, context, state, transitions=None): """ Examine one line of input for a transition match & execute its method. Parameters: - `context`: application-dependent storage. - `state`: a `State` object, the current state. - `transitions`: an optional ordered list of transition names to try, instead of ``state.transition_order``. Return the values returned by the transition method: - context: possibly modified from the parameter `context`; - next state name (`State` subclass name); - the result output of the transition, a list. When there is no match, ``state.no_match()`` is called and its return value is returned. """ if transitions is None: transitions = state.transition_order state_correction = None if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: state="%s", transitions=%r.' % (state.__class__.__name__, transitions)) for name in transitions: pattern, method, next_state = state.transitions[name] match = pattern.match(self.line) if match: if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: Matched transition ' '"%s" in state "%s".' % (name, state.__class__.__name__)) return method(match, context, next_state) else: if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: No match in state "%s".' % state.__class__.__name__) return state.no_match(context, transitions) def add_state(self, state_class): """ Initialize & add a `state_class` (`State` subclass) object. Exception: `DuplicateStateError` raised if `state_class` was already added. """ statename = state_class.__name__ if statename in self.states: raise DuplicateStateError(statename) self.states[statename] = state_class(self, self.debug) def add_states(self, state_classes): """ Add `state_classes` (a list of `State` subclasses). """ for state_class in state_classes: self.add_state(state_class) def runtime_init(self): """ Initialize `self.states`. """ for state in self.states.values(): state.runtime_init() def error(self): """Report error details.""" type, value, module, line, function = _exception_data() print >>sys.stderr, '%s: %s' % (type, value) print >>sys.stderr, 'input line %s' % (self.abs_line_number()) print >>sys.stderr, ('module %s, line %s, function %s' % (module, line, function)) def attach_observer(self, observer): """ The `observer` parameter is a function or bound method which takes two arguments, the source and offset of the current line. """ self.observers.append(observer) def detach_observer(self, observer): self.observers.remove(observer) def notify_observers(self): for observer in self.observers: try: info = self.input_lines.info(self.line_offset) except IndexError: info = (None, None) observer(*info) class State: """ State superclass. Contains a list of transitions, and transition methods. Transition methods all have the same signature. They take 3 parameters: - An `re` match object. ``match.string`` contains the matched input line, ``match.start()`` gives the start index of the match, and ``match.end()`` gives the end index. - A context object, whose meaning is application-defined (initial value ``None``). It can be used to store any information required by the state machine, and the retured context is passed on to the next transition method unchanged. - The name of the next state, a string, taken from the transitions list; normally it is returned unchanged, but it may be altered by the transition method if necessary. Transition methods all return a 3-tuple: - A context object, as (potentially) modified by the transition method. - The next state name (a return value of ``None`` means no state change). - The processing result, a list, which is accumulated by the state machine. Transition methods may raise an `EOFError` to cut processing short. There are two implicit transitions, and corresponding transition methods are defined: `bof()` handles the beginning-of-file, and `eof()` handles the end-of-file. These methods have non-standard signatures and return values. `bof()` returns the initial context and results, and may be used to return a header string, or do any other processing needed. `eof()` should handle any remaining context and wrap things up; it returns the final processing result. Typical applications need only subclass `State` (or a subclass), set the `patterns` and `initial_transitions` class attributes, and provide corresponding transition methods. The default object initialization will take care of constructing the list of transitions. """ patterns = None """ {Name: pattern} mapping, used by `make_transition()`. Each pattern may be a string or a compiled `re` pattern. Override in subclasses. """ initial_transitions = None """ A list of transitions to initialize when a `State` is instantiated. Each entry is either a transition name string, or a (transition name, next state name) pair. See `make_transitions()`. Override in subclasses. """ nested_sm = None """ The `StateMachine` class for handling nested processing. If left as ``None``, `nested_sm` defaults to the class of the state's controlling state machine. Override it in subclasses to avoid the default. """ nested_sm_kwargs = None """ Keyword arguments dictionary, passed to the `nested_sm` constructor. Two keys must have entries in the dictionary: - Key 'state_classes' must be set to a list of `State` classes. - Key 'initial_state' must be set to the name of the initial state class. If `nested_sm_kwargs` is left as ``None``, 'state_classes' defaults to the class of the current state, and 'initial_state' defaults to the name of the class of the current state. Override in subclasses to avoid the defaults. """ def __init__(self, state_machine, debug=0): """ Initialize a `State` object; make & add initial transitions. Parameters: - `statemachine`: the controlling `StateMachine` object. - `debug`: a boolean; produce verbose output if true (nonzero). """ self.transition_order = [] """A list of transition names in search order.""" self.transitions = {} """ A mapping of transition names to 3-tuples containing (compiled_pattern, transition_method, next_state_name). Initialized as an instance attribute dynamically (instead of as a class attribute) because it may make forward references to patterns and methods in this or other classes. """ self.add_initial_transitions() self.state_machine = state_machine """A reference to the controlling `StateMachine` object.""" self.debug = debug """Debugging mode on/off.""" if self.nested_sm is None: self.nested_sm = self.state_machine.__class__ if self.nested_sm_kwargs is None: self.nested_sm_kwargs = {'state_classes': [self.__class__], 'initial_state': self.__class__.__name__} def runtime_init(self): """ Initialize this `State` before running the state machine; called from `self.state_machine.run()`. """ pass def unlink(self): """Remove circular references to objects no longer required.""" self.state_machine = None def add_initial_transitions(self): """Make and add transitions listed in `self.initial_transitions`.""" if self.initial_transitions: names, transitions = self.make_transitions( self.initial_transitions) self.add_transitions(names, transitions) def add_transitions(self, names, transitions): """ Add a list of transitions to the start of the transition list. Parameters: - `names`: a list of transition names. - `transitions`: a mapping of names to transition tuples. Exceptions: `DuplicateTransitionError`, `UnknownTransitionError`. """ for name in names: if name in self.transitions: raise DuplicateTransitionError(name) if name not in transitions: raise UnknownTransitionError(name) self.transition_order[:0] = names self.transitions.update(transitions) def add_transition(self, name, transition): """ Add a transition to the start of the transition list. Parameter `transition`: a ready-made transition 3-tuple. Exception: `DuplicateTransitionError`. """ if name in self.transitions: raise DuplicateTransitionError(name) self.transition_order[:0] = [name] self.transitions[name] = transition def remove_transition(self, name): """ Remove a transition by `name`. Exception: `UnknownTransitionError`. """ try: del self.transitions[name] self.transition_order.remove(name) except: raise UnknownTransitionError(name) def make_transition(self, name, next_state=None): """ Make & return a transition tuple based on `name`. This is a convenience function to simplify transition creation. Parameters: - `name`: a string, the name of the transition pattern & method. This `State` object must have a method called '`name`', and a dictionary `self.patterns` containing a key '`name`'. - `next_state`: a string, the name of the next `State` object for this transition. A value of ``None`` (or absent) implies no state change (i.e., continue with the same state). Exceptions: `TransitionPatternNotFound`, `TransitionMethodNotFound`. """ if next_state is None: next_state = self.__class__.__name__ try: pattern = self.patterns[name] if not hasattr(pattern, 'match'): pattern = re.compile(pattern) except KeyError: raise TransitionPatternNotFound( '%s.patterns[%r]' % (self.__class__.__name__, name)) try: method = getattr(self, name) except AttributeError: raise TransitionMethodNotFound( '%s.%s' % (self.__class__.__name__, name)) return (pattern, method, next_state) def make_transitions(self, name_list): """ Return a list of transition names and a transition mapping. Parameter `name_list`: a list, where each entry is either a transition name string, or a 1- or 2-tuple (transition name, optional next state name). """ stringtype = type('') names = [] transitions = {} for namestate in name_list: if type(namestate) is stringtype: transitions[namestate] = self.make_transition(namestate) names.append(namestate) else: transitions[namestate[0]] = self.make_transition(*namestate) names.append(namestate[0]) return names, transitions def no_match(self, context, transitions): """ Called when there is no match from `StateMachine.check_line()`. Return the same values returned by transition methods: - context: unchanged; - next state name: ``None``; - empty result list. Override in subclasses to catch this event. """ return context, None, [] def bof(self, context): """ Handle beginning-of-file. Return unchanged `context`, empty result. Override in subclasses. Parameter `context`: application-defined storage. """ return context, [] def eof(self, context): """ Handle end-of-file. Return empty result. Override in subclasses. Parameter `context`: application-defined storage. """ return [] def nop(self, match, context, next_state): """ A "do nothing" transition method. Return unchanged `context` & `next_state`, empty result. Useful for simple state changes (actionless transitions). """ return context, next_state, [] class StateMachineWS(StateMachine): """ `StateMachine` subclass specialized for whitespace recognition. There are three methods provided for extracting indented text blocks: - `get_indented()`: use when the indent is unknown. - `get_known_indented()`: use when the indent is known for all lines. - `get_first_known_indented()`: use when only the first line's indent is known. """ def get_indented(self, until_blank=0, strip_indent=1): """ Return a block of indented lines of text, and info. Extract an indented block where the indent is unknown for all lines. :Parameters: - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip common leading indent if true (1, default). :Return: - the indented block (a list of lines of text), - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent) if indented: self.next_line(len(indented) - 1) # advance to last indented line while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, indent, offset, blank_finish def get_known_indented(self, indent, until_blank=0, strip_indent=1): """ Return an indented block and info. Extract an indented block where the indent is known for all lines. Starting with the current line, extract the entire text block with at least `indent` indentation (which must be whitespace, except for the first line). :Parameters: - `indent`: The number of indent columns/characters. - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). :Return: - the indented block, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent, block_indent=indent) self.next_line(len(indented) - 1) # advance to last indented line while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, offset, blank_finish def get_first_known_indented(self, indent, until_blank=0, strip_indent=1, strip_top=1): """ Return an indented block and info. Extract an indented block where the indent is known for the first line and unknown for all other lines. :Parameters: - `indent`: The first line's indent (# of columns/characters). - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). - `strip_top`: Strip blank lines from the beginning of the block. :Return: - the indented block, - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent, first_indent=indent) self.next_line(len(indented) - 1) # advance to last indented line if strip_top: while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, indent, offset, blank_finish class StateWS(State): """ State superclass specialized for whitespace (blank lines & indents). Use this class with `StateMachineWS`. The transitions 'blank' (for blank lines) and 'indent' (for indented text blocks) are added automatically, before any other transitions. The transition method `blank()` handles blank lines and `indent()` handles nested indented blocks. Indented blocks trigger a new state machine to be created by `indent()` and run. The class of the state machine to be created is in `indent_sm`, and the constructor keyword arguments are in the dictionary `indent_sm_kwargs`. The methods `known_indent()` and `firstknown_indent()` are provided for indented blocks where the indent (all lines' and first line's only, respectively) is known to the transition method, along with the attributes `known_indent_sm` and `known_indent_sm_kwargs`. Neither transition method is triggered automatically. """ indent_sm = None """ The `StateMachine` class handling indented text blocks. If left as ``None``, `indent_sm` defaults to the value of `State.nested_sm`. Override it in subclasses to avoid the default. """ indent_sm_kwargs = None """ Keyword arguments dictionary, passed to the `indent_sm` constructor. If left as ``None``, `indent_sm_kwargs` defaults to the value of `State.nested_sm_kwargs`. Override it in subclasses to avoid the default. """ known_indent_sm = None """ The `StateMachine` class handling known-indented text blocks. If left as ``None``, `known_indent_sm` defaults to the value of `indent_sm`. Override it in subclasses to avoid the default. """ known_indent_sm_kwargs = None """ Keyword arguments dictionary, passed to the `known_indent_sm` constructor. If left as ``None``, `known_indent_sm_kwargs` defaults to the value of `indent_sm_kwargs`. Override it in subclasses to avoid the default. """ ws_patterns = {'blank': ' *$', 'indent': ' +'} """Patterns for default whitespace transitions. May be overridden in subclasses.""" ws_initial_transitions = ('blank', 'indent') """Default initial whitespace transitions, added before those listed in `State.initial_transitions`. May be overridden in subclasses.""" def __init__(self, state_machine, debug=0): """ Initialize a `StateSM` object; extends `State.__init__()`. Check for indent state machine attributes, set defaults if not set. """ State.__init__(self, state_machine, debug) if self.indent_sm is None: self.indent_sm = self.nested_sm if self.indent_sm_kwargs is None: self.indent_sm_kwargs = self.nested_sm_kwargs if self.known_indent_sm is None: self.known_indent_sm = self.indent_sm if self.known_indent_sm_kwargs is None: self.known_indent_sm_kwargs = self.indent_sm_kwargs def add_initial_transitions(self): """ Add whitespace-specific transitions before those defined in subclass. Extends `State.add_initial_transitions()`. """ State.add_initial_transitions(self) if self.patterns is None: self.patterns = {} self.patterns.update(self.ws_patterns) names, transitions = self.make_transitions( self.ws_initial_transitions) self.add_transitions(names, transitions) def blank(self, match, context, next_state): """Handle blank lines. Does nothing. Override in subclasses.""" return self.nop(match, context, next_state) def indent(self, match, context, next_state): """ Handle an indented text block. Extend or override in subclasses. Recursively run the registered state machine for indented blocks (`self.indent_sm`). """ indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() sm = self.indent_sm(debug=self.debug, **self.indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results def known_indent(self, match, context, next_state): """ Handle a known-indent text block. Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. """ indented, line_offset, blank_finish = \ self.state_machine.get_known_indented(match.end()) sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results def first_known_indent(self, match, context, next_state): """ Handle an indented text block (first line's indent known). Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. """ indented, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results class _SearchOverride: """ Mix-in class to override `StateMachine` regular expression behavior. Changes regular expression matching, from the default `re.match()` (succeeds only if the pattern matches at the start of `self.line`) to `re.search()` (succeeds if the pattern matches anywhere in `self.line`). When subclassing a `StateMachine`, list this class **first** in the inheritance list of the class definition. """ def match(self, pattern): """ Return the result of a regular expression search. Overrides `StateMachine.match()`. Parameter `pattern`: `re` compiled regular expression. """ return pattern.search(self.line) class SearchStateMachine(_SearchOverride, StateMachine): """`StateMachine` which uses `re.search()` instead of `re.match()`.""" pass class SearchStateMachineWS(_SearchOverride, StateMachineWS): """`StateMachineWS` which uses `re.search()` instead of `re.match()`.""" pass class ViewList: """ List with extended functionality: slices of ViewList objects are child lists, linked to their parents. Changes made to a child list also affect the parent list. A child list is effectively a "view" (in the SQL sense) of the parent list. Changes to parent lists, however, do *not* affect active child lists. If a parent list is changed, any active child lists should be recreated. The start and end of the slice can be trimmed using the `trim_start()` and `trim_end()` methods, without affecting the parent list. The link between child and parent lists can be broken by calling `disconnect()` on the child list. Also, ViewList objects keep track of the source & offset of each item. This information is accessible via the `source()`, `offset()`, and `info()` methods. """ def __init__(self, initlist=None, source=None, items=None, parent=None, parent_offset=None): self.data = [] """The actual list of data, flattened from various sources.""" self.items = [] """A list of (source, offset) pairs, same length as `self.data`: the source of each line and the offset of each line from the beginning of its source.""" self.parent = parent """The parent list.""" self.parent_offset = parent_offset """Offset of this list from the beginning of the parent list.""" if isinstance(initlist, ViewList): self.data = initlist.data[:] self.items = initlist.items[:] elif initlist is not None: self.data = list(initlist) if items: self.items = items else: self.items = [(source, i) for i in range(len(initlist))] assert len(self.data) == len(self.items), 'data mismatch' def __str__(self): return str(self.data) def __repr__(self): return '%s(%s, items=%s)' % (self.__class__.__name__, self.data, self.items) def __lt__(self, other): return self.data < self.__cast(other) def __le__(self, other): return self.data <= self.__cast(other) def __eq__(self, other): return self.data == self.__cast(other) def __ne__(self, other): return self.data != self.__cast(other) def __gt__(self, other): return self.data > self.__cast(other) def __ge__(self, other): return self.data >= self.__cast(other) def __cmp__(self, other): return cmp(self.data, self.__cast(other)) def __cast(self, other): if isinstance(other, ViewList): return other.data else: return other def __contains__(self, item): return item in self.data def __len__(self): return len(self.data) # The __getitem__()/__setitem__() methods check whether the index # is a slice first, since indexing a native list with a slice object # just works. def __getitem__(self, i): if isinstance(i, types.SliceType): assert i.step in (None, 1), 'cannot handle slice with stride' return self.__class__(self.data[i.start:i.stop], items=self.items[i.start:i.stop], parent=self, parent_offset=i.start or 0) else: return self.data[i] def __setitem__(self, i, item): if isinstance(i, types.SliceType): assert i.step in (None, 1), 'cannot handle slice with stride' if not isinstance(item, ViewList): raise TypeError('assigning non-ViewList to ViewList slice') self.data[i.start:i.stop] = item.data self.items[i.start:i.stop] = item.items assert len(self.data) == len(self.items), 'data mismatch' if self.parent: self.parent[(i.start or 0) + self.parent_offset : (i.stop or len(self)) + self.parent_offset] = item else: self.data[i] = item if self.parent: self.parent[i + self.parent_offset] = item def __delitem__(self, i): try: del self.data[i] del self.items[i] if self.parent: del self.parent[i + self.parent_offset] except TypeError: assert i.step is None, 'cannot handle slice with stride' del self.data[i.start:i.stop] del self.items[i.start:i.stop] if self.parent: del self.parent[(i.start or 0) + self.parent_offset : (i.stop or len(self)) + self.parent_offset] def __add__(self, other): if isinstance(other, ViewList): return self.__class__(self.data + other.data, items=(self.items + other.items)) else: raise TypeError('adding non-ViewList to a ViewList') def __radd__(self, other): if isinstance(other, ViewList): return self.__class__(other.data + self.data, items=(other.items + self.items)) else: raise TypeError('adding ViewList to a non-ViewList') def __iadd__(self, other): if isinstance(other, ViewList): self.data += other.data else: raise TypeError('argument to += must be a ViewList') return self def __mul__(self, n): return self.__class__(self.data * n, items=(self.items * n)) __rmul__ = __mul__ def __imul__(self, n): self.data *= n self.items *= n return self def extend(self, other): if not isinstance(other, ViewList): raise TypeError('extending a ViewList with a non-ViewList') if self.parent: self.parent.insert(len(self.data) + self.parent_offset, other) self.data.extend(other.data) self.items.extend(other.items) def append(self, item, source=None, offset=0): if source is None: self.extend(item) else: if self.parent: self.parent.insert(len(self.data) + self.parent_offset, item, source, offset) self.data.append(item) self.items.append((source, offset)) def insert(self, i, item, source=None, offset=0): if source is None: if not isinstance(item, ViewList): raise TypeError('inserting non-ViewList with no source given') self.data[i:i] = item.data self.items[i:i] = item.items if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.insert(index + self.parent_offset, item) else: self.data.insert(i, item) self.items.insert(i, (source, offset)) if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.insert(index + self.parent_offset, item, source, offset) def pop(self, i=-1): if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.pop(index + self.parent_offset) self.items.pop(i) return self.data.pop(i) def trim_start(self, n=1): """ Remove items from the start of the list, without touching the parent. """ if n > len(self.data): raise IndexError("Size of trim too large; can't trim %s items " "from a list of size %s." % (n, len(self.data))) elif n < 0: raise IndexError('Trim size must be >= 0.') del self.data[:n] del self.items[:n] if self.parent: self.parent_offset += n def trim_end(self, n=1): """ Remove items from the end of the list, without touching the parent. """ if n > len(self.data): raise IndexError("Size of trim too large; can't trim %s items " "from a list of size %s." % (n, len(self.data))) elif n < 0: raise IndexError('Trim size must be >= 0.') del self.data[-n:] del self.items[-n:] def remove(self, item): index = self.index(item) del self[index] def count(self, item): return self.data.count(item) def index(self, item): return self.data.index(item) def reverse(self): self.data.reverse() self.items.reverse() self.parent = None def sort(self, *args): tmp = zip(self.data, self.items) tmp.sort(*args) self.data = [entry[0] for entry in tmp] self.items = [entry[1] for entry in tmp] self.parent = None def info(self, i): """Return source & offset for index `i`.""" try: return self.items[i] except IndexError: if i == len(self.data): # Just past the end return self.items[i - 1][0], None else: raise def source(self, i): """Return source for index `i`.""" return self.info(i)[0] def offset(self, i): """Return offset for index `i`.""" return self.info(i)[1] def disconnect(self): """Break link between this list and parent list.""" self.parent = None def xitems(self): """Return iterator yielding (source, offset, value) tuples.""" for (value, (source, offset)) in zip(self.data, self.items): yield (source, offset, value) def pprint(self): """Print the list in `grep` format (`source:offset:value` lines)""" for line in self.xitems(): print "%s:%d:%s" % line class StringList(ViewList): """A `ViewList` with string-specific methods.""" def trim_left(self, length, start=0, end=sys.maxint): """ Trim `length` characters off the beginning of each item, in-place, from index `start` to `end`. No whitespace-checking is done on the trimmed text. Does not affect slice parent. """ self.data[start:end] = [line[length:] for line in self.data[start:end]] def get_text_block(self, start, flush_left=0): """ Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). """ end = start last = len(self.data) while end < last: line = self.data[end] if not line.strip(): break if flush_left and (line[0] == ' '): source, offset = self.info(end) raise UnexpectedIndentationError(self[start:end], source, offset + 1) end += 1 return self[start:end] def get_indented(self, start=0, until_blank=0, strip_indent=1, block_indent=None, first_indent=None): """ Extract and return a StringList of indented lines of text. Collect all lines with indentation, determine the minimum indentation, remove the minimum indentation from all indented lines (unless `strip_indent` is false), and return them. All lines up to but not including the first unindented line will be returned. :Parameters: - `start`: The index of the first line to examine. - `until_blank`: Stop collecting at the first blank line if true. - `strip_indent`: Strip common leading indent if true (default). - `block_indent`: The indent of the entire block, if known. - `first_indent`: The indent of the first line, if known. :Return: - a StringList of indented lines with mininum indent removed; - the amount of the indent; - a boolean: did the indented block finish with a blank line or EOF? """ indent = block_indent # start with None if unknown end = start if block_indent is not None and first_indent is None: first_indent = block_indent if first_indent is not None: end += 1 last = len(self.data) while end < last: line = self.data[end] if line and (line[0] != ' ' or (block_indent is not None and line[:block_indent].strip())): # Line not indented or insufficiently indented. # Block finished properly iff the last indented line blank: blank_finish = ((end > start) and not self.data[end - 1].strip()) break stripped = line.lstrip() if not stripped: # blank line if until_blank: blank_finish = 1 break elif block_indent is None: line_indent = len(line) - len(stripped) if indent is None: indent = line_indent else: indent = min(indent, line_indent) end += 1 else: blank_finish = 1 # block ends at end of lines block = self[start:end] if first_indent is not None and block: block.data[0] = block.data[0][first_indent:] if indent and strip_indent: block.trim_left(indent, start=(first_indent is not None)) return block, indent or 0, blank_finish def get_2D_block(self, top, left, bottom, right, strip_indent=1): block = self[top:bottom] indent = right for i in range(len(block.data)): block.data[i] = line = block.data[i][left:right].rstrip() if line: indent = min(indent, len(line) - len(line.lstrip())) if strip_indent and 0 < indent < right: block.data = [line[indent:] for line in block.data] return block def pad_double_width(self, pad_char): """ Pad all double-width characters in self by appending `pad_char` to each. For East Asian language support. """ if hasattr(unicodedata, 'east_asian_width'): east_asian_width = unicodedata.east_asian_width else: return # new in Python 2.4 for i in range(len(self.data)): line = self.data[i] if isinstance(line, unicode): new = [] for char in line: new.append(char) if east_asian_width(char) in 'WF': # 'W'ide & 'F'ull-width new.append(pad_char) self.data[i] = ''.join(new) def replace(self, old, new): """Replace all occurrences of substring `old` with `new`.""" for i in range(len(self.data)): self.data[i] = self.data[i].replace(old, new) class StateMachineError(Exception): pass class UnknownStateError(StateMachineError): pass class DuplicateStateError(StateMachineError): pass class UnknownTransitionError(StateMachineError): pass class DuplicateTransitionError(StateMachineError): pass class TransitionPatternNotFound(StateMachineError): pass class TransitionMethodNotFound(StateMachineError): pass class UnexpectedIndentationError(StateMachineError): pass class TransitionCorrection(Exception): """ Raise from within a transition method to switch to another transition. Raise with one argument, the new transition name. """ class StateCorrection(Exception): """ Raise from within a transition method to switch to another state. Raise with one or two arguments: new state name, and an optional new transition name. """ def string2lines(astring, tab_width=8, convert_whitespace=0, whitespace=re.compile('[\v\f]')): """ Return a list of one-line strings with tabs expanded, no newlines, and trailing whitespace stripped. Each tab is expanded with between 1 and `tab_width` spaces, so that the next character's index becomes a multiple of `tab_width` (8 by default). Parameters: - `astring`: a multi-line string. - `tab_width`: the number of columns between tab stops. - `convert_whitespace`: convert form feeds and vertical tabs to spaces? """ if convert_whitespace: astring = whitespace.sub(' ', astring) return [s.expandtabs(tab_width).rstrip() for s in astring.splitlines()] def _exception_data(): """ Return exception information: - the exception's class name; - the exception object; - the name of the file containing the offending code; - the line number of the offending code; - the function name of the offending code. """ type, value, traceback = sys.exc_info() while traceback.tb_next: traceback = traceback.tb_next code = traceback.tb_frame.f_code return (type.__name__, value, code.co_filename, traceback.tb_lineno, code.co_name)
Python
from functools import wraps from inspect import isfunction from google.appengine.api import users from common import FreeRealmsRequestHandler, QUOTED_GROUP import model def campaign_handler(*args, **kwargs): def decorator(func): @wraps(func) def wrapper(self, campaign, *args): campaign = model.Campaign.get_by_quoted(campaign) if not campaign: self.error(404) return if kwargs.get('gm_only') and not campaign.is_gamemaster(): self.redirect(users.create_login_url(self.request.uri)) return return func(self, campaign, *args) return wrapper if args: return decorator(args[0]) else: return decorator class CampaignPage(FreeRealmsRequestHandler): url = r'/campaign/%s/' % QUOTED_GROUP template = 'campaign.html' @campaign_handler def get(self, campaign): self.render(campaign=campaign) class DescriptionPage(FreeRealmsRequestHandler): url = r'/campaigns/%s/description' % QUOTED_GROUP template = 'description.html' @campaign_handler def get(self, campaign): self.render(campaign=campaign) class NewPage(FreeRealmsRequestHandler): url = r'/campaigns/%s/new' % QUOTED_GROUP template = '???' @campaign_handler def get(self, campaign): user = users.get_current_user() if not user or not campaign.can_post(user): self.redirect(users.create_login_url(self.request.uri)) self.render(campaign=campaign) class ApplicationPage(FreeRealmsRequestHandler): url = r'/campaigns/%s/application' % QUOTED_GROUP template = 'application.html' @campaign_handler def get(self, campaign): if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri)) form = self.form_data() application = campaign.application() message = self.request.get('message', application.message if application else '') self.render(campaign=campaign, message=message) @campaign_handler def post(self, campaign): action = self.request.get('action', 'apply') message = self.request.get('message') try: if action == 'apply': campaign.create_application(message) else: campaign.delete_application() self.relative_redirect('/') except ClientError, e: self.render(campaign=campaign, message=message, error_msg=e.msg) class ApplicationsPage(FreeRealmsRequestHandler): url = r'/campaigns/%s/applications' % QUOTED_GROUP template = 'applications.html' @campaign_handler(gm_only=True) def get(self, campaign): self.render(campaign=campaign, applications=campaign.applications()) @campaign_handler def post(self, campaign): if not campaign.is_gamemaster(): self.redirect(users.create_login_url(self.request.uri)) return accept = self.request.get('accept') reject = self.request.get('reject') user_id = accept or reject if user_id: application = campaign.application(user_id) if accept and application: campaign.create_player(application.user) application.delete() if reject and application: application.delete() self.render(campaign=campaign, applications=applications) class PlayersPage(FreeRealmsRequestHandler): url = r'/campaigns/%s/players' % QUOTED_GROUP template = 'players.html' @campaign_handler def get(self, campaign): if not campaign.is_gamemaster(): self.redirect(users.create_login_url(self.request.uri)) return players = campaign.players() self.render(campaign=campaign, players=players) @campaign_handler def post(self, campaign): if not campaign.is_gamemaster(): self.redirect(users.create_login_url(self.request.uri)) return handover = self.request.get('handover') user_id = handover if user_id: player = campaign.player(user_id) if player and handover: character = self.request.get('character') if not character in player.characters: player.characters.append(character) player.put() self.render(campaign=campaign, players=players) class CharactersPage(FreeRealmsRequestHandler): url = r'/campaigns/%s/characters/' % QUOTED_GROUP template = 'characters.html' @campaign_handler def get(self, campaign): if not campaign.is_gamemaster(): self.redirect(users.create_login_url(self.request.uri)) return self.render(campaign=campaign, characters=campaign.characters()) @campaign_handler def post(self, campaign): if not campaign.is_gamemaster(): self.redirect(users.create_login_url(self.request.uri)) return character = self.request.get('remove') if character: campaign.delete_character(character) self.render(campaign=campaign, characters=campaign.characters()) class AddCharacterPage(FreeRealmsRequestHandler): url = r'/campaigns/%s/characters/add' % QUOTED_GROUP template = 'add_character.html' @campaign_handler def get(self, campaign): if not campaign.is_gamemaster(): self.redirect(users.create_login_url(self.request.uri)) return self.render(campaign=campaign) @campaign_handler def post(self, campaign): if not campaign.is_gamemaster(): self.redirect(users.create_login_url(self.request.uri)) return name = self.request.get('name') short_desc = self.request.get('short_desc') description = self.request.get('description') try: campaign.create_character(name, short_desc, description) self.relative_redirect(campaign.url + 'characters/') except ClientError, e: self.render( campaign=campaign, name=name, short_desc=short_desc, description=description, error_msg=e.msg) class CharacterPage(FreeRealmsRequestHandler): url = r'/campaigns/%s/characters/%s/' % (QUOTED_GROUP, QUOTED_GROUP) template = 'character.html' def get(self, campaign, character): campaign = model.Campaign.get_by_quoted(campaign)
Python
# See: http://code.google.com/appengine/articles/sharding_counters.html from google.appengine.api import memcache from google.appengine.ext import db import random class GeneralCounterShardConfig(db.Model): """Tracks the number of shards for each named counter.""" name = db.StringProperty(required=True) num_shards = db.IntegerProperty(required=True, default=20) class GeneralCounterShard(db.Model): """Shards for each named counter""" name = db.StringProperty(required=True) count = db.IntegerProperty(required=True, default=0) def get_count(name): """Retrieve the value for a given sharded counter. Parameters: name - The name of the counter """ total = memcache.get(name) if total is None: total = 0 for counter in GeneralCounterShard.all().filter('name = ', name): total += counter.count memcache.add(name, str(total), 60) return total def increment(name): """Increment the value for a given sharded counter. Parameters: name - The name of the counter """ config = GeneralCounterShardConfig.get_or_insert(name, name=name) def txn(): index = random.randint(0, config.num_shards - 1) shard_name = name + str(index) counter = GeneralCounterShard.get_by_key_name(shard_name) if counter is None: counter = GeneralCounterShard(key_name=shard_name, name=name) counter.count += 1 counter.put() db.run_in_transaction(txn) memcache.incr(name, initial_value=0) def increase_shards(name, num): """Increase the number of shards for a given sharded counter. Will never decrease the number of shards. Parameters: name - The name of the counter num - How many shards to use """ config = GeneralCounterShardConfig.get_or_insert(name, name=name) def txn(): if config.num_shards < num: config.num_shards = num config.put() db.run_in_transaction(txn)
Python
def webapp_add_wsgi_middleware(app): from google.appengine.ext.appstats import recording app = recording.appstats_wsgi_middleware(app) return app
Python
import urllib from google.appengine.dist import use_library use_library('django', '1.2') #os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' #from django.conf import settings #settings._targets = None from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp import template from common import FreeRealmsRequestHandler, wsgi_application import counter from error import ClientError import model import campaign template.register_template_library('common.templatefilters') class MainPage(FreeRealmsRequestHandler): url = r'/' template = 'index.html' def get(self): campaign_count = counter.get_count('campaigns') keywords = request.get('keywords') self.render( campaign_count=campaign_count, applications=model.Application.find(), campaigns=model.Campaign.find(keywords)) class AddPage(FreeRealmsRequestHandler): url = r'/add' template = 'add.html' def get(self): if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri)) self.render() def post(self): name = request.get('name') system = request.get('system', 'Unspecified') description = request.get('description') try: campaign = model.Campaign.create(name, description, system) self.relative_redirect(campaign.url) except ClientError, e: self.render( name=name, system=system, description=description, error_msg=e.msg) application = wsgi_application(debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
Python
import urllib from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext.db import BadKeyError import counter from common import ComputedProperty, generate_keywords from error import ClientError class Campaign(db.Model): description = db.TextProperty() system = db.StringProperty() gamemasters = db.ListProperty(users.User) created = db.DateTimeProperty(auto_now_add=True) modified = db.DateTimeProperty(auto_now=True) new_applications = db.BooleanProperty(default=False) @ComputedProperty def keywords(model_instance): value = [] value.extend(generate_keywords(model_instance.key().name())) value.extend(generate_keywords(model_instance.system)) for user in model_instance.gamemasters: value.extend(generate_keywords(user.nickname())) return value @property def name(self): return self.key().name() def __str__(self): return self.name @classmethod def get_by_quoted(cls, campaign): return cls.get_by_key_name(urllib.unquote(campaign)) def can_post(self): try: user = users.User() except users.UserNotFoundError: return False if user in self.gamemasters: return True q = Player.all() q.anchestor(self) q.filter('__key__ =', user.user_id()) return q.get() def is_gamemaster(self): try: return users.User() in self.gamemasters except users.UserNotFoundError: return False @property def url(self): return '/campaigns/%s/' % urllib.quote(self.name, '') @classmethod def find(cls, keywords): q = cls.all() for word in keywords.split(): q.filter('keywords =', word.lower()) q.order('-modified') q.order('__key__') return q.fetch(20) @classmethod def create(name, description, system): user = users.get_current_user() if not user: raise ClientError( u"Not logged in. Please log in before you proceed.") try: campaign = cls( key_name=name, description=description, system=system, gamemasters=[user]) except BadKeyError: raise ClientError( u"'%s' is not a suitable campaign name." % name if name else u"Campaign name missing. Please fill in a campaign name.") def txn(): if Campaign.get_by_key_name(name): raise ClientError( u"There exists already a campaign by the name '%s'." % name) campaign.put() db.run_in_transaction(txn) counter.increment('campaigns') return campaign def create_application(self, message): try: application = Application( parent=self, key_name=users.User().user_id(), message=message) except users.UserNotFoundError: raise ClientError( u"Not logged in. Please log in before you proceed.") application.put() self.new_applications = True self.put() return application def create_player(self, user): player = Player(parent=self, key_name=user.user_id(), user=user) player.put() return player def application(self, user_id=None): if not user_id: user_id = users.User().user_id() return Application.get_by_key_name(user_id, parent=self) def delete_application(self): application = self.application() if application: application.delete() def applications(self): self.new_applications = False self.put() q = Application.all() q.ancestor(self) q.order('-modified') q.order('user') return q.fetch(20) def player(self, user_id=None): if not user_id: user_id = users.User().user_id() return Player.get_by_key_name(user_id, parent=self) def players(self): q = Player.all() q.ancestor(self) q.order('user') return q.fetch(20) def create_character(self, name, short_desc, description): try: character = Character( parent=self, key_name=name, short_desc=short_desc, description=description) except BadKeyError: raise ClientError( u"'%s' is not a suitable character name." % name if name else u"Character name missing. Please fill in a character name.") character.put() return character def get_character(self, name): return Character.get_by_key_name(name, parent=self) def delete_character(self, name): character = self.get_character(name) if character: character.delete() def characters(self): q = Character.all() q.ancestor(self) q.order('__key__') return q.fetch(20) class Application(db.Model): modified = db.DateTimeProperty(auto_now=True) user = db.UserProperty(auto_current_user_add=True) message = db.TextProperty() @property def user_id(self): return self.key().name() @property def campaign(self): return self.parent() @classmethod def find(cls): try: q = cls.all() q.filter('user =', users.User()) q.order('-modified') q.order('__key__') return q.fetch(20) except users.UserNotFoundError: return None class Player(db.Model): user = db.UserProperty() characters = db.StringListProperty() @property def user_id(self): return self.key().name() @property def campaign(self): return self.parent() def __str__(self): return self.user.nickname() def non_characters(self): campaign_key = self.parent_key() q = Character.all() q.ancestor(campaign_key) q.order('__key__') result = q.fetch(20) return [character for character in result if character.name not in self.characters] class Character(db.Model): short_desc = db.StringProperty(required=True) description = db.TextProperty() @property def campaign(self): return self.parent() @property def name(self): return self.key().name() def __str__(self): return self.name def players(self): q = Player.all() q.ancestor(self.parent_key()) q.filter('characters =', self.name) q.order('user') return q.fetch(20) class Post(db.Model): @property def version(self): return int(self.key.name)
Python
class Error(Exception): """Base class for exceptions in this application.""" class ClientError(Error): """Raised when an operation fails due to invalid input data.""" def __init__(self, msg): self.msg = msg
Python
import urllib from docutils.core import publish_parts from google.appengine.ext.webapp import template from django.utils.safestring import mark_safe from django.utils.encoding import smart_str, force_unicode register = template.create_template_register() # XXX: We don't need this if we implement an url instance method for the models. @register.filter def urlquote(value): return urllib.quote(value, '') @register.filter def restructuredtext(value): parts = publish_parts(source=smart_str(value), writer_name="html4css1", settings_overrides={ 'initial_header_level': 3, 'doctitle_xform': False, '_disable_config': True }) return mark_safe(force_unicode(parts["fragment"])) restructuredtext.is_safe = True
Python
import os from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from _common import root_path QUOTED_GROUP = r'([a-zA-Z0-9_\.\-%]+)' class ComputedProperty(db.Property): data_type = None def __init__(self, derive_func, *args, **kwargs): """Constructor. Args: derive_func: A function that takes on argument, the model isntance, and returns a calculated value. """ super(ComputedProperty, self).__init__(*args, **kwargs) self.__derive_func = derive_func def get_value_for_datastore(self, model_instance): return self.__derive_func(model_instance) def generate_keywords(string): return (word.lower() for word in string.split()) _url_mapping = [] def wsgi_application(debug=False): return webapp.WSGIApplication(_url_mapping, debug) class MetaFreeRealmsRequestHandler(type): def __init__(cls, name, bases, dct): try: _url_mapping.append((cls.url, cls)) except AttributeError: pass class UserInfo(object): def __init__(self, request): user = users.get_current_user() if user: self.nickname = user.nickname() self.url = users.create_logout_url(request.uri) else: self.url = users.create_login_url(request.uri) class FreeRealmsRequestHandler(webapp.RequestHandler): __metaclass__ = MetaFreeRealmsRequestHandler def render(self, **template_values): path = os.path.join(root_path, 'templates', self.template) template_values.setdefault('user', UserInfo(self.request)) self.response.out.write(template.render(path, template_values)) def relative_redirect(self, url): self.redirect(self.request.relative_url(url, to_application=True))
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of kothic, the realtime map renderer. # kothic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # kothic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with kothic. If not, see <http://www.gnu.org/licenses/>. class Rule(): def __init__(self, s=''): self.conditions = [] self.isAnd = True self.minZoom = 0 self.maxZoom = 19 self.subject = s # "", "way", "node" or "relation" def __repr__(self): return "%s|z%s-%s %s"%(self.subject,self.minZoom,self.maxZoom, self.conditions) #public function test(obj:Entity,tags:Object):Boolean { def test(self, obj, tags, zoom): if (self.subject!='') and not _test_feature_compatibility(obj, self.subject, tags): return False #print _test_feature_compatibility(obj, self.subject, tags), obj, self.subject if not self.test_zoom(zoom): return False v="a" for condition in self.conditions: r = condition.test(tags) if v=="a": v = r elif self.isAnd: v = v & r else: v = v | r return v def test_zoom(self, zoom): return (zoom >= self.minZoom) and (zoom <= self.maxZoom) def get_interesting_tags(self, obj, zoom): if obj: if (self.subject!='') and not _test_feature_compatibility(obj, self.subject, {}): return set() if not self.test_zoom(zoom): return set() a = set() for condition in self.conditions: a.update(condition.get_interesting_tags()) return a def get_numerics(self): a = set() for condition in self.conditions: a.add(condition.get_numerics()) a.discard(False) return a def get_sql_hints(self, obj, zoom): if obj: if (self.subject!='') and not _test_feature_compatibility(obj, self.subject, {":area":"yes"}): return set() if not self.test_zoom(zoom): return set() a = set() b = set() for condition in self.conditions: q = condition.get_sql() if q: if q[1]: a.add(q[0]) b.add(q[1]) b = " AND ".join(b) return a,b def _test_feature_compatibility (f1, f2, tags={}): """ Checks if feature of type f1 is compatible with f2. """ if f2 == f1: return True elif f2 == "way" and f1 == "line": return True elif f2 == "way" and f1 == "area": return True elif f2 == "area" and f1 in ("way", "area", "POLYGON"): if ":area" in tags: pass else: return False elif f2 == "line" and f1 in ("way", "line", "LINESTRING"): pass elif f2 == "point" and f1 in ("node", "POINT"): pass else: return False #print f1, f2, True return True
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of kothic, the realtime map renderer. # kothic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # kothic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with kothic. If not, see <http://www.gnu.org/licenses/>. import re INVERSIONS = {"eq":"ne", "true":"false", "set":"unset", "<":">=", ">":"<="} in2 = {} for a,b in INVERSIONS.iteritems(): in2[b] = a INVERSIONS.update(in2) del in2 class Condition: def __init__(self, typez, params): self.type=typez # eq, regex, lt, gt etc. if type(params) == type(str()): params = (params,) self.params=params # e.g. ('highway','primary') if typez == "regex": self.regex = re.compile(self.params[0], re.I) self.compiled_regex = "" def get_interesting_tags(self): if self.params[0][:2] == "::": return [] return set([self.params[0]]) def get_numerics(self): if self.type in ("<", ">", ">=", "<="): return self.params[0] else: return False def test(self, tags): """ Test a hash against this condition """ t = self.type params = self.params if t == 'eq': # don't compare tags against sublayers if params[0][:2] == "::": return True try: if t == 'eq': return tags[params[0]]==params[1] if t == 'ne': return tags.get(params[0], "")!=params[1] if t == 'regex': return bool(self.regex.match(tags[params[0]])) if t == 'true': return (tags[params[0]]=='true') | (tags[params[0]]=='yes') | (tags[params[0]]=='1') if t == 'false': return (tags.get(params[0], "")=='false') | (tags.get(params[0], "")=='no') | (tags.get(params[0], "")=='') if t == 'set': if params[0] in tags: return tags[params[0]]!='' return False if t == 'unset': if params[0] in tags: return tags[params[0]]=='' return True if t == '<': return (Number(tags[params[0]])< Number(params[1])) if t == '<=': return (Number(tags[params[0]])<=Number(params[1])) if t == '>': return (Number(tags[params[0]])> Number(params[1])) if t == '>=': return (Number(tags[params[0]])>=Number(params[1])) except KeyError: pass return False; def inverse(self): """ Get a not-A for condition A """ t = self.type params = self.params try: return Condition(INVERSIONS[t], params) if t == 'regex': ### FIXME: learn how to invert regexes return Condition("regex", params) except KeyError: pass return self; def get_sql(self): #params = [re.escape(x) for x in self.params] params = self.params t = self.type if t == 'eq': # don't compare tags against sublayers if params[0][:2] == "::": return ("","") try: if t == 'eq': return params[0], '"%s" = \'%s\''%(params[0], params[1]) if t == 'ne': return params[0], '("%s" != \'%s\' or "%s" IS NULL)'%(params[0], params[1],params[0]) if t == 'regex': return params[0], '"%s" ~ \'%s\''%(params[0],params[1].replace("'","\\'")) if t == 'true': return params[0], '"%s" IN (\'true\', \'yes\', \'1\')'%(params[0]) if t == 'untrue': return params[0], '"%s" NOT IN (\'true\', \'yes\', \'1\')'%(params[0]) if t == 'set': return params[0], '"%s" IS NOT NULL'%(params[0]) if t == 'unset': return params[0], '"%s" IS NULL'%(params[0]) if t == '<': return params[0], """(CASE WHEN "%s" ~ E'^[-]?[[:digit:]]+([.][[:digit:]]+)?$' THEN CAST ("%s" AS FLOAT) &lt; %s ELSE false END) """%(params[0],params[0],params[1]) if t == '<=': return params[0], """(CASE WHEN "%s" ~ E'^[-]?[[:digit:]]+([.][[:digit:]]+)?$' THEN CAST ("%s" AS FLOAT) &lt;= %s ELSE false END)"""%(params[0],params[0],params[1]) if t == '>': return params[0], """(CASE WHEN "%s" ~ E'^[-]?[[:digit:]]+([.][[:digit:]]+)?$' THEN CAST ("%s" AS FLOAT) > %s ELSE false END) """%(params[0],params[0],params[1]) if t == '>=': return params[0], """(CASE WHEN "%s" ~ E'^[-]?[[:digit:]]+([.][[:digit:]]+)?$' THEN CAST ("%s" AS FLOAT) >= %s ELSE false END) """%(params[0],params[0],params[1]) except KeyError: pass def get_mapnik_filter(self): #params = [re.escape(x) for x in self.params] params = self.params t = self.type if t == 'eq': # don't compare tags against sublayers if params[0][:2] == "::": return '' try: if t == 'eq': return '[%s] = \'%s\''%(params[0], params[1]) if t == 'ne': return 'not([%s] = \'%s\')'%(params[0], params[1]) if t == 'regex': return '[%s].match(\'%s\')'%(params[0], params[1].replace("'","\\'")) if t == 'true': return '[%s] = \'yes\''%(params[0]) if t == 'untrue': return '[%s] = \'no\''%(params[0]) if t == 'set': return '[%s] != \'\''%(params[0]) if t == 'unset': return 'not([%s] != \'\')'%(params[0]) if t == '<': return '[%s__num] &lt; %s'%(params[0], float(params[1])) if t == '<=': return '[%s__num] &lt;= %s'%(params[0], float(params[1])) if t == '>': return '[%s__num] &gt; %s'%(params[0], float(params[1])) if t == '>=': return '[%s__num] &gt;= %s'%(params[0], float(params[1])) #return "" except KeyError: pass def __repr__(self): return "%s %s "%(self.type, repr(self.params)) def __eq__(self, a): return (self.params == a.params) and (self.type == a.type) def and_with(self, c2): """ merges two rules with AND. """ #TODO: possible other minimizations if c2.params[0] == self.params[0]: if c2.params == self.params: if c2.type == INVERSIONS[self.type]: # for example, eq AND ne = 0 return False if c2.type == self.type: return (self,) if self.type == ">=" and c2.type == "<=": # a<=2 and a>=2 --> a=2 return (Condition ("eq", self.params),) if self.type == "<=" and c2.type == ">=": return (Condition ("eq", self.params),) if self.type == ">" and c2.type == "<": return False if self.type == "<" and c2.type == ">": return False if c2.type == "eq" and self.type in ("ne", "<", ">"): if c2.params[1] != self.params[1]: return (c2,) if self.type == "eq" and c2.type in ("ne", "<", ">"): if c2.params[1] != self.params[1]: return (self,) if self.type == "eq" and c2.type == "eq": if c2.params[1] != self.params[1]: return False if c2.type == "set" and self.type in ("eq","ne","regex", "<", "<=", ">", ">="): # a is set and a == b -> a == b return (self,) if c2.type == "unset" and self.type in ("eq","ne","regex", "<", "<=", ">", ">="): # a is unset and a == b -> impossible return False if self.type == "set" and c2.type in ("eq","ne","regex", "<", "<=", ">", ">="): return (c2,) if self.type == "unset" and c2.type in ("eq","ne","regex", "<", "<=", ">", ">="): return False return self, c2 def Number(tt): """ Wrap float() not to produce exceptions """ try: return float(tt) except ValueError: return 0
Python
import os from distutils.core import setup setup(name='webcolors', version='1.3', description='A library for working with sRGB color specifications as used in HTML and CSS.', long_description=open(os.path.join(os.path.dirname(__file__), 'README.txt')).read(), author='James Bennett', author_email='james@b-list.org', url='http://www.bitbucket.org/ubernostrum/webcolors/overview/', py_modules=['webcolors'], download_url='http://bitbucket.org/ubernostrum/webcolors/downloads/webcolors-1.3.tar.gz', classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
Python
# -*- coding: utf-8 -*-
Python
# -*- coding: utf-8 -*- """ A simple library for working with the color names and color codes defined by the HTML and CSS specifications. An overview of HTML and CSS colors ---------------------------------- Colors on the Web are specified in `the sRGB color space`_, where each color is made up of a red component, a green component and a blue component. This is useful because it maps (fairly) cleanly to the red, green and blue components of pixels on a computer display, and to the cone cells of a human eye, which come in three sets roughly corresponding to the wavelengths of light associated with red, green and blue. `The HTML 4 standard`_ defines two ways to specify sRGB colors: * A hash mark ('#') followed by three pairs of hexdecimal digits, specifying values for red, green and blue components in that order; for example, ``#0099cc``. Since each pair of hexadecimal digits can express 256 different values, this allows up to 256**3 or 16,777,216 unique colors to be specified (though, due to differences in display technology, not all of these colors may be clearly distinguished on any given physical display). * A set of predefined color names which correspond to specific hexadecimal values; for example, ``white``. HTML 4 defines sixteen such colors. `The CSS 2 standard`_ allows any valid HTML 4 color specification, and adds three new ways to specify sRGB colors: * A hash mark followed by three hexadecimal digits, which is expanded into three hexadecimal pairs by repeating each digit; thus ``#09c`` is equivalent to ``#0099cc``. * The string 'rgb', followed by parentheses, between which are three numeric values each between 0 and 255, inclusive, which are taken to be the values of the red, green and blue components in that order; for example, ``rgb(0, 153, 204)``. * The same as above, except using percentages instead of numeric values; for example, ``rgb(0%, 60%, 80%)``. `The CSS 2.1 revision`_ does not add any new methods of specifying sRGB colors, but does add one additional named color. `The CSS 3 color module`_ (currently a W3C Candidate Recommendation) adds one new way to specify sRGB colors: * A hue-saturation-lightness triple (HSL), using the construct ``hsl()``. It also adds support for variable opacity of colors, by allowing the specification of alpha-channel information, through the ``rgba()`` and ``hsla()`` constructs, which are identical to ``rgb()`` and ``hsl()`` with one exception: a fourth value is supplied, indicating the level of opacity from ``0.0`` (completely transparent) to ``1.0`` (completely opaque). Though not technically a color, the keyword ``transparent`` is also made available in lieu of a color value, and corresponds to ``rgba(0,0,0,0)``. Additionally, CSS3 defines a new set of color names; this set is taken directly from the named colors defined for SVG (Scalable Vector Graphics) markup, and is a proper superset of the named colors defined in CSS 2.1. This set also has significant overlap with traditional X11 color sets as defined by the ``rgb.txt`` file on many Unix and Unix-like operating systems, though the correspondence is not exact; the set of X11 colors is not standardized, and the set of CSS3 colors contains some definitions which diverge significantly from customary X11 definitions (for example, CSS3's ``green`` is not equivalent to X11's ``green``; the value which X11 designates ``green`` is designated ``lime`` in CSS3). .. _the sRGB color space: http://www.w3.org/Graphics/Color/sRGB .. _The HTML 4 standard: http://www.w3.org/TR/html401/types.html#h-6.5 .. _The CSS 2 standard: http://www.w3.org/TR/REC-CSS2/syndata.html#value-def-color .. _The CSS 2.1 revision: http://www.w3.org/TR/CSS21/ .. _The CSS 3 color module: http://www.w3.org/TR/css3-color/ What this module supports ------------------------- The mappings and functions within this module support the following methods of specifying sRGB colors, and conversions between them: * Six-digit hexadecimal. * Three-digit hexadecimal. * Integer ``rgb()`` triplet. * Percentage ``rgb()`` triplet. * Varying selections of predefined color names (see below). This module does not support ``hsl()`` triplets, nor does it support opacity/alpha-channel information via ``rgba()`` or ``hsla()``. If you need to convert between RGB-specified colors and HSL-specified colors, or colors specified via other means, consult `the colorsys module`_ in the Python standard library, which can perform conversions amongst several common color spaces. .. _the colorsys module: http://docs.python.org/library/colorsys.html Normalization ------------- For colors specified via hexadecimal values, this module will accept input in the following formats: * A hash mark (#) followed by three hexadecimal digits, where letters may be upper- or lower-case. * A hash mark (#) followed by six hexadecimal digits, where letters may be upper- or lower-case. For output which consists of a color specified via hexadecimal values, and for functions which perform intermediate conversion to hexadecimal before returning a result in another format, this module always normalizes such values to the following format: * A hash mark (#) followed by six hexadecimal digits, with letters forced to lower-case. The function ``normalize_hex()`` in this module can be used to perform this normalization manually if desired; see its documentation for an explanation of the normalization process. For colors specified via predefined names, this module will accept input in the following formats: * An entirely lower-case name, such as ``aliceblue``. * A name using initial capitals, such as ``AliceBlue``. For output which consists of a color specified via a predefined name, and for functions which perform intermediate conversion to a predefined name before returning a result in another format, this module always normalizes such values to be entirely lower-case. Mappings of color names ----------------------- For each set of defined color names -- HTML 4, CSS 2, CSS 2.1 and CSS 3 -- this module exports two mappings: one of normalized color names to normalized hexadecimal values, and one of normalized hexadecimal values to normalized color names. These eight mappings are as follows: ``html4_names_to_hex`` Mapping of normalized HTML 4 color names to normalized hexadecimal values. ``html4_hex_to_names`` Mapping of normalized hexadecimal values to normalized HTML 4 color names. ``css2_names_to_hex`` Mapping of normalized CSS 2 color names to normalized hexadecimal values. Because CSS 2 defines the same set of named colors as HTML 4, this is merely an alias for ``html4_names_to_hex``. ``css2_hex_to_names`` Mapping of normalized hexadecimal values to normalized CSS 2 color nams. For the reasons described above, this is merely an alias for ``html4_hex_to_names``. ``css21_names_to_hex`` Mapping of normalized CSS 2.1 color names to normalized hexadecimal values. This is identical to ``html4_names_to_hex``, except for one addition: ``orange``. ``css21_hex_to_names`` Mapping of normalized hexadecimal values to normalized CSS 2.1 color names. As above, this is identical to ``html4_hex_to_names`` except for the addition of ``orange``. ``css3_names_to_hex`` Mapping of normalized CSS3 color names to normalized hexadecimal values. ``css3_hex_to_names`` Mapping of normalized hexadecimal values to normalized CSS3 color names. """ import math import re from hashlib import md5 def _reversedict(d): """ Internal helper for generating reverse mappings; given a dictionary, returns a new dictionary with keys and values swapped. """ return dict(zip(d.values(), d.keys())) HEX_COLOR_RE = re.compile(r'^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$') SUPPORTED_SPECIFICATIONS = ('html4', 'css2', 'css21', 'css3') ###################################################################### # Mappings of color names to normalized hexadecimal color values. ###################################################################### html4_names_to_hex = { 'aqua': '#00ffff', 'black': '#000000', 'blue': '#0000ff', 'fuchsia': '#ff00ff', 'green': '#008000', 'grey': '#808080', 'lime': '#00ff00', 'maroon': '#800000', 'navy': '#000080', 'olive': '#808000', 'purple': '#800080', 'red': '#ff0000', 'silver': '#c0c0c0', 'teal': '#008080', 'white': '#ffffff', 'yellow': '#ffff00' } css2_names_to_hex = html4_names_to_hex css21_names_to_hex = dict(html4_names_to_hex, orange='#ffa500') css3_names_to_hex = { 'aliceblue': '#f0f8ff', 'antiquewhite': '#faebd7', 'aqua': '#00ffff', 'aquamarine': '#7fffd4', 'azure': '#f0ffff', 'beige': '#f5f5dc', 'bisque': '#ffe4c4', 'black': '#000000', 'blanchedalmond': '#ffebcd', 'blue': '#0000ff', 'blueviolet': '#8a2be2', 'brown': '#a52a2a', 'burlywood': '#deb887', 'cadetblue': '#5f9ea0', 'chartreuse': '#7fff00', 'chocolate': '#d2691e', 'coral': '#ff7f50', 'cornflowerblue': '#6495ed', 'cornsilk': '#fff8dc', 'crimson': '#dc143c', 'cyan': '#00ffff', 'darkblue': '#00008b', 'darkcyan': '#008b8b', 'darkgoldenrod': '#b8860b', 'darkgray': '#a9a9a9', 'darkgrey': '#a9a9a9', 'darkgreen': '#006400', 'darkkhaki': '#bdb76b', 'darkmagenta': '#8b008b', 'darkolivegreen': '#556b2f', 'darkorange': '#ff8c00', 'darkorchid': '#9932cc', 'darkred': '#8b0000', 'darksalmon': '#e9967a', 'darkseagreen': '#8fbc8f', 'darkslateblue': '#483d8b', 'darkslategray': '#2f4f4f', 'darkslategrey': '#2f4f4f', 'darkturquoise': '#00ced1', 'darkviolet': '#9400d3', 'deeppink': '#ff1493', 'deepskyblue': '#00bfff', 'dimgray': '#696969', 'dimgrey': '#696969', 'dodgerblue': '#1e90ff', 'firebrick': '#b22222', 'floralwhite': '#fffaf0', 'forestgreen': '#228b22', 'fuchsia': '#ff00ff', 'gainsboro': '#dcdcdc', 'ghostwhite': '#f8f8ff', 'gold': '#ffd700', 'goldenrod': '#daa520', 'gray': '#808080', 'grey': '#808080', 'green': '#008000', 'greenyellow': '#adff2f', 'honeydew': '#f0fff0', 'hotpink': '#ff69b4', 'indianred': '#cd5c5c', 'indigo': '#4b0082', 'ivory': '#fffff0', 'khaki': '#f0e68c', 'lavender': '#e6e6fa', 'lavenderblush': '#fff0f5', 'lawngreen': '#7cfc00', 'lemonchiffon': '#fffacd', 'lightblue': '#add8e6', 'lightcoral': '#f08080', 'lightcyan': '#e0ffff', 'lightgoldenrodyellow': '#fafad2', 'lightgray': '#d3d3d3', 'lightgrey': '#d3d3d3', 'lightgreen': '#90ee90', 'lightpink': '#ffb6c1', 'lightsalmon': '#ffa07a', 'lightseagreen': '#20b2aa', 'lightskyblue': '#87cefa', 'lightslategray': '#778899', 'lightslategrey': '#778899', 'lightsteelblue': '#b0c4de', 'lightyellow': '#ffffe0', 'lime': '#00ff00', 'limegreen': '#32cd32', 'linen': '#faf0e6', 'magenta': '#ff00ff', 'maroon': '#800000', 'mediumaquamarine': '#66cdaa', 'mediumblue': '#0000cd', 'mediumorchid': '#ba55d3', 'mediumpurple': '#9370d8', 'mediumseagreen': '#3cb371', 'mediumslateblue': '#7b68ee', 'mediumspringgreen': '#00fa9a', 'mediumturquoise': '#48d1cc', 'mediumvioletred': '#c71585', 'midnightblue': '#191970', 'mintcream': '#f5fffa', 'mistyrose': '#ffe4e1', 'moccasin': '#ffe4b5', 'navajowhite': '#ffdead', 'navy': '#000080', 'oldlace': '#fdf5e6', 'olive': '#808000', 'olivedrab': '#6b8e23', 'orange': '#ffa500', 'orangered': '#ff4500', 'orchid': '#da70d6', 'palegoldenrod': '#eee8aa', 'palegreen': '#98fb98', 'paleturquoise': '#afeeee', 'palevioletred': '#d87093', 'papayawhip': '#ffefd5', 'peachpuff': '#ffdab9', 'peru': '#cd853f', 'pink': '#ffc0cb', 'plum': '#dda0dd', 'powderblue': '#b0e0e6', 'purple': '#800080', 'red': '#ff0000', 'rosybrown': '#bc8f8f', 'royalblue': '#4169e1', 'saddlebrown': '#8b4513', 'salmon': '#fa8072', 'sandybrown': '#f4a460', 'seagreen': '#2e8b57', 'seashell': '#fff5ee', 'sienna': '#a0522d', 'silver': '#c0c0c0', 'skyblue': '#87ceeb', 'slateblue': '#6a5acd', 'slategray': '#708090', 'slategrey': '#708090', 'snow': '#fffafa', 'springgreen': '#00ff7f', 'steelblue': '#4682b4', 'tan': '#d2b48c', 'teal': '#008080', 'thistle': '#d8bfd8', 'tomato': '#ff6347', 'turquoise': '#40e0d0', 'violet': '#ee82ee', 'wheat': '#f5deb3', 'white': '#ffffff', 'whitesmoke': '#f5f5f5', 'yellow': '#ffff00', 'yellowgreen': '#9acd32', } ###################################################################### # Mappings of normalized hexadecimal color values to color names. ###################################################################### html4_hex_to_names = _reversedict(html4_names_to_hex) css2_hex_to_names = html4_hex_to_names css21_hex_to_names = _reversedict(css21_names_to_hex) css3_hex_to_names = _reversedict(css3_names_to_hex) ###################################################################### # Normalization routines. ###################################################################### def normalize_hex(hex_value): """ Normalize a hexadecimal color value to the following form and return the result:: #[a-f0-9]{6} In other words, the following transformations are applied as needed: * If the value contains only three hexadecimal digits, it is expanded to six. * The value is normalized to lower-case. If the supplied value cannot be interpreted as a hexadecimal color value, ``ValueError`` is raised. Examples: >>> normalize_hex('#09c') '#0099cc' >>> normalize_hex('#0099cc') '#0099cc' >>> normalize_hex('#09C') '#0099cc' >>> normalize_hex('#0099CC') '#0099cc' >>> normalize_hex('0099cc') Traceback (most recent call last): ... ValueError: '0099cc' is not a valid hexadecimal color value. >>> normalize_hex('#0099QX') Traceback (most recent call last): ... ValueError: '#0099QX' is not a valid hexadecimal color value. >>> normalize_hex('foobarbaz') Traceback (most recent call last): ... ValueError: 'foobarbaz' is not a valid hexadecimal color value. >>> normalize_hex('#0') Traceback (most recent call last): ... ValueError: '#0' is not a valid hexadecimal color value. """ try: hex_digits = HEX_COLOR_RE.match(hex_value).groups()[0] except AttributeError: raise ValueError("'%s' is not a valid hexadecimal color value." % hex_value) if len(hex_digits) == 3: hex_digits = ''.join(map(lambda s: 2 * s, hex_digits)) return '#%s' % hex_digits.lower() ###################################################################### # Conversions from color names to various formats. ###################################################################### def name_to_hex(name, spec='css3'): """ Convert a color name to a normalized hexadecimal color value. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css3``. The color name will be normalized to lower-case before being looked up, and when no color of that name exists in the given specification, ``ValueError`` is raised. Examples: >>> name_to_hex('deepskyblue') '#00bfff' >>> name_to_hex('DeepSkyBlue') '#00bfff' >>> name_to_hex('white', spec='html4') '#ffffff' >>> name_to_hex('white', spec='css2') '#ffffff' >>> name_to_hex('white', spec='css21') '#ffffff' >>> name_to_hex('white', spec='css3') '#ffffff' >>> name_to_hex('white', spec='css4') Traceback (most recent call last): ... TypeError: 'css4' is not a supported specification for color name lookups; supported specifications are: html4, css2, css21, css3. >>> name_to_hex('deepskyblue', spec='css2') Traceback (most recent call last): ... ValueError: 'deepskyblue' is not defined as a named color in css2. """ if spec not in SUPPORTED_SPECIFICATIONS: raise TypeError("'%s' is not a supported specification for color name lookups; supported specifications are: %s." % (spec, ', '.join(SUPPORTED_SPECIFICATIONS))) normalized = name.lower() try: hex_value = globals()['%s_names_to_hex' % spec][normalized] except KeyError: raise ValueError("'%s' is not defined as a named color in %s." % (name, spec)) return hex_value def name_to_rgb(name, spec='css3'): """ Convert a color name to a 3-tuple of integers suitable for use in an ``rgb()`` triplet specifying that color. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css3``. The color name will be normalized to lower-case before being looked up, and when no color of that name exists in the given specification, ``ValueError`` is raised. Examples: >>> name_to_rgb('navy') (0, 0, 128) >>> name_to_rgb('cadetblue') (95, 158, 160) >>> name_to_rgb('cadetblue', spec='html4') Traceback (most recent call last): ... ValueError: 'cadetblue' is not defined as a named color in html4. """ return hex_to_rgb(name_to_hex(name, spec=spec)) def name_to_rgb_percent(name, spec='css3'): """ Convert a color name to a 3-tuple of percentages suitable for use in an ``rgb()`` triplet specifying that color. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css3``. The color name will be normalized to lower-case before being looked up, and when no color of that name exists in the given specification, ``ValueError`` is raised. Examples: >>> name_to_rgb_percent('white') ('100%', '100%', '100%') >>> name_to_rgb_percent('navy') ('0%', '0%', '50%') >>> name_to_rgb_percent('goldenrod') ('85.49%', '64.71%', '12.5%') """ return rgb_to_rgb_percent(name_to_rgb(name, spec=spec)) ###################################################################### # Conversions from hexadecimal color values to various formats. ###################################################################### def hex_to_name(hex_value, spec='css3'): """ Convert a hexadecimal color value to its corresponding normalized color name, if any such name exists. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css3``. The hexadecimal value will be normalized before being looked up, and when no color name for the value is found in the given specification, ``ValueError`` is raised. Examples: >>> hex_to_name('#000080') 'navy' >>> hex_to_name('#000080', spec='html4') 'navy' >>> hex_to_name('#000080', spec='css2') 'navy' >>> hex_to_name('#000080', spec='css21') 'navy' >>> hex_to_name('#8b4513') 'saddlebrown' >>> hex_to_name('#8b4513', spec='html4') Traceback (most recent call last): ... ValueError: '#8b4513' has no defined color name in html4. >>> hex_to_name('#8b4513', spec='css4') Traceback (most recent call last): ... TypeError: 'css4' is not a supported specification for color name lookups; supported specifications are: html4, css2, css21, css3. """ if spec not in SUPPORTED_SPECIFICATIONS: raise TypeError("'%s' is not a supported specification for color name lookups; supported specifications are: %s." % (spec, ', '.join(SUPPORTED_SPECIFICATIONS))) normalized = normalize_hex(hex_value) try: name = globals()['%s_hex_to_names' % spec][normalized] except KeyError: raise ValueError("'%s' has no defined color name in %s." % (hex_value, spec)) return name def hex_to_rgb(hex_value): """ Convert a hexadecimal color value to a 3-tuple of integers suitable for use in an ``rgb()`` triplet specifying that color. The hexadecimal value will be normalized before being converted. Examples: >>> hex_to_rgb('#000080') (0, 0, 128) >>> hex_to_rgb('#ffff00') (255, 255, 0) >>> hex_to_rgb('#f00') (255, 0, 0) >>> hex_to_rgb('#deb887') (222, 184, 135) """ hex_digits = normalize_hex(hex_value) return tuple(map(lambda s: int(s, 16), (hex_digits[1:3], hex_digits[3:5], hex_digits[5:7]))) def hex_to_rgb_percent(hex_value): """ Convert a hexadecimal color value to a 3-tuple of percentages suitable for use in an ``rgb()`` triplet representing that color. The hexadecimal value will be normalized before converting. Examples: >>> hex_to_rgb_percent('#ffffff') ('100%', '100%', '100%') >>> hex_to_rgb_percent('#000080') ('0%', '0%', '50%') """ return rgb_to_rgb_percent(hex_to_rgb(hex_value)) ###################################################################### # Conversions from integer rgb() triplets to various formats. ###################################################################### def rgb_to_name(rgb_triplet, spec='css3'): """ Convert a 3-tuple of integers, suitable for use in an ``rgb()`` color triplet, to its corresponding normalized color name, if any such name exists. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css3``. If there is no matching name, ``ValueError`` is raised. Examples: >>> rgb_to_name((0, 0, 0)) 'black' >>> rgb_to_name((0, 0, 128)) 'navy' >>> rgb_to_name((95, 158, 160)) 'cadetblue' """ return hex_to_name(rgb_to_hex(rgb_triplet), spec=spec) def rgb_to_hex(rgb_triplet): """ Convert a 3-tuple of integers, suitable for use in an ``rgb()`` color triplet, to a normalized hexadecimal value for that color. Examples: >>> rgb_to_hex((255, 255, 255)) '#ffffff' >>> rgb_to_hex((0, 0, 128)) '#000080' >>> rgb_to_hex((33, 56, 192)) '#2138c0' """ return '#%02x%02x%02x' % rgb_triplet def rgb_to_rgb_percent(rgb_triplet): """ Convert a 3-tuple of integers, suitable for use in an ``rgb()`` color triplet, to a 3-tuple of percentages suitable for use in representing that color. This function makes some trade-offs in terms of the accuracy of the final representation; for some common integer values, special-case logic is used to ensure a precise result (e.g., integer 128 will always convert to '50%', integer 32 will always convert to '12.5%'), but for all other values a standard Python ``float`` is used and rounded to two decimal places, which may result in a loss of precision for some values. Examples: >>> rgb_to_rgb_percent((255, 255, 255)) ('100%', '100%', '100%') >>> rgb_to_rgb_percent((0, 0, 128)) ('0%', '0%', '50%') >>> rgb_to_rgb_percent((33, 56, 192)) ('12.94%', '21.96%', '75.29%') >>> rgb_to_rgb_percent((64, 32, 16)) ('25%', '12.5%', '6.25%') """ # In order to maintain precision for common values, # 256 / 2**n is special-cased for values of n # from 0 through 4, as well as 0 itself. specials = { 255: '100%', 128: '50%', 64: '25%', 32: '12.5%', 16: '6.25%', 0: '0%' } return tuple(map(lambda d: specials.get(d, '%.02f%%' % ((d / 255.0) * 100)), rgb_triplet)) ###################################################################### # Conversions from percentage rgb() triplets to various formats. ###################################################################### def rgb_percent_to_name(rgb_percent_triplet, spec='css3'): """ Convert a 3-tuple of percentages, suitable for use in an ``rgb()`` color triplet, to its corresponding normalized color name, if any such name exists. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css3``. If there is no matching name, ``ValueError`` is raised. Examples: >>> rgb_percent_to_name(('0%', '0%', '0%')) 'black' >>> rgb_percent_to_name(('0%', '0%', '50%')) 'navy' >>> rgb_percent_to_name(('85.49%', '64.71%', '12.5%')) 'goldenrod' """ return rgb_to_name(rgb_percent_to_rgb(rgb_percent_triplet), spec=spec) def rgb_percent_to_hex(rgb_percent_triplet): """ Convert a 3-tuple of percentages, suitable for use in an ``rgb()`` color triplet, to a normalized hexadecimal color value for that color. Examples: >>> rgb_percent_to_hex(('100%', '100%', '0%')) '#ffff00' >>> rgb_percent_to_hex(('0%', '0%', '50%')) '#000080' >>> rgb_percent_to_hex(('85.49%', '64.71%', '12.5%')) '#daa520' """ return rgb_to_hex(rgb_percent_to_rgb(rgb_percent_triplet)) def _percent_to_integer(percent): """ Internal helper for converting a percentage value to an integer between 0 and 255 inclusive. """ num = float(percent.split('%')[0]) / 100.0 * 255 e = num - math.floor(num) return e < 0.5 and int(math.floor(num)) or int(math.ceil(num)) def rgb_percent_to_rgb(rgb_percent_triplet): """ Convert a 3-tuple of percentages, suitable for use in an ``rgb()`` color triplet, to a 3-tuple of integers suitable for use in representing that color. Some precision may be lost in this conversion. See the note regarding precision for ``rgb_to_rgb_percent()`` for details; generally speaking, the following is true for any 3-tuple ``t`` of integers in the range 0...255 inclusive:: t == rgb_percent_to_rgb(rgb_to_rgb_percent(t)) Examples: >>> rgb_percent_to_rgb(('100%', '100%', '100%')) (255, 255, 255) >>> rgb_percent_to_rgb(('0%', '0%', '50%')) (0, 0, 128) >>> rgb_percent_to_rgb(('25%', '12.5%', '6.25%')) (64, 32, 16) >>> rgb_percent_to_rgb(('12.94%', '21.96%', '75.29%')) (33, 56, 192) """ return tuple(map(_percent_to_integer, rgb_percent_triplet)) def whatever_to_rgb(string): """ Converts CSS3 color or a hex into rgb triplet; hash of string if fails. """ try: return name_to_rgb(string) except ValueError: try: return hex_to_rgb(string) except ValueError: #a = md5.new(string) return hex_to_rgb("#"+md5(string).hexdigest()[:6]) def whatever_to_hex(string): if type(string) == tuple: return cairo_to_hex(string) return rgb_to_hex(whatever_to_rgb(string)) def whatever_to_cairo(string): a = whatever_to_rgb(string) return a[0]/255.,a[1]/255.,a[2]/255., def cairo_to_hex (cairo): return rgb_to_hex((cairo[0]*255,cairo[1]*255,cairo[2]*255,)) if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of kothic, the realtime map renderer. # kothic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # kothic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with kothic. If not, see <http://www.gnu.org/licenses/>. from Rule import Rule from webcolors.webcolors import whatever_to_cairo as colorparser from webcolors.webcolors import cairo_to_hex from Eval import Eval class StyleChooser: """ A StyleChooser object is equivalent to one CSS selector+declaration. Its ruleChains property is an array of all the selectors, which would traditionally be comma-separated. For example: h1, h2, h3 em is three ruleChains. Each ruleChain is itself an array of nested selectors. So the above example would roughly be encoded as: [[h1],[h2],[h3,em]] ^^ ^^ ^^ ^^ each of these is a Rule The styles property is an array of all the style objects to be drawn if any of the ruleChains evaluate to true. """ def __repr__(self): return "{(%s) : [%s] }\n"%(self.ruleChains, self.styles) def __init__(self, scalepair): self.ruleChains = [[],] self.styles = [] self.eval_type = type(Eval()) self.scalepair = scalepair self.rcpos=0 self.stylepos=0 def get_numerics(self): """ Returns a set of number-compared values. """ a = set() for c in self.ruleChains: for r in c: a.update(r.get_numerics()) a.discard(False) return a def get_interesting_tags(self, type, zoom): """ Returns a set of tags that were used in here. """ ### FIXME a = set() for c in self.ruleChains: for r in c: a.update(r.get_interesting_tags(type, zoom)) if a: ## FIXME: semi-illegal optimization, may wreck in future on tagless matches for r in self.styles: for c,b in r.iteritems(): if __builtins__["type"](b) == self.eval_type: a.update(b.extract_tags()) return a def get_sql_hints(self, type, zoom): """ Returns a set of tags that were used in here in form of SQL-hints. """ a = set() b = "" needed = set(["width", "casing-width", "fill-color", "fill-image", "icon-image", "text", "extrude", "background-image", "background-color", "pattern-image"]) if not needed.isdisjoint(set(self.styles[0].keys())): for c in self.ruleChains: for r in c: p = r.get_sql_hints(type, zoom) if p: q = "("+p[1] + ")"#[t[1] for t in p] if q == "()": q = "" if b and q: b += " OR "+ q else: b = q a.update(p[0]) # no need to check for eval's return a,b # // Update the current StyleList from this StyleChooser def updateStyles(self,sl,type, tags, zoom, scale, zscale): # Are any of the ruleChains fulfilled? w = 0 for c in self.ruleChains: if (self.testChain(c,type,tags,zoom)): break else: return sl ## Update StyleList object_id = 1 for r in self.styles: ra = {} for a,b in r.iteritems(): "calculating eval()'s" if __builtins__["type"](b) == self.eval_type: combined_style = {} for t in sl: combined_style.update(t) for p,q in combined_style.iteritems(): if "color" in p: combined_style[p] = cairo_to_hex(q) b = b.compute(tags,combined_style, scale, zscale) ra[a] = b r = ra ra = {} for a, b in r.iteritems(): "checking and nicifying style table" if "color" in a: "parsing color value to 3-tuple" ra[a] = colorparser(b) elif any(x in a for x in ("width", "z-index", "opacity", "offset", "radius", "extrude")): "these things are float's or not in table at all" try: ra[a] = float(b) except ValueError: pass elif "dashes" in a: "these things are arrays of float's or not in table at all" try: b = b.split(",") b = [float(x) for x in b] ra[a]= b except ValueError: pass else: ra[a]=b ra["layer"] = float(tags.get("layer",0))*100+ra.get("z-index",1) # calculating z-index for k,v in ra.items(): # if a value is empty, we don't need it - renderer will do as default. if not v: del ra[k] if "object-id" not in ra: ra["object-id"] = str(object_id) for x in sl: if x.get("object-id","1") == ra["object-id"]: x.update(ra) break else: sl.append(ra) object_id += 1 return sl #a = "" #if (r is ShapeStyle) { #a=sl.shapeStyles; #if (ShapeStyle(r).width>sl.maxwidth && !r.evals['width']) { sl.maxwidth=ShapeStyle(r).width; } #} else if (r is ShieldStyle) { #a=sl.shieldStyles; #} else if (r is TextStyle) { #a=sl.textStyles; #} else if (r is PointStyle) { #a=sl.pointStyles; #w=0; #if (PointStyle(r).icon_width && !PointStyle(r).evals['icon_width']) { #w=PointStyle(r).icon_width; #} else if (PointStyle(r).icon_image && imageWidths[PointStyle(r).icon_image]) { #w=imageWidths[PointStyle(r).icon_image]; #} #if (w>sl.maxwidth) { sl.maxwidth=w; } #} else if (r is InstructionStyle) { #if (InstructionStyle(r).breaker) { return; } #if (InstructionStyle(r).set_tags) { #for (var k:String in InstructionStyle(r).set_tags) { tags[k]=InstructionStyle(r).set_tags[k]; } #} #continue; #} #if (r.drawn) { tags[':drawn']='yes'; } #tags['_width']=sl.maxwidth; #r.runEvals(tags); #if (a[r.sublayer]) { ## // If there's already a style on this sublayer, then merge them ## // (making a deep copy if necessary to avoid altering the root style) #if (!a[r.sublayer].merged) { a[r.sublayer]=a[r.sublayer].deepCopy(); } #a[r.sublayer].mergeWith(r); #} else { ## // Otherwise, just assign it #a[r.sublayer]=r; #} #} #} ## // Test a ruleChain ## // - run a set of tests in the chain ## // works backwards from at position "pos" in array, or -1 for the last ## // separate tags object is required in case they've been dynamically retagged ## // - if they fail, return false ## // - if they succeed, and it's the last in the chain, return happily ## // - if they succeed, and there's more in the chain, rerun this for each parent until success #private function testChain(chain:Array,pos:int,obj:Entity,tags:Object):Boolean { #if (pos==-1) { pos=chain.length-1; } #var r:Rule=chain[pos]; #if (!r.test(obj, tags)) { return false; } #if (pos==0) { return true; } #var o:Array=obj.parentObjects; #for each (var p:Entity in o) { #if (testChain(chain, pos-1, p, p.getTagsHash() )) { return true; } #} #return false; #} def testChain(self,chain, obj, tags, zoom): """ Tests an object against a chain """ ### FIXME: total MapCSS misreading for r in chain: if r.test(obj,tags,zoom): return True return False ## // --------------------------------------------------------------------------------------------- ## // Methods to add properties (used by parsers such as MapCSS) def newGroup(self): """ starts a new ruleChain in this.ruleChains """ if (len(self.ruleChains[self.rcpos])>0): self.ruleChains.append([]) #} #} def newObject(self,e=''): """ adds into the current ruleChain (starting a new Rule) """ self.ruleChains[self.rcpos].append(Rule(e)) self.ruleChains[self.rcpos][-1].minZoom=float(self.scalepair[0]) self.ruleChains[self.rcpos][-1].maxZoom=float(self.scalepair[1]) def addZoom(self,z): """ adds into the current ruleChain (existing Rule) """ self.ruleChains[self.rcpos][len(self.ruleChains[self.rcpos])-1].minZoom=float(z[0]) self.ruleChains[self.rcpos][len(self.ruleChains[self.rcpos])-1].maxZoom=float(z[1]) def addCondition(self,c): """ adds into the current ruleChain (existing Rule) """ self.ruleChains[self.rcpos][len(self.ruleChains[self.rcpos])-1].conditions.append(c) def addStyles(self, a): """ adds to this.styles """ rb = [] for r in a: ra = {} for a,b in r.iteritems(): if "text" == a[-4:]: if b.strip()[:5] != "eval(": b = "eval(tag(\""+b+"\"))" if b.strip()[:5] == "eval(": b = Eval(b) ra[a] = b rb.append(ra) # print rb self.styles = self.styles + rb
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of kothic, the realtime map renderer. # kothic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # kothic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with kothic. If not, see <http://www.gnu.org/licenses/>. import re import logging from hashlib import md5 from StyleChooser import StyleChooser from Condition import Condition WHITESPACE = re.compile(r'^ \s+ ', re.S | re.X) COMMENT = re.compile(r'^ \/\* .+? \*\/ \s* ', re.S | re.X) CLASS = re.compile(r'^ ([\.:]:?\w+) \s* ', re.S | re.X) NOT_CLASS = re.compile(r'^ !([\.:]\w+) \s* ', re.S | re.X) ZOOM = re.compile(r'^ \| \s* z([\d\-]+) \s* ', re.I | re.S | re.X) GROUP = re.compile(r'^ , \s* ', re.I | re.S | re.X) CONDITION = re.compile(r'^ \[(.+?)\] \s* ', re.S | re.X) OBJECT = re.compile(r'^ (\w+) \s* ', re.S | re.X) DECLARATION = re.compile(r'^ \{(.+?)\} \s* ', re.S | re.X) UNKNOWN = re.compile(r'^ (\S+) \s* ', re.S | re.X) ZOOM_MINMAX = re.compile(r'^ (\d+)\-(\d+) $', re.S | re.X) ZOOM_MIN = re.compile(r'^ (\d+)\- $', re.S | re.X) ZOOM_MAX = re.compile(r'^ \-(\d+) $', re.S | re.X) ZOOM_SINGLE = re.compile(r'^ (\d+) $', re.S | re.X) CONDITION_TRUE = re.compile(r'^ \s* ([:\w]+) \s* [?] \s* $', re.I | re.S | re.X) CONDITION_invTRUE = re.compile(r'^ \s* [!] \s* ([:\w]+) \s* [?] \s* $', re.I | re.S | re.X) CONDITION_FALSE = re.compile(r'^ \s* ([:\w]+) \s* = \s* no \s* $', re.I | re.S | re.X) CONDITION_SET = re.compile(r'^ \s* ([:\w]+) \s* $', re.S | re.X) CONDITION_UNSET = re.compile(r'^ \s* !([:\w]+) \s* $', re.S | re.X) CONDITION_EQ = re.compile(r'^ \s* ([:\w]+) \s* = \s* (.+) \s* $', re.S | re.X) CONDITION_NE = re.compile(r'^ \s* ([:\w]+) \s* != \s* (.+) \s* $', re.S | re.X) CONDITION_GT = re.compile(r'^ \s* ([:\w]+) \s* > \s* (.+) \s* $', re.S | re.X) CONDITION_GE = re.compile(r'^ \s* ([:\w]+) \s* >= \s* (.+) \s* $', re.S | re.X) CONDITION_LT = re.compile(r'^ \s* ([:\w]+) \s* < \s* (.+) \s* $', re.S | re.X) CONDITION_LE = re.compile(r'^ \s* ([:\w]+) \s* <= \s* (.+) \s* $', re.S | re.X) CONDITION_REGEX = re.compile(r'^ \s* ([:\w]+) \s* =~\/ \s* (.+) \/ \s* $', re.S | re.X) ASSIGNMENT_EVAL = re.compile(r"^ \s* (\S+) \s* \: \s* eval \s* \( \s* ' (.+?) ' \s* \) \s* $", re.I | re.S | re.X) ASSIGNMENT = re.compile(r'^ \s* (\S+) \s* \: \s* (.+?) \s* $', re.S | re.X) SET_TAG_EVAL = re.compile(r"^ \s* set \s+(\S+)\s* = \s* eval \s* \( \s* ' (.+?) ' \s* \) \s* $", re.I | re.S | re.X) SET_TAG = re.compile(r'^ \s* set \s+(\S+)\s* = \s* (.+?) \s* $', re.I | re.S | re.X) SET_TAG_TRUE = re.compile(r'^ \s* set \s+(\S+)\s* $', re.I | re.S | re.X) EXIT = re.compile(r'^ \s* exit \s* $', re.I | re.S | re.X) oZOOM=2 oGROUP=3 oCONDITION=4 oOBJECT=5 oDECLARATION=6 oSUBPART=7 DASH = re.compile(r'\-/g') COLOR = re.compile(r'color$/') BOLD = re.compile(r'^bold$/i') ITALIC = re.compile(r'^italic|oblique$/i') UNDERLINE = re.compile(r'^underline$/i') CAPS = re.compile(r'^uppercase$/i') CENTER = re.compile(r'^center$/i') HEX = re.compile(r'^#([0-9a-f]+)$/i') builtin_style = """ canvas {fill-color: #cccccc} way {width: 1; casing-width:1; casing-color: white} """ ## ** also needs to support @import rules class MapCSS(): def __init__(self,minscale=0,maxscale=19): """ """ self.cache = {} self.cache["style"] = {} self.minscale=minscale self.maxscale=maxscale self.scalepair = (minscale, maxscale) self.choosers = [] self.style_loaded = False self.parse(builtin_style) self.style_loaded = False #override one after loading def parseZoom(self, s): if ZOOM_MINMAX.match(s): return tuple([float(i) for i in ZOOM_MINMAX.match(s).groups()]) elif ZOOM_MIN.match(s): return float(ZOOM_MIN.match(s).groups()[0]), self.maxscale elif ZOOM_MAX.match(s): return float(self.minscale),float(ZOOM_MAX.match(s).groups()[0]) elif ZOOM_SINGLE.match(s): return float(ZOOM_SINGLE.match(s).groups()[0]),float(ZOOM_SINGLE.match(s).groups()[0]) else: logging.error("unparsed zoom: %s" %s) def get_style (self, type, tags={}, zoom=0, scale=1, zscale=.5): """ Kothic styling API """ shash = md5(repr(tags)+repr(zoom)).digest() if shash in self.cache["style"]: return self.cache["style"][shash] style = [] #return [{"width": 1, "color":(0,0,0), "layer": 1}, {"width": 3, "color":(1,1,1), "layer":0}] for chooser in self.choosers: style = chooser.updateStyles(style, type, tags, zoom, scale, zscale) self.cache["style"][shash] = style return style def get_interesting_tags(self, type=None, zoom=None): """ Get set of interesting tags. """ tags = set() for chooser in self.choosers: tags.update(chooser.get_interesting_tags(type, zoom)) return tags def get_sql_hints(self, type=None, zoom=None): """ Get set of interesting tags. """ hints = [] for chooser in self.choosers: p = chooser.get_sql_hints(type, zoom) if p: if p[0] and p[1]: # print chooser.get_sql_hints(type, zoom) hints.append(p) #print hints return hints def parse(self, css): """ Parses MapCSS given as string """ if not self.style_loaded: self.choosers = [] log = logging.getLogger('mapcss.parser') previous = 0 # what was the previous CSS word? sc=StyleChooser(self.scalepair) #currently being assembled #choosers=[] #o = [] while (css): # CSS comment if COMMENT.match(css): log.debug("comment found") css=COMMENT.sub("", css) #// Whitespace (probably only at beginning of file) elif WHITESPACE.match(css): log.debug("whitespace found") css=WHITESPACE.sub("",css) #// Class - .motorway, .builtup, :hover elif CLASS.match(css): if previous==oDECLARATION: self.choosers.append(sc) sc = StyleChooser(self.scalepair) cond = CLASS.match(css).groups()[0] log.debug("class found: %s"% (cond)) css = CLASS.sub("", css) sc.addCondition(Condition('eq',("::class",cond))) previous=oCONDITION; #// Not class - !.motorway, !.builtup, !:hover elif NOT_CLASS.match(css): if (previous==oDECLARATION): self.choosers.append(sc) sc = StyleChooser(self.scalepair) cond = NOT_CLASS.match(css).groups()[0] log.debug("not_class found: %s"% (cond)) css = NOT_CLASS.sub("", css) sc.addCondition(Condition('ne',("::class",cond))) previous=oCONDITION; #css=css.replace(NOT_CLASS,''); #sc.addCondition(new Condition('unset',o[1])); #previous=oCONDITION; #// Zoom elif ZOOM.match(css): if (previous!=oOBJECT & previous!=oCONDITION): sc.newObject() cond = ZOOM.match(css).groups()[0] log.debug("zoom found: %s"% (cond)) css=ZOOM.sub("",css) sc.addZoom(self.parseZoom(cond)) previous=oZOOM; #css=css.replace(ZOOM,''); #var z:Array=parseZoom(o[1]); #sc.addZoom(z[0],z[1]); #previous=oZOOM; #// Grouping - just a comma elif GROUP.match(css): css=GROUP.sub("",css) sc.newGroup() previous=oGROUP #// Condition - [highway=primary] elif CONDITION.match(css): if (previous==oDECLARATION): self.choosers.append(sc) sc = StyleChooser(self.scalepair) if (previous!=oOBJECT) and (previous!=oZOOM) and (previous!=oCONDITION): sc.newObject() cond = CONDITION.match(css).groups()[0] log.debug("condition found: %s"% (cond)) css=CONDITION.sub("",css) sc.addCondition(parseCondition(cond)) previous=oCONDITION; #// Object - way, node, relation elif OBJECT.match(css): if (previous==oDECLARATION): self.choosers.append(sc) sc = StyleChooser(self.scalepair) obj = OBJECT.match(css).groups()[0] log.debug("object found: %s"% (obj)) css=OBJECT.sub("",css) sc.newObject(obj) previous=oOBJECT #// Declaration - {...} elif DECLARATION.match(css): decl = DECLARATION.match(css).groups()[0] log.debug("declaration found: %s"% (decl)) sc.addStyles(parseDeclaration(decl)) css=DECLARATION.sub("",css) previous=oDECLARATION #// Unknown pattern elif UNKNOWN.match(css): log.warning("unknown thing found: %s"%(UNKNOWN.match(css).group())) css=UNKNOWN.sub("",css) else: log.warning("choked on: %s"%(css)) return #print sc if (previous==oDECLARATION): self.choosers.append(sc) sc= StyleChooser(self.scalepair) #print self.choosers return #} def parseCondition(s): log = logging.getLogger('mapcss.parser.condition') if CONDITION_TRUE.match(s): a = CONDITION_TRUE.match(s).groups() log.debug("condition true: %s"%(a[0])) return Condition('true' ,a) if CONDITION_invTRUE.match(s): a = CONDITION_invTRUE.match(s).groups() log.debug("condition invtrue: %s"%(a[0])) return Condition('ne' ,(a[0],"yes")) if CONDITION_FALSE.match(s): a = CONDITION_FALSE.match(s).groups() log.debug("condition false: %s"%(a[0])) return Condition('false' ,a) if CONDITION_SET.match(s): a = CONDITION_SET.match(s).groups() log.debug("condition set: %s"%(a)) return Condition('set' ,a) if CONDITION_UNSET.match(s): a = CONDITION_UNSET.match(s).groups() log.debug("condition unset: %s"%(a)) return Condition('unset' ,a) if CONDITION_NE.match(s): a = CONDITION_NE.match(s).groups() log.debug("condition NE: %s = %s"%(a[0], a[1])) return Condition('ne' ,a) ## FIXME: convert other conditions to python if CONDITION_LE.match(s): a = CONDITION_LE.match(s).groups() log.debug("condition LE: %s <= %s"%(a[0], a[1])) return Condition('<=' ,a) if CONDITION_GE.match(s): a = CONDITION_GE.match(s).groups() log.debug("condition GE: %s >= %s"%(a[0], a[1])) return Condition('>=' ,a) if CONDITION_LT.match(s): a = CONDITION_LT.match(s).groups() log.debug("condition LT: %s < %s"%(a[0], a[1])) return Condition('<' ,a) if CONDITION_GT.match(s): a = CONDITION_GT.match(s).groups() log.debug("condition GT: %s > %s"%(a[0], a[1])) return Condition('>' ,a) if CONDITION_REGEX.match(s): a = CONDITION_REGEX.match(s).groups() log.debug("condition REGEX: %s = %s"%(a[0], a[1])) return Condition('regex' ,a) #else if ((o=CONDITION_REGEX.exec(s))) { return new Condition('regex',o[1],o[2]); } if CONDITION_EQ.match(s): a = CONDITION_EQ.match(s).groups() log.debug("condition EQ: %s = %s"%(a[0], a[1])) return Condition('eq' ,a) else: log.warning("condition UNKNOWN: %s"%(s)) def parseDeclaration(s): """ Parse declaration string into list of styles """ styles=[] t = {} #var t:Object=new Object(); #var o:Object=new Object(); #var a:String, k:String; #// Create styles #var ss:ShapeStyle =new ShapeStyle() ; #var ps:PointStyle =new PointStyle() ; #var ts:TextStyle =new TextStyle() ; #var hs:ShieldStyle=new ShieldStyle(); #var xs:InstructionStyle=new InstructionStyle(); for a in s.split(';'): #if ((o=ASSIGNMENT_EVAL.exec(a))) { t[o[1].replace(DASH,'_')]=new Eval(o[2]); } if ASSIGNMENT.match(a): tzz = ASSIGNMENT.match(a).groups() t[tzz[0]]=tzz[1].strip().strip('"') logging.debug("%s == %s" % (tzz[0],tzz[1]) ) else: logging.debug("unknown %s" % (a) ) return [t] #else if ((o=SET_TAG_EVAL.exec(a))) { xs.addSetTag(o[1],new Eval(o[2])); } #else if ((o=SET_TAG.exec(a))) { xs.addSetTag(o[1],o[2]); } #else if ((o=SET_TAG_TRUE.exec(a))) { xs.addSetTag(o[1],true); } #else if ((o=EXIT.exec(a))) { xs.setPropertyFromString('breaker',true); } #} #// Find sublayer #var sub:uint=5; #if (t['z_index']) { sub=Number(t['z_index']); delete t['z_index']; } #ss.sublayer=ps.sublayer=ts.sublayer=hs.sublayer=sub; #xs.sublayer=10; #// Munge special values #if (t['font_weight'] ) { t['font_bold' ] = t['font_weight' ].match(BOLD ) ? true : false; delete t['font_weight']; } #if (t['font_style'] ) { t['font_italic'] = t['font_style' ].match(ITALIC) ? true : false; delete t['font_style']; } #if (t['text_decoration']) { t['font_underline'] = t['text_decoration'].match(UNDERLINE) ? true : false; delete t['text_decoration']; } #if (t['text_position'] ) { t['text_center'] = t['text_position' ].match(CENTER) ? true : false; delete t['text_position']; } #if (t['text_transform']) { #// ** needs other transformations, e.g. lower-case, sentence-case #if (t['text_transform'].match(CAPS)) { t['font_caps']=true; } else { t['font_caps']=false; } #delete t['text_transform']; #} #// ** Do compound settings (e.g. line: 5px dotted blue;) #// Assign each property to the appropriate style #for (a in t) { #// Parse properties #// ** also do units, e.g. px/pt #if (a.match(COLOR)) { #t[a] = parseCSSColor(t[a]); #} #// Set in styles #if (ss.hasOwnProperty(a)) { ss.setPropertyFromString(a,t[a]); } #else if (ps.hasOwnProperty(a)) { ps.setPropertyFromString(a,t[a]); } #else if (ts.hasOwnProperty(a)) { ts.setPropertyFromString(a,t[a]); } #else if (hs.hasOwnProperty(a)) { hs.setPropertyFromString(a,t[a]); } #} #// Add each style to list #if (ss.edited) { styles.push(ss); } #if (ps.edited) { styles.push(ps); } #if (ts.edited) { styles.push(ts); } #if (hs.edited) { styles.push(hs); } #if (xs.edited) { styles.push(xs); } #return styles; #} #public static function parseCSSColor(colorStr:String):uint { #colorStr = colorStr.toLowerCase(); #if (CSSCOLORS[colorStr]) #return CSSCOLORS[colorStr]; #else { #var match:Object = HEX.exec(colorStr); #if ( match ) #return Number("0x"+match[1]); #} #return 0; #} #} #} if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) mc = MapCSS(0,19)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of kothic, the realtime map renderer. # kothic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # kothic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with kothic. If not, see <http://www.gnu.org/licenses/>. NONE = "" class Eval(): def __init__(self, s='eval()'): """ Parse expression and convert it into Python """ s = s.strip()[5:-1].strip() self.expr_text = s try: self.expr = compile (s, "MapCSS expression", "eval") except: #print "Can't compile %s" % s self.expr = compile ("0", "MapCSS expression", "eval") def extract_tags(self): """ Extracts list of tags that might be used in calculation """ def fake_compute(*x): """ Perform a fake computation. Always computes all the parameters, always returns 0. WARNING: Might not cope with complex statements. """ for t in x: q = x return 0 tags = set([]) #print self.expr_text a = eval(self.expr,{},{ "tag":lambda x: max([tags.add(x), " "]), "prop": lambda x: "", "num": lambda x: 0, "metric": fake_compute, "zmetric": fake_compute, "str": lambda x: "", "any": fake_compute, "min": fake_compute, "max": fake_compute, }) return tags def compute(self, tags={}, props = {}, xscale = 1., zscale = 0.5 ): """ Compute this eval() """ for k,v in tags.iteritems(): try: tag[k] = float(v) except: pass try: return str(eval(self.expr, {}, { "tag":lambda x: tags.get(x,""), "prop":lambda x: props.get(x,""), "num": m_num, "metric": lambda x: m_metric(x, xscale), "zmetric": lambda x: m_metric(x, zscale), "str": str, "any": m_any, "min": m_min, "max": m_max, "cond": m_cond, "boolean": m_boolean })) except: return "" def __repr__(self): return "eval(%s)"%repr(self.expr) def m_boolean(expr): expr = str(expr) if expr in ("", "0", "no", "false", "False"): return False else: return True def m_cond(why, yes, no): if m_boolean(why): return yes else: return no def m_min(*x): """ min() MapCSS Feature """ try: return min([m_num(t) for t in x]) except: return 0 def m_max(*x): """ max() MapCSS Feature """ try: return max([m_num(t) for t in x]) except: return 0 def m_any(*x): """ any() MapCSS feature """ for t in x: if t: return t else: return "" def m_num(x): """ num() MapCSS feature """ try: return float(str(x)) except ValueError: return 0 def m_metric(x, t): """ metric() and zmetric() function. """ x = str(x) try: return float(x)*float(t) except: "Heuristics." # FIXME: add ft, m and friends x = x.strip() try: if x[-2:] in ("cm", "CM", "см"): return float(x[0:-2])*float(t)/100 if x[-2:] in ("mm", "MM", "мм"): return float(x[0:-2])*float(t)/1000 if x[-1] in ("m", "M", "м"): return float(x[0:-1])*float(t) except: return "" #def str(x): #""" #str() MapCSS feature #""" #return __builtins__.str(x) if __name__ == "__main__": a = Eval(""" eval( any( metric(tag("height")), metric ( num(tag("building:levels")) * 3), metric("1m"))) """) print repr(a) print a.compute({"building:levels":"3"}) print a.extract_tags()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of kothic, the realtime map renderer. # kothic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # kothic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with kothic. If not, see <http://www.gnu.org/licenses/>. import datetime import sys def debug(st): """ Debug write to stderr """ sys.stderr.write(str(st)+"\n") sys.stderr.flush() class Timer: """ A small timer for debugging """ def __init__(self, comment): self.time = datetime.datetime.now() self.comment = comment debug("%s started" % comment) def stop(self): debug("%s finished in %s" % (self.comment, str(datetime.datetime.now() - self.time)))
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of kothic, the realtime map renderer. # kothic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # kothic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with kothic. If not, see <http://www.gnu.org/licenses/>. from debug import debug, Timer from mapcss.webcolors.webcolors import whatever_to_hex as nicecolor map_proj = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" db_proj = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" table_prefix = "planet_osm_" db_user = "gis" db_name = "gis" db_srid = 900913 icons_path = "/home/gis/mapnik/kosmo/icons/" world_bnd_path = "/home/gis/mapnik/world_boundaries/" substyles = [] last_id = 0 def get_id(i = 0): global last_id last_id += i return last_id def zoom_to_scaledenom(z1,z2=False): """ Converts zoom level to mapnik's scaledenominator pair for EPSG:3857 """ if not z2: z2 = z1 s = 279541132.014 z1 = (s/(2**(z1-1))+s/(2**(z1-2)))/2 z2 = (s/(2**(z2-1))+s/(2**z2))/2 #return 100000000000000, 1 return z1, z2 def pixel_size_at_zoom(z, l=1): """ Converts l pixels on tiles into length on zoom z """ return l* 20037508.342789244 / 256 * 2 / (2**z) def xml_fontset(name, unicode=True): if unicode: unicode = '<Font face_name="unifont Medium" />' return """ <FontSet name="%s"> <Font face_name="%s" /> %s </FontSet>"""%(name, name, unicode) def xml_pointsymbolizer(path="", width="", height="", opacity=1, overlap="false"): if width: width =' width="%s" '%width if height: height =' height="%s" '%height return """ <PointSymbolizer file="%s%s" %s %s opacity="%s" allow_overlap="%s" />"""\ %(icons_path, \ path, width, height, opacity, overlap) def xml_linesymbolizer(color="#000000", width="1", opacity="1", linecap="butt", linejoin="round", dashes="", zoom=200): color = nicecolor(color) linecap = {"none":"butt",}.get(linecap.lower(), linecap) if dashes: dashes = '<CssParameter name="stroke-dasharray">%s</CssParameter>'%(dashes) else: dashes = "" rasterizer = "" # if float(width) < 4 and not dashes and zoom < 6: # rasterizer = ' rasterizer="fast"' return """ <LineSymbolizer %s> <CssParameter name="stroke">%s</CssParameter> <CssParameter name="stroke-width">%s</CssParameter> <CssParameter name="stroke-opacity">%s</CssParameter> <CssParameter name="stroke-linejoin">%s</CssParameter> <CssParameter name="stroke-linecap">%s</CssParameter> %s </LineSymbolizer>"""%(rasterizer, color, float(width), float(opacity), linejoin, linecap, dashes) def xml_polygonsymbolizer(color="#000000", opacity="1"): color = nicecolor(color) return """ <PolygonSymbolizer> <CssParameter name="fill">%s</CssParameter> <CssParameter name="fill-opacity">%s</CssParameter> </PolygonSymbolizer>"""%(color, float(opacity)) def xml_polygonpatternsymbolizer(file=""): return """ <PolygonPatternSymbolizer file="%s%s"/>"""%(icons_path,file) def xml_linepatternsymbolizer(path=""): return """ <LinePatternSymbolizer file="%s%s"/>"""%(icons_path, path) def xml_textsymbolizer( text="name",face="DejaVu Sans Book",size="10",color="#000000", halo_color="#ffffff", halo_radius="0", placement="line", offset="0", overlap="false", distance="26", wrap_width=256, align="center", opacity="1", pos="X", transform = "none"): color = nicecolor(color) halo_color = nicecolor(halo_color) pos = pos.replace("exact", "X").replace("any","S, E, X, N, W, NE, SE, NW, SW").split(",") pos.extend([str(int(float(x))) for x in size.split(",")]) pos = ",".join(pos) size = size.split(",")[0] placement = {"center": "interior"}.get(placement.lower(), placement) align = {"center": "middle"}.get(align.lower(), align) dy = int(float(offset)) dx = 0 if align in ("right",'left'): dx = dy dy = 0 return """ <TextSymbolizer name="%s" fontset_name="%s" size="%s" fill="%s" halo_fill= "%s" halo_radius="%s" placement="%s" dx="%s" dy="%s" max_char_angle_delta="17" allow_overlap="%s" wrap_width="%s" min_distance="%s" vertical_alignment="middle" horizontal_alignment="%s" opacity="%s" placement-type="simple" placements="%s" text-transform="%s" minimum-path-length="5" /> """%(text,face,int(float(size)),color,halo_color,halo_radius,placement,dx,dy,overlap,wrap_width,distance,align,opacity,pos, transform) def xml_shieldsymbolizer(path="", width="", height="", text="name",face="DejaVu Sans Book",size="10",color="#000000", halo_color="#ffffff", halo_radius="0", placement="line", offset="0", overlap="false", distance="26", wrap_width=256, align="center", opacity="1", transform="none", unlock_image='true'): color = nicecolor(color) halo_color = nicecolor(halo_color) placement = {"center": "point"}.get(placement.lower(), placement) align = {"center": "middle"}.get(align.lower(), align) size = size.split(",")[0] if width: width =' width="%s" '%width if height: height =' height="%s" '%height return """ <ShieldSymbolizer file="%s%s" %s %s name="%s" fontset_name="%s" size="%s" fill="%s" halo_fill= "%s" halo_radius="%s" placement="%s" dy="%s" allow_overlap="%s" wrap_width="%s" min_distance="%s" horizontal_alignment="%s" opacity="%s" text-transform="%s" unlock-image="%s" /> """%(icons_path, \ path, width, height,text,face,int(float(size)),color,halo_color,halo_radius,placement,offset,overlap,wrap_width,distance,align,opacity, transform, unlock_image) def xml_filter(string): return """ <Filter>%s</Filter>"""%string def xml_scaledenominator(z1, z2=False): zz1, zz2 = zoom_to_scaledenom(z1,z2) return """ <MaxScaleDenominator>%s</MaxScaleDenominator> <MinScaleDenominator>%s</MinScaleDenominator><!-- z%s-%s -->"""%(zz1,zz2,z1,z2) def xml_start(bgcolor="transparent"): if bgcolor != "transparent": bgcolor = nicecolor(bgcolor) return """<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE Map> <Map bgcolor="%s" srs="%s" minimum_version="0.7.1" buffer_size="512" maximum-extent="-20037508.342789244,-20037508.342780735,20037508.342789244,20037508.342780709" > """%(bgcolor, map_proj) def xml_end(): return """ </Map>""" def xml_style_start(): global substyles layer_id = get_id(1) substyles.append(layer_id) return """ <Style name="s%s">"""%(layer_id) def xml_style_end(): return """ </Style>""" def xml_rule_start(): return """ <Rule>""" def xml_rule_end(): return """ </Rule>""" def xml_hardcoded_arrows(): return """ <LineSymbolizer> <CssParameter name="stroke">#6c70d5</CssParameter> <CssParameter name="stroke-width">1</CssParameter> <CssParameter name="stroke-linejoin">bevel</CssParameter> <CssParameter name="stroke-dasharray">0,12,10,152</CssParameter> </LineSymbolizer> <LineSymbolizer> <CssParameter name="stroke">#6c70d5</CssParameter> <CssParameter name="stroke-width">2</CssParameter> <CssParameter name="stroke-linejoin">bevel</CssParameter> <CssParameter name="stroke-dasharray">0,12,9,153</CssParameter> </LineSymbolizer> <LineSymbolizer> <CssParameter name="stroke">#6c70d5</CssParameter> <CssParameter name="stroke-width">3</CssParameter> <CssParameter name="stroke-linejoin">bevel</CssParameter> <CssParameter name="stroke-dasharray">0,18,2,154</CssParameter> </LineSymbolizer> <LineSymbolizer> <CssParameter name="stroke">#6c70d5</CssParameter> <CssParameter name="stroke-width">4</CssParameter> <CssParameter name="stroke-linejoin">bevel</CssParameter> <CssParameter name="stroke-dasharray">0,18,1,155</CssParameter> </LineSymbolizer>""" def xml_layer(type="postgis", geom="point", interesting_tags = "*", sql = "true", zoom=0 ): layer_id = get_id(1) global substyles subs = "\n".join(["<StyleName>s%s</StyleName>"%i for i in substyles]) substyles = [] intersection_SQL = "" if zoom < 5: intersection_SQL = '<Parameter name="intersect_max_scale">1</Parameter>' elif zoom > 16: intersection_SQL = '<Parameter name="intersect_min_scale">500000000000</Parameter>' if type == "postgis": interesting_tags = list(interesting_tags) if '"' not in "".join(interesting_tags) and "->" not in "".join(interesting_tags): interesting_tags = "\", \"".join(interesting_tags) interesting_tags = "\""+ interesting_tags+"\"" else: interesting_tags = ", ".join(interesting_tags) return """ <Layer name="l%s" status="on" srs="%s"> %s <Datasource> <Parameter name="table"> (select %s, way from %s%s where %s ) as text </Parameter> %s <Parameter name="type">postgis</Parameter> <Parameter name="st_prefix">true</Parameter> <Parameter name="user">%s</Parameter> <Parameter name="dbname">%s</Parameter> <Parameter name="srid">%s</Parameter> <Parameter name="geometry_field">way</Parameter> <Parameter name="geometry_table">%s%s</Parameter> <Parameter name="estimate_extent">false</Parameter> <Parameter name="extent">-20037508.342789244, -20037508.342780735, 20037508.342789244, 20037508.342780709</Parameter> </Datasource> </Layer>"""%(layer_id, db_proj, subs, interesting_tags, table_prefix, geom, sql, intersection_SQL, db_user, db_name, db_srid, table_prefix, geom) elif type == "postgis-process": return """ <Layer name="l%s" status="on" srs="%s"> %s <Datasource> <Parameter name="table"> (%s ) as text </Parameter> %s <Parameter name="type">postgis</Parameter> <Parameter name="st_prefix">true</Parameter> <Parameter name="user">%s</Parameter> <Parameter name="dbname">%s</Parameter> <Parameter name="srid">%s</Parameter> <Parameter name="geometry_field">way</Parameter> <Parameter name="geometry_table">%s%s</Parameter> <Parameter name="estimate_extent">false</Parameter> <Parameter name="extent">-20037508.342789244, -20037508.342780735, 20037508.342789244, 20037508.342780709</Parameter> </Datasource> </Layer>"""%(layer_id, db_proj, subs, sql, intersection_SQL, db_user, db_name, db_srid, table_prefix, geom) elif type == "coast": if zoom < 9: return """ <Layer name="l%s" status="on" srs="%s"> %s <Datasource> <Parameter name="type">shape</Parameter> <Parameter name="file">%sshoreline_300</Parameter> </Datasource> </Layer>"""%(layer_id, db_proj, subs, world_bnd_path) else: return """ <Layer name="l%s" status="on" srs="%s"> %s <Datasource> <Parameter name="type">shape</Parameter> <Parameter name="file">%sprocessed_p</Parameter> </Datasource> </Layer>"""%(layer_id, db_proj, subs, world_bnd_path) def xml_nolayer(): global substyles substyles = [] def xml_nosubstyle(): global substyles substyles = substyles[:-1]
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of kothic, the realtime map renderer. # kothic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # kothic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with kothic. If not, see <http://www.gnu.org/licenses/>. from debug import debug, Timer from backend.vtile import QuadTileBackend as DataBackend #from backend.postgis import PostGisBackend as DataBackend #from style import Styling from mapcss import MapCSS from render import RasterTile svg = False if svg: import cairo style = MapCSS(1, 19) #zoom levels style.parse(open("styles/default.mapcss","r").read()) bbox = (27.115768874532,53.740327031764,28.028320754378,54.067187302158) w,h = 630*4,364*4 z = 10 db = DataBackend() #style = Styling() res = RasterTile(w, h, z, db) if svg: file = open("test.svg", "wb") res.surface = cairo.SVGSurface(file.name, w,h) res.update_surface(bbox, z, style) if not svg: res.surface.write_to_png("test.png") else: res.surface.finish()
Python