Beispiel #1
0
 def add_node(self, node, **kwds):
     self.debug('[app] adding node: %r', (node, kwds))
     if not kwds.pop('override', False) and \
        hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__):
         self.warn('while setting up extension %s: node class %r is '
                   'already registered, its visitors will be overridden' %
                   (self._setting_up_extension, node.__name__))
     nodes._add_node_class_names([node.__name__])
     for key, val in iteritems(kwds):
         try:
             visit, depart = val
         except ValueError:
             raise ExtensionError('Value for key %r must be a '
                                  '(visit, depart) function tuple' % key)
         translator = self._translators.get(key)
         if translator is not None:
             pass
         elif key == 'html':
             from sphinx.writers.html import HTMLTranslator as translator
         elif key == 'latex':
             from sphinx.writers.latex import LaTeXTranslator as translator
         elif key == 'text':
             from sphinx.writers.text import TextTranslator as translator
         elif key == 'man':
             from sphinx.writers.manpage import ManualPageTranslator \
                 as translator
         elif key == 'texinfo':
             from sphinx.writers.texinfo import TexinfoTranslator \
                 as translator
         else:
             # ignore invalid keys for compatibility
             continue
         setattr(translator, 'visit_' + node.__name__, visit)
         if depart:
             setattr(translator, 'depart_' + node.__name__, depart)
Beispiel #2
0
 def add_node(self, node, **kwds):
     self.debug('[app] adding node: %r', (node, kwds))
     nodes._add_node_class_names([node.__name__])
     for key, val in kwds.iteritems():
         try:
             visit, depart = val
         except ValueError:
             raise ExtensionError('Value for key %r must be a '
                                  '(visit, depart) function tuple' % key)
         if key == 'html':
             from sphinx.writers.html import HTMLTranslator as translator
         elif key == 'latex':
             from sphinx.writers.latex import LaTeXTranslator as translator
         elif key == 'text':
             from sphinx.writers.text import TextTranslator as translator
         elif key == 'man':
             from sphinx.writers.manpage import ManualPageTranslator \
                 as translator
         elif key == 'texinfo':
             from sphinx.writers.texinfo import TexinfoTranslator \
                 as translator
         else:
             # ignore invalid keys for compatibility
             continue
         setattr(translator, 'visit_' + node.__name__, visit)
         if depart:
             setattr(translator, 'depart_' + node.__name__, depart)
Beispiel #3
0
 def add_node(self, node, **kwds):
     self.debug('[app] adding node: %r', (node, kwds))
     if not kwds.pop('override', False) and \
        hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__):
         self.warn('while setting up extension %s: node class %r is '
                   'already registered, its visitors will be overridden' %
                   (self._setting_up_extension, node.__name__))
     nodes._add_node_class_names([node.__name__])
     for key, val in iteritems(kwds):
         try:
             visit, depart = val
         except ValueError:
             raise ExtensionError('Value for key %r must be a '
                                  '(visit, depart) function tuple' % key)
         translator = self._translators.get(key)
         if translator is not None:
             pass
         elif key == 'html':
             from sphinx.writers.html import HTMLTranslator as translator
         elif key == 'latex':
             from sphinx.writers.latex import LaTeXTranslator as translator
         elif key == 'text':
             from sphinx.writers.text import TextTranslator as translator
         elif key == 'man':
             from sphinx.writers.manpage import ManualPageTranslator \
                 as translator
         elif key == 'texinfo':
             from sphinx.writers.texinfo import TexinfoTranslator \
                 as translator
         else:
             # ignore invalid keys for compatibility
             continue
         setattr(translator, 'visit_'+node.__name__, visit)
         if depart:
             setattr(translator, 'depart_'+node.__name__, depart)
 def add_node(self, node, **kwds):
     self.debug("[app] adding node: %r", (node, kwds))
     nodes._add_node_class_names([node.__name__])
     for key, val in iteritems(kwds):
         try:
             visit, depart = val
         except ValueError:
             raise ExtensionError("Value for key %r must be a " "(visit, depart) function tuple" % key)
         translator = self._translators.get(key)
         if translator is not None:
             pass
         elif key == "html":
             from sphinx.writers.html import HTMLTranslator as translator
         elif key == "latex":
             from sphinx.writers.latex import LaTeXTranslator as translator
         elif key == "text":
             from sphinx.writers.text import TextTranslator as translator
         elif key == "man":
             from sphinx.writers.manpage import ManualPageTranslator as translator
         elif key == "texinfo":
             from sphinx.writers.texinfo import TexinfoTranslator as translator
         else:
             # ignore invalid keys for compatibility
             continue
         setattr(translator, "visit_" + node.__name__, visit)
         if depart:
             setattr(translator, "depart_" + node.__name__, depart)
Beispiel #5
0
 def add_node(self, node, **kwds):
     self.debug('[app] adding node: %r', (node, kwds))
     nodes._add_node_class_names([node.__name__])
     for key, val in kwds.iteritems():
         try:
             visit, depart = val
         except ValueError:
             raise ExtensionError('Value for key %r must be a '
                                  '(visit, depart) function tuple' % key)
         if key == 'html':
             from sphinx.writers.html import HTMLTranslator as translator
         elif key == 'latex':
             from sphinx.writers.latex import LaTeXTranslator as translator
         elif key == 'text':
             from sphinx.writers.text import TextTranslator as translator
         elif key == 'man':
             from sphinx.writers.manpage import ManualPageTranslator \
                 as translator
         elif key == 'texinfo':
             from sphinx.writers.texinfo import TexinfoTranslator \
                 as translator
         else:
             # ignore invalid keys for compatibility
             continue
         setattr(translator, 'visit_'+node.__name__, visit)
         if depart:
             setattr(translator, 'depart_'+node.__name__, depart)
Beispiel #6
0
 def add_node(self, node, **kwds):
     self.debug("[app] adding node: %r", (node, kwds))
     if not kwds.pop("override", False) and hasattr(nodes.GenericNodeVisitor, "visit_" + node.__name__):
         self.warn(
             "while setting up extension %s: node class %r is "
             "already registered, its visitors will be overridden" % (self._setting_up_extension, node.__name__)
         )
     nodes._add_node_class_names([node.__name__])
     for key, val in iteritems(kwds):
         try:
             visit, depart = val
         except ValueError:
             raise ExtensionError("Value for key %r must be a " "(visit, depart) function tuple" % key)
         translator = self._translators.get(key)
         if translator is not None:
             pass
         elif key == "html":
             from sphinx.writers.html import HTMLTranslator as translator
         elif key == "latex":
             from sphinx.writers.latex import LaTeXTranslator as translator
         elif key == "text":
             from sphinx.writers.text import TextTranslator as translator
         elif key == "man":
             from sphinx.writers.manpage import ManualPageTranslator as translator
         elif key == "texinfo":
             from sphinx.writers.texinfo import TexinfoTranslator as translator
         else:
             # ignore invalid keys for compatibility
             continue
         setattr(translator, "visit_" + node.__name__, visit)
         if depart:
             setattr(translator, "depart_" + node.__name__, depart)
Beispiel #7
0
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)
Beispiel #8
0
def add_node(node_name, visit_function=None, depart_function=None):
    """Register a Docutils node class.
    """
    nodes._add_node_class_names([node_name])
    if visit_function is not None:
        setattr(docutils.writers._html_base.HTMLTranslator, 'visit_' + node_name, visit_function)
    if depart_function is not None:
        setattr(docutils.writers._html_base.HTMLTranslator, 'depart_' + node_name, depart_function)
Beispiel #9
0
def register_node(node: "Type[Element]") -> None:
    """Register a node to docutils.

    This modifies global state of some visitors.  So it is better to use this
    inside ``docutils_namespace()`` to prevent side-effects.
    """
    if not hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__):
        nodes._add_node_class_names([node.__name__])  # type: ignore
        additional_nodes.add(node)
Beispiel #10
0
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)
Beispiel #11
0
def register_node(node):
    # type: (nodes.Node) -> None
    """Register a node to docutils.

    This modifies global state of some visitors.  So it is better to use this
    inside ``docutils_namespace()`` to prevent side-effects.
    """
    if not hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__):
        nodes._add_node_class_names([node.__name__])
        additional_nodes.add(node)
Beispiel #12
0
def add_node(node, **kwds):
    nodes._add_node_class_names([node.__name__])
    for key, val in kwds.items():
        try:
            visit, depart = val
        except ValueError:
            raise ExtensionError('Value for key %r must be a '
                                 '(visit, depart) function tuple' % key)

        assert key == 'html', 'accept html only'

        setattr(RST2RevealTranslator, 'visit_'+node.__name__, visit)
        setattr(RST2RevealTranslator, 'depart_'+node.__name__, depart)
Beispiel #13
0
def add_node(node, **kwds):
    nodes._add_node_class_names([node.__name__])
    for key, val in kwds.items():
        try:
            visit, depart = val
        except ValueError:
            raise ExtensionError('Value for key %r must be a '
                                 '(visit, depart) function tuple' % key)

        assert key == 'html', 'accept html only'

        setattr(RST2RevealTranslator, 'visit_' + node.__name__, visit)
        setattr(RST2RevealTranslator, 'depart_' + node.__name__, depart)
Beispiel #14
0
def register_pylatest_nodes():
    """
    Register custom pylatest nodes for test step and resutl sections.
    These custom nodes are used to wrap content of pylatest directives into div
    or span elements.
    """
    nodes._add_node_class_names(pylatest.xdocutils.nodes.node_class_names)
    for node_name in pylatest.xdocutils.nodes.node_class_names:
        visit_func_name = "visit_" + node_name
        depart_func_name = "depart_" + node_name
        setattr(HTMLTranslator, visit_func_name,
            getattr(pylatest.xdocutils.htmltranslator, visit_func_name))
        setattr(HTMLTranslator, depart_func_name,
            getattr(pylatest.xdocutils.htmltranslator, depart_func_name))
Beispiel #15
0
def register_pylatest_nodes():
    """
    Register (actually inject, this is kind of a hack) custom pylatest nodes
    into html4css1.HTMLTranslator. These custom nodes are used to wrap content
    of pylatest directives into div or span elements.
    """
    nodes._add_node_class_names(pylatest.xdocutils.nodes.node_class_names)
    for node_name in pylatest.xdocutils.nodes.node_class_names:
        visit_func_name = "visit_" + node_name
        depart_func_name = "depart_" + node_name
        setattr(HTMLTranslator, visit_func_name,
                getattr(pylatest.xdocutils.htmltranslator, visit_func_name))
        setattr(HTMLTranslator, depart_func_name,
                getattr(pylatest.xdocutils.htmltranslator, depart_func_name))
Beispiel #16
0
    def add_node(self, node, **kwds):
        # type: (nodes.Node, Any) -> None
        logger.debug('[app] adding node: %r', (node, kwds))
        if not kwds.pop('override', False) and \
           hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__):
            logger.warning(__(
                'while setting up extension %s: node class %r is '
                'already registered, its visitors will be overridden'),
                           self._setting_up_extension,
                           node.__name__,
                           type='app',
                           subtype='add_node')
        nodes._add_node_class_names([node.__name__])
        for key, val in iteritems(kwds):
            try:
                visit, depart = val
            except ValueError:
                raise ExtensionError(
                    __('Value for key %r must be a '
                       '(visit, depart) function tuple') % key)
            translator = self.registry.translators.get(key)
            translators = []
            if translator is not None:
                translators.append(translator)
            elif key == 'html':
                from sphinx.writers.html import HTMLTranslator
                translators.append(HTMLTranslator)
                if is_html5_writer_available():
                    from sphinx.writers.html5 import HTML5Translator
                    translators.append(HTML5Translator)
            elif key == 'latex':
                from sphinx.writers.latex import LaTeXTranslator
                translators.append(LaTeXTranslator)
            elif key == 'text':
                from sphinx.writers.text import TextTranslator
                translators.append(TextTranslator)
            elif key == 'man':
                from sphinx.writers.manpage import ManualPageTranslator
                translators.append(ManualPageTranslator)
            elif key == 'texinfo':
                from sphinx.writers.texinfo import TexinfoTranslator
                translators.append(TexinfoTranslator)

            for translator in translators:
                setattr(translator, 'visit_' + node.__name__, visit)
                if depart:
                    setattr(translator, 'depart_' + node.__name__, depart)
Beispiel #17
0
    def add_node(self, node, **kwds):
        """
        See :epkg:`class Sphinx`.
        """
        # type: (nodes.Node, Any) -> None
        nodes._add_node_class_names([node.__name__])
        for key, val in kwds.items():
            if not isinstance(val, tuple):
                continue
            visit, depart = val
            translator = self.writer.app.registry.translators.get(key)
            translators = []
            if translator is not None:
                translators.append(translator)
            elif key == 'html':
                from sphinx.writers.html import HTMLTranslator
                translators.append(HTMLTranslator)
                if is_html5_writer_available():
                    from sphinx.writers.html5 import HTML5Translator
                    translators.append(HTML5Translator)
            elif key == 'latex':
                try:
                    from sphinx.writers.latex import LaTeXTranslator
                except ImportError:
                    # Since sphinx 1.7.3 (circular reference).
                    import sphinx.builders.latex.transforms
                    from sphinx.writers.latex import LaTeXTranslator
                translators.append(LaTeXTranslator)
            elif key == 'text':
                from sphinx.writers.text import TextTranslator
                translators.append(TextTranslator)
            elif key == 'man':
                from sphinx.writers.manpage import ManualPageTranslator
                translators.append(ManualPageTranslator)
            elif key == 'texinfo':
                from sphinx.writers.texinfo import TexinfoTranslator
                translators.append(TexinfoTranslator)

            for translator in translators:
                setattr(translator, 'visit_' + node.__name__, visit)
                if depart:
                    setattr(translator, 'depart_' +
                            node.__name__, depart)
Beispiel #18
0
    def add_node(self, node, **kwds):
        # type: (nodes.Node, Any) -> None
        logger.debug('[app] adding node: %r', (node, kwds))
        if not kwds.pop('override', False) and \
           hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__):
            logger.warning(__('while setting up extension %s: node class %r is '
                              'already registered, its visitors will be overridden'),
                           self._setting_up_extension, node.__name__,
                           type='app', subtype='add_node')
        nodes._add_node_class_names([node.__name__])
        for key, val in iteritems(kwds):
            try:
                visit, depart = val
            except ValueError:
                raise ExtensionError(__('Value for key %r must be a '
                                        '(visit, depart) function tuple') % key)
            translator = self.registry.translators.get(key)
            translators = []
            if translator is not None:
                translators.append(translator)
            elif key == 'html':
                from sphinx.writers.html import HTMLTranslator
                translators.append(HTMLTranslator)
                if is_html5_writer_available():
                    from sphinx.writers.html5 import HTML5Translator
                    translators.append(HTML5Translator)
            elif key == 'latex':
                from sphinx.writers.latex import LaTeXTranslator
                translators.append(LaTeXTranslator)
            elif key == 'text':
                from sphinx.writers.text import TextTranslator
                translators.append(TextTranslator)
            elif key == 'man':
                from sphinx.writers.manpage import ManualPageTranslator
                translators.append(ManualPageTranslator)
            elif key == 'texinfo':
                from sphinx.writers.texinfo import TexinfoTranslator
                translators.append(TexinfoTranslator)

            for translator in translators:
                setattr(translator, 'visit_' + node.__name__, visit)
                if depart:
                    setattr(translator, 'depart_' + node.__name__, depart)
Beispiel #19
0
 def add_node(self, node, **kwds):
     nodes._add_node_class_names([node.__name__])
     for key, val in kwds.iteritems():
         try:
             visit, depart = val
         except ValueError:
             raise ExtensionError('Value for key %r must be a (visit, depart) '
                                  'function tuple' % key)
         if key == 'html':
             from sphinx.htmlwriter import HTMLTranslator as translator
         elif key == 'latex':
             from sphinx.latexwriter import LaTeXTranslator as translator
         elif key == 'text':
             from sphinx.textwriter import TextTranslator as translator
         else:
             # ignore invalid keys for compatibility
             continue
         setattr(translator, 'visit_'+node.__name__, visit)
         if depart:
             setattr(translator, 'depart_'+node.__name__, depart)
def add_node(node, **kwds):
    """add_node from Sphinx
    """
    nodes._add_node_class_names([node.__name__])
    for key, val in list(kwds.items()):
        try:
            visit, depart = val
        except ValueError:
            raise ValueError('Value for key %r must be a '
                             '(visit, depart) function tuple' % key)
        if key == 'html':
            from docutils.writers.html4css1 import HTMLTranslator as translator
        elif key == 'latex':
            from docutils.writers.latex2e import LaTeXTranslator as translator
        else:
            # ignore invalid keys for compatibility
            continue
        setattr(translator, 'visit_' + node.__name__, visit)
        if depart:
            setattr(translator, 'depart_' + node.__name__, depart)
Beispiel #21
0
def add_node(node, **kwds):
    """add_node from Sphinx
    """
    nodes._add_node_class_names([node.__name__])
    for key, val in kwds.iteritems():
        try:
            visit, depart = val
        except ValueError:
            raise ValueError('Value for key %r must be a '
                                 '(visit, depart) function tuple' % key)
        if key == 'html':
            from docutils.writers.html4css1 import HTMLTranslator as translator
        elif key == 'latex':
            from docutils.writers.latex2e import LaTeXTranslator as translator
        else:
            # ignore invalid keys for compatibility
            continue
        setattr(translator, 'visit_'+node.__name__, visit)
        if depart:
            setattr(translator, 'depart_'+node.__name__, depart)
Beispiel #22
0
def init(settings):
    """Initialise and load the docutils extensions.
    """
    directives.register_directive('sourcecode', Pygments)
    directives.register_directive('youtube', YouTube)
    directives.register_directive('quiz', Quiz)
    directives.register_directive('quiz-question', QuizQuestion)
    directives.register_directive('show-hide', ShowHideBlock)
    roles.register_local_role('asset', asset_ref_role)
    roles.register_local_role('crossref', crossref_role)
    roles.register_local_role('style', inline_css_role)
    for _, aliases, _, _ in get_all_lexers():
        for alias in aliases:
            roles.register_local_role('code-%s' % (alias),
                                      inline_pygments_role)
    nodes._add_node_class_names([HtmlElementBlock.__name__])
    setattr(HTMLTranslator, 'visit_%s' % HtmlElementBlock.__name__,
            visit_htmlelementblock)
    setattr(HTMLTranslator, 'depart_%s' % HtmlElementBlock.__name__,
            depart_htmlelementblock)
class toctree(nodes.General, nodes.Element):
    pass


# centered
class centered(nodes.Part, nodes.Element):
    pass


# pending xref
class pending_xref(nodes.Element):
    pass


# compact paragraph -- never makes a <p>
class compact_paragraph(nodes.paragraph):
    pass


# sets the highlighting language for literal blocks
class highlightlang(nodes.Element):
    pass


# make them known to docutils. this is needed, because the HTMl writer
# will choke at some point if these are not added
nodes._add_node_class_names("""index desc desc_content desc_signature
      desc_classname desc_name desc_parameterlist desc_parameter desc_optional
      centered versionmodified seealso productionlist production toctree
      pending_xref compact_paragraph highlightlang""".split())
Beispiel #24
0
        self.body.append(self.starttag(node, 'abbr', '', **attrs))

    def depart_abbreviation(self, node):
        self.body.append('</abbr>')

    def visit_kbd(self, node):
        self.body.append(self.starttag(node, 'kbd', ''))

    def depart_kbd(self, node):
        self.body.append('</kbd>')


class kbd(nodes.Inline, nodes.TextElement):
    """Node for kbd element"""

nodes._add_node_class_names('kbd')

def inline_roles(role, raw, text, *args):
    if role == 'kbd':
        return [kbd('kbd', text)], []
    elif role == 'var':
        return [nodes.literal('var', text)], []

roles.register_local_role('kbd', inline_roles)
roles.register_local_role('var', inline_roles)

# FIXME: this has to be lowercase for some reason
class abbreviation(nodes.Inline, nodes.TextElement):
    """Node for abbreviations with explanations."""

nodes._add_node_class_names('abbreviation')
Beispiel #25
0
from docutils import nodes as basenodes


class Abbreviation(basenodes.Inline, basenodes.TextElement): pass
class Url(basenodes.Inline, basenodes.TextElement): pass
class File(basenodes.Inline, basenodes.TextElement): pass
class Command(basenodes.Inline, basenodes.TextElement): pass

basenodes._add_node_class_names(["Abbreviation", "Url", "File", "Command"])
Beispiel #26
0
    pass


# module declaration
class module(nodes.Element):
    pass


# start of a file, used in the LaTeX builder only
class start_of_file(nodes.Element):
    pass


# tabular column specification, used for the LaTeX writer
class tabular_col_spec(nodes.Element):
    pass


# meta directive -- same as docutils' standard meta node, but pickleable
class meta(nodes.Special, nodes.PreBibliographic, nodes.Element):
    pass


# make them known to docutils. this is needed, because the HTML writer
# will choke at some point if these are not added
nodes._add_node_class_names("""index desc desc_content desc_signature desc_type
      desc_addname desc_name desc_parameterlist desc_parameter desc_optional
      centered versionmodified seealso productionlist production toctree
      pending_xref compact_paragraph highlightlang literal_emphasis
      glossary acks module start_of_file tabular_col_spec meta""".split())
Beispiel #27
0
                # Allow breaks at whitespace:
                self.body.append(token)
            else:
                # Protect runs of multiple spaces; the last space can wrap:
                self.body.append('&nbsp;' * (len(token) - 1) + ' ')
        self.body.append('</code>')
        # Content already processed:
        raise nodes.SkipNode

    def depart_literal(self, node):
        # skipped unless literal element is from "code" role:
        self.body.append('</code>')


class kbd(nodes.Inline, nodes.TextElement):
    """Node for kbd element"""


def inline_roles(role, raw, text, *args):
    if role == 'kbd':
        return [kbd('kbd', text)], []


nodes._add_node_class_names('kbd')
roles.register_local_role('kbd', inline_roles)

if __name__ == '__main__':
    import sys
    parts = publish_parts(writer=Writer(), source=open(sys.argv[1]).read())
    print(parts['html_body'])
Beispiel #28
0
    def add_node(self, node, **kwds):
        # type: (nodes.Node, Any) -> None
        """Register a Docutils node class.

        This is necessary for Docutils internals.  It may also be used in the
        future to validate nodes in the parsed documents.

        Node visitor functions for the Sphinx HTML, LaTeX, text and manpage
        writers can be given as keyword arguments: the keyword should be one or
        more of ``'html'``, ``'latex'``, ``'text'``, ``'man'``, ``'texinfo'``
        or any other supported translators, the value a 2-tuple of ``(visit,
        depart)`` methods.  ``depart`` can be ``None`` if the ``visit``
        function raises :exc:`docutils.nodes.SkipNode`.  Example:

        .. code-block:: python

           class math(docutils.nodes.Element): pass

           def visit_math_html(self, node):
               self.body.append(self.starttag(node, 'math'))
           def depart_math_html(self, node):
               self.body.append('</math>')

           app.add_node(math, html=(visit_math_html, depart_math_html))

        Obviously, translators for which you don't specify visitor methods will
        choke on the node when encountered in a document to translate.

        .. versionchanged:: 0.5
           Added the support for keyword arguments giving visit functions.
        """
        logger.debug('[app] adding node: %r', (node, kwds))
        if not kwds.pop('override', False) and \
           hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__):
            logger.warning(__('while setting up extension %s: node class %r is '
                              'already registered, its visitors will be overridden'),
                           self._setting_up_extension, node.__name__,
                           type='app', subtype='add_node')
        nodes._add_node_class_names([node.__name__])
        for key, val in iteritems(kwds):
            try:
                visit, depart = val
            except ValueError:
                raise ExtensionError(__('Value for key %r must be a '
                                        '(visit, depart) function tuple') % key)
            translator = self.registry.translators.get(key)
            translators = []
            if translator is not None:
                translators.append(translator)
            elif key == 'html':
                from sphinx.writers.html import HTMLTranslator
                translators.append(HTMLTranslator)
                if is_html5_writer_available():
                    from sphinx.writers.html5 import HTML5Translator
                    translators.append(HTML5Translator)
            elif key == 'latex':
                from sphinx.writers.latex import LaTeXTranslator
                translators.append(LaTeXTranslator)
            elif key == 'text':
                from sphinx.writers.text import TextTranslator
                translators.append(TextTranslator)
            elif key == 'man':
                from sphinx.writers.manpage import ManualPageTranslator
                translators.append(ManualPageTranslator)
            elif key == 'texinfo':
                from sphinx.writers.texinfo import TexinfoTranslator
                translators.append(TexinfoTranslator)

            for translator in translators:
                setattr(translator, 'visit_' + node.__name__, visit)
                if depart:
                    setattr(translator, 'depart_' + node.__name__, depart)
Beispiel #29
0
 def setup():
     'add support for math to docutils'
     nodes._add_node_class_names(['math', 'displaymath', 'eqref'])
     roles.register_local_role('math', math_role)
     roles.register_local_role('eq', eq_role)
     directives.register_directive('math', directive_dwim(MathDirective2))
Beispiel #30
0
        self.body.append(self.starttag(node, 'abbr', '', **attrs))

    def depart_abbreviation(self, node):
        self.body.append('</abbr>')

    def visit_kbd(self, node):
        self.body.append(self.starttag(node, 'kbd', ''))

    def depart_kbd(self, node):
        self.body.append('</kbd>')


class kbd(nodes.Inline, nodes.TextElement):
    """Node for kbd element"""

nodes._add_node_class_names('kbd')


def inline_roles(role, raw, text, *args):
    if role == 'kbd':
        return [kbd('kbd', text)], []
    elif role == 'var':
        return [nodes.literal('var', text)], []


roles.register_local_role('kbd', inline_roles)
roles.register_local_role('var', inline_roles)


# FIXME: this has to be lowercase for some reason
class abbreviation(nodes.Inline, nodes.TextElement):
Beispiel #31
0
    pass


class source(nodes.General, nodes.Inline, nodes.Element):
    pass


class video(nodes.image):
    pass


class track(nodes.General, nodes.Inline, nodes.Element):
    pass


nodes._add_node_class_names(('audio', 'source', 'video', 'track'))
"""
Create base class 'Media'.
This is the parent class to the Audio, Video and Image directives.
"""


class Media(
        Directive
):  # just define shared options and useful functions. Doesn't actually create nodes.
    messages = []
    contraindications = ('align', 'height', 'scale', 'width', 'no_fullscreen')
    crossorigin = True

    def style_check(arg):
        if arg and arg.strip():
Beispiel #32
0
class compact_paragraph(nodes.paragraph): pass

# for the ACKS list
class acks(nodes.Element): pass

# sets the highlighting language for literal blocks
class highlightlang(nodes.Element): pass

# like emphasis, but doesn't apply further text processors, e.g. smartypants
class literal_emphasis(nodes.emphasis): pass

# glossary
class glossary(nodes.Element): pass

# module declaration
class module(nodes.Element): pass

# start of a file, used in the LaTeX builder only
class start_of_file(nodes.Element): pass

# tabular column specification, used for the LaTeX writer
class tabular_col_spec(nodes.Element): pass

# make them known to docutils. this is needed, because the HTML writer
# will choke at some point if these are not added
nodes._add_node_class_names("""index desc desc_content desc_signature desc_type
      desc_addname desc_name desc_parameterlist desc_parameter desc_optional
      centered versionmodified seealso productionlist production toctree
      pending_xref compact_paragraph highlightlang literal_emphasis
      glossary acks module start_of_file tabular_col_spec""".split())
Beispiel #33
0
 def add_node(self, node):
     nodes._add_node_class_names([node.__name__])
Beispiel #34
0
        # Assume image paths are relative to the container
        for node in doctree.traverse(condition=nodes.image):
            reference = get_reference(node['uri'].encode('utf_8'))
            # Skip external
            if is_external(reference):
                continue
            # Strip the view
            path = reference.path
            if path[-1][0] == ';':
                path = path[:-1]
            # Resolve absolute path
            resource = parent.get_resource(path, soft=True)
            if resource is not None:
                node['uri'] = str(resource.abspath)

        return doctree


    def get_book(self):
        doctree = self.get_doctree()
        return doctree.next_node(condition=nodes.book)



# Register dummy book directive for ODT export
nodes._add_node_class_names(['book'])
nodes.book = book
register_directive('book', Book)
labels['book'] = ''
Beispiel #35
0
def add_node(node, **kwds):
    nodes._add_node_class_names([node.__name__])
Beispiel #36
0
def add_node(node, **kwds):
    nodes._add_node_class_names([node.__name__])
Beispiel #37
0
	def setup():
		'add support for math to docutils'
		nodes._add_node_class_names(['math', 'displaymath', 'eqref'])
		roles.register_local_role('math', math_role)
		roles.register_local_role('eq', eq_role)
		directives.register_directive('math', directive_dwim(MathDirective2))
Beispiel #38
0

class download_reference(nodes.reference):
    """Node for download references, similar to pending_xref."""


class literal_emphasis(nodes.emphasis):
    """Node that behaves like `emphasis`, but further text processors are not
    applied (e.g. smartypants for HTML output).
    """


class literal_strong(nodes.strong):
    """Node that behaves like `strong`, but further text processors are not
    applied (e.g. smartypants for HTML output).
    """


class abbreviation(nodes.Inline, nodes.TextElement):
    """Node for abbreviations with explanations."""


class termsep(nodes.Structural, nodes.Element):
    """Separates two terms within a <term> node."""


# make the new nodes known to docutils; needed because the HTML writer will
# choke at some point if these are not added
nodes._add_node_class_names(k for k in globals().keys()
                            if k != 'nodes' and k[0] != '_')
Beispiel #39
0
    information about all documents.

    These nodes are resolved before writing output, in
    BuildEnvironment.resolve_references.
    """

class download_reference(nodes.reference):
    """Node for download references, similar to pending_xref."""

class literal_emphasis(nodes.emphasis):
    """Node that behaves like `emphasis`, but further text processors are not
    applied (e.g. smartypants for HTML output).
    """

class literal_strong(nodes.strong):
    """Node that behaves like `strong`, but further text processors are not
    applied (e.g. smartypants for HTML output).
    """

class abbreviation(nodes.Inline, nodes.TextElement):
    """Node for abbreviations with explanations."""

class termsep(nodes.Structural, nodes.Element):
    """Separates two terms within a <term> node."""


# make the new nodes known to docutils; needed because the HTML writer will
# choke at some point if these are not added
nodes._add_node_class_names(k for k in globals().keys()
                            if k != 'nodes' and k[0] != '_')
Beispiel #40
0
class versionmodified(nodes.Admonition, nodes.TextElement): pass

# seealso
class seealso(nodes.Admonition, nodes.Element): pass

# productionlist
class productionlist(nodes.Admonition, nodes.Element): pass
class production(nodes.Part, nodes.Inline, nodes.TextElement): pass

# toc tree
class toctree(nodes.General, nodes.Element): pass

# centered
class centered(nodes.Part, nodes.Element): pass

# pending xref
class pending_xref(nodes.Element): pass

# compact paragraph -- never makes a <p>
class compact_paragraph(nodes.paragraph): pass

# sets the highlighting language for literal blocks
class highlightlang(nodes.Element): pass

# make them known to docutils. this is needed, because the HTMl writer
# will choke at some point if these are not added
nodes._add_node_class_names("""index desc desc_content desc_signature
      desc_classname desc_name desc_parameterlist desc_parameter desc_optional
      centered versionmodified seealso productionlist production toctree
      pending_xref compact_paragraph highlightlang""".split())
Beispiel #41
0
  generic_docroles = sroles.generic_docroles
  specific_docroles = sroles.specific_docroles

  for rolename, nodeclass in generic_docroles.items():
    generic = roles.GenericRole(rolename, nodeclass)
    role = roles.CustomRole(rolename, generic, {'classes': [rolename]})
    roles.register_local_role(rolename, role)

  for rolename, func in specific_docroles.items():
      roles.register_local_role(rolename, func)


  print [k for k in dir(addnodes) if k != 'nodes' and k[0] != '_']

  nodes._add_node_class_names(k for k in dir(addnodes) if k != 'nodes' and k[0] != '_')



  def dummy_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    return [], []


def test():
  register_sphinx_support()
  writer = MyWriter()
  fname = os.path.join(os.path.dirname(__file__), '..', 'README.rst')
  output = core.publish_file(source_path=fname, writer=writer)

  print output