Ejemplo n.º 1
0
def pybabel():
    # This registers our minimal robot translation extractor
    import babel.messages.extract

    babel.messages.extract.DEFAULT_MAPPING.extend(
        [
            ("**.rst", "plone.app.robotframework.pybabel:extract_robot"),
            ("**.robot", "plone.app.robotframework.pybabel:extract_robot"),
        ]
    )

    # This code hides warnings for known Sphinx-only-directives when
    # executing pybot against Sphinx-documentation:
    from docutils.parsers.rst.directives import register_directive
    from docutils.parsers.rst.roles import register_local_role

    dummy_directive = lambda *args: []
    options = ("maxdepth", "creates", "numbered", "hidden")
    setattr(dummy_directive, "content", True)
    setattr(dummy_directive, "options", dict([(opt, str) for opt in options]))
    register_directive("toctree", dummy_directive)
    register_directive("robotframework", dummy_directive)
    register_local_role("ref", dummy_directive)

    from babel.messages.frontend import main

    main()
Ejemplo n.º 2
0
def setup(app):
    app.add_config_value('autonumber_by_chapter', True, False)
    roles.register_local_role('autonumber', autonumber_role)
    app.add_node(autonumber)
    app.add_node(autonumber_ref)
    app.add_role('autonumref', XRefRole(nodeclass=autonumber_ref))
    app.connect('doctree-resolved', doctree_resolved)
Ejemplo n.º 3
0
 def add_crossref_type(self, directivename, rolename, indextemplate='',
                       ref_nodeclass=None):
     additional_xref_types[directivename] = (rolename, indextemplate, None)
     directives.register_directive(directivename, directive_dwim(Target))
     roles.register_local_role(rolename, xfileref_role)
     if ref_nodeclass is not None:
         innernodetypes[rolename] = ref_nodeclass
Ejemplo n.º 4
0
 def add_role(self, name, role):
     self.debug('[app] adding role: %r', (name, role))
     if name in roles._roles:
         self.warn('while setting up extension %s: role %r is '
                   'already registered, it will be overridden' %
                   (self._setting_up_extension[-1], name))
     roles.register_local_role(name, role)
Ejemplo n.º 5
0
def _override_command_role():
    from docutils.parsers.rst import roles
    from docutils import nodes
    rolename = 'cmd'
    generic = roles.GenericRole(rolename, nodes.literal)
    role = roles.CustomRole(rolename, generic, {'classes': [rolename]})
    roles.register_local_role(rolename, role)
Ejemplo n.º 6
0
def setup(app):
    roles.register_local_role('xml', xml_role)

    return {
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
Ejemplo n.º 7
0
def add_literal_role(rolename):
    from docutils.parsers.rst import roles
    from docutils import nodes
    nodeclass = nodes.literal
    generic = roles.GenericRole(rolename, nodeclass)
    role = roles.CustomRole(rolename, generic, {'classes': [rolename]})
    roles.register_local_role(rolename, role)
Ejemplo n.º 8
0
 def set_site(self, site):
     """Set Nikola site."""
     self.site = site
     roles.register_local_role('issue', IssueRole)
     global ISSUE_URL
     IssueRole.site = site
     return super(Plugin, self).set_site(site)
Ejemplo n.º 9
0
    def format(self, decl):

        def ref(name, rawtext, text, lineno, inliner,
                options={}, content=[]):

            name = utils.unescape(text)
            uri = self.lookup_symbol(name, decl.name[:-1])
            if uri:
                node = reference(rawtext, name, refid=uri, **options)
            else:
                node = emphasis(rawtext, name)
            return [node], []

        roles.register_local_role('', ref)

        errstream = StringIO.StringIO()
        settings = {}
        settings['halt_level'] = 2
        settings['warning_stream'] = errstream
        settings['traceback'] = True

        doc = decl.annotations.get('doc')
        if doc:
            try:
                doctree = publish_doctree(doc.text, settings_overrides=settings)
                # Extract the summary.
                extractor = SummaryExtractor(doctree)
                doctree.walk(extractor)

                reader = docutils.readers.doctree.Reader(parser_name='null')

                # Publish the summary.
                if extractor.summary:
                    pub = Publisher(reader, None, None,
                                    source=io.DocTreeInput(extractor.summary),
                                    destination_class=io.StringOutput)
                    pub.writer = Writer()
                    pub.process_programmatic_settings(None, None, None)
                    dummy = pub.publish(enable_exit_status=None)
                    summary = pub.writer.output
                else:
                    summary = ''
                
                # Publish the details.
                pub = Publisher(reader, None, None,
                                source=io.DocTreeInput(doctree),
                                destination_class=io.StringOutput)
                pub.writer = Writer()
                pub.process_programmatic_settings(None, None, None)
                dummy = pub.publish(enable_exit_status=None)
                details = pub.writer.output
                
                return Struct(summary, details)

            except docutils.utils.SystemMessage, error:
                xx, line, message = str(error).split(':', 2)
                print 'In DocString attached to declaration at %s:%d:'%(decl.file.name,
                                                                        decl.line)
                print '  line %s:%s'%(line, message)
Ejemplo n.º 10
0
def setup(app):
    from docutils.parsers.rst import roles
    roles.register_local_role('eval', eval_role)

    return {
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
Ejemplo n.º 11
0
def register_role(name, role):
    # type: (str, RoleFunction) -> None
    """Register a role to docutils.

    This modifies global state of docutils.  So it is better to use this
    inside ``docutils_namespace()`` to prevent side-effects.
    """
    roles.register_local_role(name, role)
Ejemplo n.º 12
0
def setup(app):
    # register our handler to overrride sphinx.roles.emph_literal_role
    from docutils.parsers.rst import roles
    import sphinx.roles as mod

    names = [key for key, value in mod.specific_docroles.items() if value is mod.emph_literal_role]
    for name in names:
        roles.register_local_role(name, emph_literal_role)
Ejemplo n.º 13
0
def setup(app):
    app.add_node(IconNode, html=(IconNode.visit_icon, IconNode.depart_icon))
    roles.register_local_role('icon', icon_role)

    return {
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
Ejemplo n.º 14
0
 def add_role(self, name, role):
     self.debug("[app] adding role: %r", (name, role))
     if name in roles._roles:
         self.warn(
             "while setting up extension %s: role %r is "
             "already registered, it will be overridden" % (self._setting_up_extension, name)
         )
     roles.register_local_role(name, role)
Ejemplo n.º 15
0
def setup(app):
    roles.register_local_role(
        'symbol', SymbolRole(warn_dangling=True, innernodeclass=literal))

    return {
        'version': '1.0',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
Ejemplo n.º 16
0
def setup(_):
    from docutils.parsers.rst import roles
    roles.register_local_role('djangosetting', django_setting_role)

    return {
        'version': 'builtin',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
Ejemplo n.º 17
0
 def add_description_unit(self, directivename, rolename, indextemplate='',
                          parse_node=None, ref_nodeclass=None):
     additional_xref_types[directivename] = (rolename, indextemplate,
                                             parse_node)
     directives.register_directive(directivename,
                                   directive_dwim(GenericDesc))
     roles.register_local_role(rolename, xfileref_role)
     if ref_nodeclass is not None:
         innernodetypes[rolename] = ref_nodeclass
Ejemplo n.º 18
0
def _define_role(name):

    base_role = roles.generic_custom_role

    role = roles.CustomRole(name, base_role, {'class': [name]}, [])



    roles.register_local_role(name, role)
Ejemplo n.º 19
0
 def add_role(self, name, role):
     # type: (unicode, Any) -> None
     logger.debug('[app] adding role: %r', (name, role))
     if name in roles._roles:
         logger.warning(__('while setting up extension %s: role %r is '
                           'already registered, it will be overridden'),
                        self._setting_up_extension[-1], name,
                        type='app', subtype='add_role')
     roles.register_local_role(name, role)
Ejemplo n.º 20
0
def setup(app):
    from docutils.parsers.rst import roles

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

    for rolename, func in iteritems(specific_docroles):
        roles.register_local_role(rolename, func)
Ejemplo n.º 21
0
 def add_generic_role(self, name, nodeclass):
     # don't use roles.register_generic_role because it uses
     # register_canonical_role
     self.debug('[app] adding generic role: %r', (name, nodeclass))
     if name in roles._roles:
         self.warn('while setting up extension %s: role %r is '
                   'already registered, it will be overridden' %
                   (self._setting_up_extension[-1], name))
     role = roles.GenericRole(name, nodeclass)
     roles.register_local_role(name, role)
Ejemplo n.º 22
0
def setup(app):
    from docutils.parsers.rst import roles
    setup_man_pages(app)
    app.add_builder(EPUBHelpBuilder)
    app.add_builder(LaTeXHelpBuilder)
    app.connect('source-read', source_read_handler)
    app.connect('doctree-read', substitute)
    app.connect('builder-inited', generate_docs)
    app.connect('html-page-context', add_html_context)
    app.connect('build-finished', finished)
    roles.register_local_role('guilabel', guilabel_role)
Ejemplo n.º 23
0
 def add_generic_role(self, name, nodeclass):
     # type: (unicode, Any) -> None
     # don't use roles.register_generic_role because it uses
     # register_canonical_role
     logger.debug('[app] adding generic role: %r', (name, nodeclass))
     if name in roles._roles:
         logger.warning(__('while setting up extension %s: role %r is '
                           'already registered, it will be overridden'),
                        self._setting_up_extension[-1], name,
                        type='app', subtype='add_generic_role')
     role = roles.GenericRole(name, nodeclass)
     roles.register_local_role(name, role)
Ejemplo n.º 24
0
def setup(app):
# ==============================================================================

    app.add_directive("flat-table", FlatTable)
    roles.register_local_role('cspan', c_span)
    roles.register_local_role('rspan', r_span)

    return dict(
        version = __version__,
        parallel_read_safe = True,
        parallel_write_safe = True
    )
Ejemplo n.º 25
0
 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 as 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 as detail:
             error = self.state_machine.reporter.error(
                 'Invalid argument for "%s" directive:\n%s.'
                 % (self.name, SafeString(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
Ejemplo n.º 26
0
def gammapy_sphinx_ext_activate():
    if HAS_GP_EXTRA:
        log.info('*** Found GAMMAPY_EXTRA = {}'.format(gammapy_extra_path))
        log.info('*** Nice!')
    else:
        log.info('*** gammapy-extra *not* found.')
        log.info('*** Set the GAMMAPY_EXTRA environment variable!')
        log.info('*** Docs build will be incomplete.')
        log.info('*** Notebook links will not be verified.')

    # Register our directives and roles with Sphinx
    register_directive('gp-extra-image', ExtraImage)
    roles.register_local_role('gp-extra-notebook', notebook_role)
Ejemplo n.º 27
0
def setup(app):

    app.add_node(eqt,
                 html = (visit_eqt_node,
                         depart_eqt_node))

    app.add_directive("eqt", Equestion)
    app.add_directive("eqt-fib", Equestion)
    app.add_directive("eqt-mc", Equestion)

    roles.register_local_role('eqt', eqt_answer)

    app.add_node(eqt_answer_type,
                 html = (visit_eqt_answer_type_node,
                         depart_eqt_answer_type_node))
Ejemplo n.º 28
0
    def gen_man_page(self, name, rst):
        from docutils.writers import manpage
        from docutils.core import publish_string
        from docutils.nodes import inline
        from docutils.parsers.rst import roles

        def issue(name, rawtext, text, lineno, inliner, options={}, content=[]):
            return [inline(rawtext, '#' + text)], []

        roles.register_local_role('issue', issue)
        # We give the source_path so that docutils can find relative includes
        # as-if the document where located in the docs/ directory.
        man_page = publish_string(source=rst, source_path='docs/%s.rst' % name, writer=manpage.Writer())
        with open('docs/man/%s.1' % name, 'wb') as fd:
            fd.write(man_page)
Ejemplo n.º 29
0
def pybot():
    # This code hides warnings for known Sphinx-only-directives when
    # executing pybot against Sphinx-documentation:
    from docutils.parsers.rst.directives import register_directive
    from docutils.parsers.rst.roles import register_local_role
    dummy_directive = lambda *args: []
    options = ('maxdepth', 'creates', 'numbered', 'hidden')
    setattr(dummy_directive, 'content', True)
    setattr(dummy_directive, 'options', dict([(opt, str) for opt in options]))
    register_directive('toctree', dummy_directive)
    register_directive('robotframework', dummy_directive)
    register_local_role('ref', dummy_directive)

    # Run pybot
    run_cli(sys.argv[1:])
Ejemplo n.º 30
0
def pybot():
    # This code hides warnings for known Sphinx-only-directives when
    # executing pybot against Sphinx-documentation:
    from docutils.parsers.rst.directives import register_directive
    from docutils.parsers.rst.roles import register_local_role

    dummy_directive = lambda *args: []
    options = ("maxdepth", "creates", "numbered", "hidden")
    setattr(dummy_directive, "content", True)
    setattr(dummy_directive, "options", dict([(opt, str) for opt in options]))
    register_directive("toctree", dummy_directive)
    register_directive("robotframework", dummy_directive)
    register_local_role("ref", dummy_directive)

    # Run pybot
    run_cli(sys.argv[1:])
Ejemplo n.º 31
0
 def add_role(self, name, role):
     self.debug('adding role: %r', (name, role))
     roles.register_local_role(name, role)
Ejemplo n.º 32
0
        # Get the resolver from the register and create an url from it.
        try:
            url = api_register[name].get_url(text)
        except IndexError, exc:
            msg = inliner.reporter.warning(str(exc), line=lineno)
            if problematic:
                prb = inliner.problematic(rawtext, text, msg)
                return [prb], [msg]
            else:
                return [node], []

        if url is not None:
            node = nodes.reference(rawtext, '', node, refuri=url, **options)
        return [node], []

    roles.register_local_role(name, resolve_api_name)


# { Command line parsing
#  --------------------


def split_name(value):
    """
    Split an option in form ``NAME:VALUE`` and check if ``NAME`` exists.
    """
    parts = value.split(':', 1)
    if len(parts) != 2:
        raise OptionValueError(
            "option value must be specified as NAME:VALUE; got '%s' instead" %
            value)
Ejemplo n.º 33
0
def register():
    roles.register_local_role('fa', fa)
Ejemplo n.º 34
0
    def set_site(self, site):
        self.site = site
        roles.register_local_role('pep', pep_role)
        roles.register_local_role('rfc', rfc_role)
        roles.register_local_role('term', term_role)
        roles.register_local_role('option', option_role)
        roles.register_local_role('ref', ref_role)
        roles.register_local_role('eq', eq_role)

        # This is copied almost verbatim from Sphinx
        generic_docroles = {
            'command': nodes.strong,
            'dfn': nodes.emphasis,
            'envvar': nodes.literal,
            'kbd': nodes.literal,
            'mailheader': nodes.emphasis,
            'makevar': nodes.strong,
            'manpage': nodes.emphasis,
            'mimetype': nodes.emphasis,
            'newsgroup': nodes.emphasis,
            'program': nodes.strong,
            'regexp': nodes.literal,
        }

        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)

        specific_docroles = {
            'guilabel': menusel_role,
            'menuselection': menusel_role,
            'file': emph_literal_role,
            'samp': emph_literal_role,
            'abbr': abbr_role,
        }

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

        # Handle abbr title
        add_node(abbreviation, visit_abbreviation, depart_abbreviation)

        for name, (base_url, prefix) in self.site.config.get('EXTLINKS',
                                                             {}).items():
            roles.register_local_role(name, make_link_role(base_url, prefix))

        directives.register_directive('deprecated', VersionChange)
        directives.register_directive('versionadded', VersionChange)
        directives.register_directive('versionchanged', VersionChange)
        directives.register_directive('centered', Centered)
        directives.register_directive('hlist', HList)
        directives.register_directive('seealso', SeeAlso)
        directives.register_directive('glossary', Glossary)
        directives.register_directive('option', Option)
        directives.register_directive('math', Math)

        site.rst_transforms.append(Today)

        return super(Plugin, self).set_site(site)
A Docutils Publisher script for the Legal Resource Registry
"""

import re, os, os.path, sys

try:
    import locale
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

pth = os.path.split(sys.argv[0])[0]
pth = os.path.join(pth, "..")
pth = os.path.abspath(pth)

from docutils.core import publish_cmdline, default_description
from docutils.parsers.rst import directives, roles, states
from docutils import nodes, statemachine
from LRR import *

directives.register_directive("bubble", BubbleDirective)
directives.register_directive("variation", VariationDirective)
directives.register_directive("reporter", ReporterDirective)
directives.register_directive("fields", FieldsDirective)
directives.register_directive("jurisdiction", JurisdictionDirective)
directives.register_directive("court", CourtDirective)
directives.register_directive("breadcrumb", BreadcrumbDirective)
directives.register_directive("tab", TabDirective)
directives.register_directive("floater", FloaterDirective)
roles.register_local_role("trans", role_trans)
Ejemplo n.º 36
0
    def visit_literal_block(self, node):
        "No classes please"
        self.body.append(self.starttag(node, 'pre', ''))

    def visit_literal(self, node):
        self.body.append(self.starttag(node, 'code', ''))

    def depart_literal(self, node):
        self.body.append('</code>')


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


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

if __name__ == '__main__':
    import sys
    parts = publish_parts(writer=MyHTMLWriter(),
                          source=open(sys.argv[1]).read())
    print parts['html_body']
Ejemplo n.º 37
0
def register():
    roles.register_local_role('shields-full', shields_full)
    roles.register_local_role('shields-python', shields_python)
    roles.register_local_role('shields-jenkins', shields_jenkins)
Ejemplo n.º 38
0
def setup(app):
    # ==============================================================================

    app.add_directive("flat-table", FlatTable)
    roles.register_local_role('cspan', c_span)
    roles.register_local_role('rspan', r_span)
Ejemplo n.º 39
0
        try:
            rfcnum = int(text)
        except ValueError:
            msg = inliner.reporter.error('invalid RFC number %s' % text,
                                         line=lineno)
            prb = inliner.problematic(rawtext, rawtext, msg)
            return [prb], [msg]
        ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum
        sn = nodes.strong('RFC ' + text, 'RFC ' + text)
        rn = nodes.reference('', '', refuri=ref)
        rn += sn
        return [targetnode, rn], []


roles.register_canonical_role('envvar', indexmarkup_role)
roles.register_local_role('pep', indexmarkup_role)
roles.register_local_role('rfc', indexmarkup_role)

# default is `literal`
innernodetypes = {
    'ref': nodes.emphasis,
    'token': nodes.strong,
}


def xfileref_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    env = inliner.document.settings.env
    text = utils.unescape(text)
    # 'token' is the default role inside 'productionlist' directives
    if typ == '':
        typ = 'token'
Ejemplo n.º 40
0
     author, 'RTIRoutingServiceTransformField', 'An basic transformation that simplifies implementation of transformations for RTI Routing Service in C.',
     'Routing'),
]

# -- Custom roles
from docutils import nodes

def role_litrep(name, rawtext, text, lineno, inliner,
            options={}, content=[]):

    node = nodes.Text(text)
    node.source, node.line = inliner.reporter.get_source_and_line(lineno)
    return [node],[]

from docutils.parsers.rst import roles
roles.register_local_role('litrep', role_litrep)

rst_epilog = """
.. |version| replace:: {0}
.. |project| replace:: {1}
""".format(version, project)


# -- links
extlinks = {'link_cmocka': (LINK_CMOCKA + '%s', 'link_cmocka'),
            'link_xml_spec':
                (LINK_XML_SPEC + '%s',
                'link_xml_spec_text'),
            'link_udpv4_properties':
                    (LINK_UDPV4_PROPERTIES + '%s',
                    'link_udpv4_config '),
Ejemplo n.º 41
0
    link = nodes.reference(rawtext, '#' + issue_no, refuri=ref, **options)
    ret = [link]
    # Additional 'new-style changelog' stuff
    if name in issue_types:
        which = '[<span class="changelog-%s">%s</span>]' % (name,
                                                            name.capitalize())
        ret = [
            nodes.raw(text=which, format='html'),
            nodes.inline(text=" "), link,
            nodes.inline(text=":")
        ]
    return ret, []


for x in issue_types + ('issue', ):
    roles.register_local_role(x, issues_role)

# Also ripped from Fabric, but we need to nail down the versioning and release process for Trigger before we start to use this.
'''
year_arg_re = re.compile(r'^(.+?)\s*(?<!\x00)<(.*?)>$', re.DOTALL)
def release_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """
    Invoked as :release:`N.N.N <YYYY-MM-DD>`.

    Turns into: <b>YYYY-MM-DD</b>: released <b><a>Trigger N.N.N</a></b>, with
    the link going to the Github source page for the tag.
    """
    # Make sure year has been specified
    match = year_arg_re.match(text)
    if not match:
        msg = inliner.reporter.error("Must specify release date!")
Ejemplo n.º 42
0
class math_node(General, Inline, Element):
    children = ()

    def __init__(self, rawsource='', label=None, *children, **attributes):
        self.rawsource = rawsource
        self.math_data = attributes['latex']
        self.label = label
        Element.__init__(self, rawsource, *children, **attributes)


def math_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    latex = utils.unescape(text, restore_backslashes=True)
    return [math_node(latex, latex=latex)], []

roles.register_local_role('math', math_role)

class eq_node(Inline, Element):
    def __init__(self, rawsource='', label=None, *children, **attributes):
        self.label=label
        Element.__init__(self, rawsource, *children, **attributes)

def eq_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    return [eq_node(label=text)],[]

roles.register_local_role('eq', eq_role)


class HandleMath(basenodehandler.NodeHandler, math_node):
    def gather_elements(self, client, node, style):
        return [math_flowable.Math(node.math_data,node.label)]
Ejemplo n.º 43
0
default_settings = docutils.frontend.OptionParser(
    components=(docutils.parsers.rst.Parser, )).get_default_values()
parser = docutils.parsers.rst.Parser()


def reet_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
    """"""
    # Once nested inline markup is implemented, this and other methods should
    # recursively call inliner.nested_parse().
    options["classes"] = "reet"
    return [nodes.inline(rawtext, docutils.utils.unescape(text),
                         **options)], []


# register_generic_role('reet', nodes.literal)
roles.register_local_role("reet", reet_role)

document = docutils.utils.new_document("katse", default_settings)

src = """
.. note:: This is a ``note`` admonition.
   This is the second line of the first paragraph.

   - The note contains all indented body elements
     following.
   - It includes this bullet list.
"""

parser.parse(src, document)
print(document)
Ejemplo n.º 44
0
    else :
        text = uri = text.strip ()
    scheme   = options.pop ("uri_scheme", None)
    if scheme :
        ref  = "%s:%s" % (scheme, uri)
    else :
        ref  = uri
    text = text.replace    (" ", "\u202F") ### narrow non breaking space
    node = nodes.reference (rawtext, text, refuri = ref, ** options)
    return [node], []
# end def _uri_role

_email_role = CustomRole ("email", _uri_role, dict (uri_scheme = "mailto"))
_tel_role   = CustomRole ("tel",   _uri_role, dict (uri_scheme = "tel"))

register_local_role (_email_role.name, _email_role)
register_local_role ("tel",            _tel_role)

def _added_role (role, rawtext, text, lineno, inliner, options={}, content=[]) :
    cssc = "added" if len (rawtext) > 60 else "added-inline"
    node = nodes.inline (rawtext, text, classes = [cssc], ** options)
    return [node], []
# end def _added_role

register_local_role ("added", _added_role)

def _deleted_role (role, rawtext, text, lineno, inliner, options={}, content=[]) :
    cssc = "deleted" if len (rawtext) > 60 else "deleted-inline"
    node = nodes.inline (rawtext, text, classes = [cssc], ** options)
    return [node], []
# end def _deleted_role
Ejemplo n.º 45
0
        else:
            print "Unhandled literal '%s' for %s" % (t, highlight_language)
            sys.exit(1)
        return [nodes.literal(text=t)], []

    else:
        print "Unhandled highlight_language '%s'" % highlight_language
        sys.exit(1)


# Usage:
#
# The previous example was :xapian-code-example:`^`.
#
# The foo example is in :xapian-code-example:`foo`.
roles.register_local_role('xapian-code-example', xapian_code_example_role)
roles.register_local_role('xapian-basename-code-example',
                          xapian_code_example_short_role)
roles.register_local_role('xapian-basename-example', xapian_example_short_role)
roles.register_local_role('xapian-example', xapian_example_role)
# e.g. :xapian-class:`Database`
roles.register_local_role('xapian-class', xapian_class_role)
# e.g. :xapian-just-method:`add_matchspy(spy)`
roles.register_local_role('xapian-just-method', xapian_just_method_role)
# e.g. :xapian-method:`Database::reopen()`
roles.register_local_role('xapian-method', xapian_method_role)
# e.g. :xapian-variable:`spy`
roles.register_local_role('xapian-variable', xapian_variable_role)
# e.g. :xapian-just-constant:`OP_OR`
# (Currently this just does the same as the method version, but when more
# languages are added this may change).
Ejemplo n.º 46
0
def setup(builder):
    directives.register_directive('math', MathDirective)
    roles.register_local_role('math', math_role)
Ejemplo n.º 47
0
 def set_site(self, site):
     self.site = site
     roles.register_local_role('emoji', emoji_role)
Ejemplo n.º 48
0
                '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(
                    u'Invalid argument for "%s" directive:\n%s.' %
                    (self.name, SafeString(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."""

    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 []
Ejemplo n.º 49
0
def register():
    roles.register_local_role('html_entity', entity_role)
Ejemplo n.º 50
0
 def add_role(self, name, role):
     roles.register_local_role(name, role)
Ejemplo n.º 51
0
def setup(app):
    roles.register_local_role("sql", sql_role)
Ejemplo n.º 52
0
 def set_site(self, site):
     self.site = site
     roles.register_local_role('emoji', emoji_role)
     site.rst_transforms.append(Emojis)
Ejemplo n.º 53
0
        model, id, label, _, _ = m.groups()

    ctx = get_ctx()
    assert ctx
    pad = get_ctx().pad
    assert pad

    entry = pad.query(model).get(id)
    if entry is None:
        msg = inliner.reporter.error(
            "object with model=%s id=%s not found" % (model, id)
        )
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]

    if not label:
        label = entry["title"]

    url = entry.parent.path + "/" + entry["_slug"] + "/"
    roles.set_classes(options)
    node = nodes.reference(rawtext, label, refuri=url, **options)
    return [node], []


roles.register_local_role('ref', ref_role)


class RefRolePlugin(Plugin):
    name = 'ref-role'
    description = "Add a 'ref' role to reST markup."
Ejemplo n.º 54
0
 def add_generic_role(self, name, nodeclass):
     # don't use roles.register_generic_role because it uses
     # register_canonical_role
     self.debug('adding generic role: %r', (name, nodeclass))
     role = roles.GenericRole(name, nodeclass)
     roles.register_local_role(name, role)
Ejemplo n.º 55
0
                node += textnode
            continue
        accel_node = nodes.inline()
        letter_node = nodes.Text(span[0])
        accel_node += letter_node
        accel_node['classes'].append('accelerator')
        node += accel_node
        textnode = nodes.Text(span[1:])
        node += textnode

    node['classes'].append(typ)
    return [node], []


# Use 'patched_menusel_role' function for processing the 'menuselection' role
roles.register_local_role("menuselection", patched_menusel_role)

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'trueos_style'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['themes']
Ejemplo n.º 56
0
def setup(app):
    app.add_config_value("libpq_docs_version", "13", "html")
    roles.register_local_role("pq", pq_role)
    get_reader().app = app
Ejemplo n.º 57
0
                  lineno,
                  inliner,
                  options={},
                  content=[]):
    label = text
    settings = inliner.document.settings
    ref = "%s/%s/%s/" % (settings.sumatra_record_store,
                         settings.sumatra_project, label)
    set_classes(options)
    node = nodes.reference(rawtext, '', refuri=ref, **options)
    node += nodes.image(uri=settings.sumatra_link_icon,
                        alt='smt:' + utils.unescape(text))
    return [node], []


roles.register_local_role('smtlink', smt_link_role)


def build_options(global_settings, local_options):
    if hasattr(global_settings, 'env'):  # using sphinx
        config = global_settings.env.config
    else:
        config = global_settings  # using plain docutils
    # convert config into dict, and strip "sumatra_" prefix
    combined_options = {}
    for name in ("record_store", "project", "link_icon"):
        full_name = "sumatra_" + name
        if hasattr(config, full_name):
            combined_options[name] = getattr(config, full_name)
    combined_options.update(local_options)
    return combined_options
Ejemplo n.º 58
0
        final_argument_whitespace = True
        option_spec = {'width': directives.nonnegative_int,
                       'height': directives.nonnegative_int}

        def run(self):
            set_classes(self.options)
            node = role_video(source=self.arguments[0], **self.options)
            return [node]

    generic_docroles = {
        'doc': role_doc}

    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)

    directives.register_directive('video', VideoDirective)

Builder.load_string('''
#:import parse_color kivy.parser.parse_color



<RstDocument>:
    content: content
    scatter: scatter
    do_scroll_x: False
    canvas.before:
        Color:
            rgba: parse_color(root.colors['background'])
Ejemplo n.º 59
0
            if flag in self.options:
                self.options[flag] = True

        # noclasses should already default to False, but just in case...
        formatter = HtmlFormatter(noclasses=False, **self.options)
        parsed = highlight('\n'.join(self.content), lexer, formatter)
        return [nodes.raw('', parsed, format='html')]


directives.register_directive('code-block', Pygments)
directives.register_directive('sourcecode', Pygments)

_abbr_re = re.compile(r'\((.*)\)$', re.DOTALL)


class abbreviation(nodes.Inline, nodes.TextElement):
    pass


def abbr_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    m = _abbr_re.search(text)
    if m is None:
        return [abbreviation(text, text)], []
    abbr = text[:m.start()].strip()
    expl = m.group(1)
    return [abbreviation(abbr, abbr, explanation=expl)], []


roles.register_local_role('abbr', abbr_role)
Ejemplo n.º 60
0
    try:
        if int(text) <= 0:
            raise ValueError
    except ValueError:
        return sphinx_err(
            inliner, lineno, rawtext,
            'GitHub pull request or issue number must be a number greater than or equal to 1; "%s" is invalid.'
            % text)

    if name == 'pr':
        ref = gh_pr_uri
    elif name == 'issue':
        ref = gh_issue_uri
    else:
        return sphinx_err(
            inliner, lineno, rawtext,
            'unknown role name for GitHub reference - "%s"' % name)

    ref = ref.format(text)
    text = '#' + utils.unescape(text)
    return sphinx_ref(options, rawtext, text, ref)


roles.register_local_role('pr', role_github_pull_request_or_issue)
roles.register_local_role('issue', role_github_pull_request_or_issue)
roles.register_local_role('ghuser', role_github_user)


def setup(app):
    app.add_stylesheet('css/style.css')