Python sphinx.locale._ Examples

The following are 30 code examples of sphinx.locale._(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sphinx.locale , or try the search function .
Example #1
Source File: conf.py    From doepy with MIT License 6 votes vote down vote up
def setup(app):
    from sphinx.domains.python import PyField
    from sphinx.util.docfields import Field

    app.add_object_type(
        'confval',
        'confval',
        objname='configuration value',
        indextemplate='pair: %s; configuration value',
        doc_field_types=[
            PyField(
                'type',
                label=_('Type'),
                has_arg=False,
                names=('type',),
                bodyrolename='class'
            ),
            Field(
                'default',
                label=_('Default'),
                has_arg=False,
                names=('default',),
            ),
        ]
    ) 
Example #2
Source File: csharp.py    From sphinx-csharp with MIT License 6 votes vote down vote up
def resolve_xref(self, _, fromdocname, builder,
                     typ, target, node, contnode):
        targets = [target]
        if node['csharp:parent'] is not None:
            parts = node['csharp:parent'].split('.')
            while parts:
                targets.append('.'.join(parts)+'.'+target)
                parts = parts[:-1]

        objects = self.data['objects']
        objtypes = self.objtypes_for_role(typ)
        for tgt in targets:
            for objtype in objtypes:
                if (objtype, tgt) in objects:
                    return make_refnode(builder, fromdocname,
                                        objects[objtype, tgt],
                                        objtype + '-' + tgt,
                                        contnode, tgt + ' ' + objtype)

        for tgt in targets:
            ref = get_msdn_ref(tgt)
            if ref is not None:
                return ref
        return None 
Example #3
Source File: __init__.py    From cotk with Apache License 2.0 6 votes vote down vote up
def add_directive_header(self, sig: str) -> None:
        if self.doc_as_attr:
            self.directivetype = 'attribute'
        super().add_directive_header(sig)

        # add inheritance info, if wanted
        if not self.doc_as_attr and self.options.show_inheritance:
            sourcename = self.get_sourcename()
            self.add_line('', sourcename)
            if hasattr(self.object, '__bases__') and len(self.object.__bases__):
                bases = [':class:`%s`' % b.__name__
                         if b.__module__ in ('__builtin__', 'builtins')
                         else ':class:`%s.%s`' % (b.__module__, b.__name__)
                         for b in self.object.__bases__]
                self.add_line('   ' + _('Bases: %s') % ', '.join(bases),
                              sourcename) 
Example #4
Source File: csharp.py    From sphinx-csharp with MIT License 6 votes vote down vote up
def add_target_and_index(self, name, _, signode):
        targetname = self.objtype + '-' + name
        if targetname not in self.state.document.ids:
            signode['names'].append(targetname)
            signode['ids'].append(targetname)
            signode['first'] = (not self.names)
            self.state.document.note_explicit_target(signode)

            objects = self.env.domaindata['csharp']['objects']
            key = (self.objtype, name)
            if key in objects:
                self.env.warn(self.env.docname,
                              'duplicate description of %s %s, ' %
                              (self.objtype, name) +
                              'other instance in ' +
                              self.env.doc2path(objects[key]),
                              self.lineno)
            objects[key] = self.env.docname
        indextext = self.get_index_text(name)
        if indextext:
            self.indexnode['entries'].append(
                ('single', indextext, targetname, '')) 
Example #5
Source File: __init__.py    From cotk with Apache License 2.0 6 votes vote down vote up
def import_object(self) -> Any:
        """Never import anything."""
        # disguise as an attribute
        self.objtype = 'attribute'
        self._datadescriptor = True

        with mock(self.env.config.autodoc_mock_imports):
            try:
                ret = import_object(self.modname, self.objpath[:-1], 'class',
                                    attrgetter=self.get_attr,
                                    warningiserror=self.env.config.autodoc_warningiserror)
                self.module, _, _, self.parent = ret
                return True
            except ImportError as exc:
                logger.warning(exc.args[0], type='autodoc', subtype='import_object')
                self.env.note_reread()
                return False 
Example #6
Source File: __init__.py    From cotk with Apache License 2.0 6 votes vote down vote up
def _patch_python_domain() -> None:
    try:
        from sphinx.domains.python import PyTypedField
    except ImportError:
        pass
    else:
        import sphinx.domains.python
        from sphinx.locale import _
        for doc_field in sphinx.domains.python.PyObject.doc_field_types:
            if doc_field.name == 'parameter':
                doc_field.names = ('param', 'parameter', 'arg', 'argument')
                break
        sphinx.domains.python.PyObject.doc_field_types.append(
            PyTypedField('keyword', label=_('Keyword Arguments'),
                         names=('keyword', 'kwarg', 'kwparam'),
                         typerolename='obj', typenames=('paramtype', 'kwtype'),
                         can_collapse=True)) 
Example #7
Source File: testproject.py    From exhale with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self):
        if len(self.content) != 1:
            raise ValueError(
                "`testproject` directive needs exactly one argument (the name of the test folder).  "
                "Example: .. testproject:: c_maths"
            )
        self.content[0] = textwrap.dedent('''\
            View the `{project} source code here <{baseurl}/{project_dir}>`_.

            See also: :data:`ExhaleTestCase.test_project <testing.base.ExhaleTestCase.test_project>`.
        '''.format(
            project=self.content[0],
            project_dir=self.content[0].replace(" ", "\\ "),
            baseurl=get_projects_baseurl()
        ))
        project_node = testproject("\n".join(self.content))
        project_node += nodes.title(_("Test Project Source"), _("Test Project Source"))
        self.state.nested_parse(self.content, self.content_offset, project_node)

        return [project_node] 
Example #8
Source File: autotested.py    From exhale with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self):
        if len(self.content) != 0:
            raise ValueError("`autotested` directive does not allow any arguments.")
        # Seriously there _HAS_ to be a better way to do this...
        # Creating something of length 1 so that I can rage-replace it
        self.content = StringList("?")
        self.content[0] = textwrap.dedent('''\
            This method is tested automatically for every derived type of
            :class:`~testing.base.ExhaleTestCase` that is not decorated with
            :func:`~testing.decorators.no_run`.  The metaclass
            :class:`~testing.base.ExhaleTestCaseMetaclass` generates a testing method
            ``test_common`` that invokes this method.
        ''')
        autotested_node = autotested("\n".join(self.content))
        autotested_node += nodes.title(_("Automatically Tested"), _("Automatically Tested"))
        self.state.nested_parse(self.content, self.content_offset, autotested_node)

        return [autotested_node] 
Example #9
Source File: core.py    From pySINDy with MIT License 6 votes vote down vote up
def get_search_results(self, q):
        """Perform a search for the query `q`, and create a set
        of search results. Then render the search results as html and
        return a context dict like the one created by
        :meth:`get_document`::

            document = support.get_search_results(q)

        :param q: the search query
        """
        results = self.search.query(q)
        ctx = {
            'q': q,
            'search_performed': True,
            'search_results': results,
            'docroot': '../',  # XXX
            '_': _,
        }
        document = {
            'body': self.results_template.render(ctx),
            'title': 'Search Results',
            'sidebar': '',
            'relbar': ''
        }
        return document 
Example #10
Source File: tags.py    From openconcept with MIT License 6 votes vote down vote up
def run(self):
        env = self.state.document.settings.env
        targetid = "tag-%d" % env.new_serialno('tag')
        targetnode = nodes.target('', '', ids=[targetid])

        # The tags fetched from the custom directive are one piece of text
        # sitting in self.content[0]
        taggs = self.content[0].split(", ")
        links = []

        for tagg in taggs:
            # Create Sphinx doc refs of format :ref:`Tagname<Tagname>`
            link = ":ref:`" + tagg + "<" + tagg + ">`"
            links.append(link)
        # Put links back in a single comma-separated string together
        linkjoin = ", ".join(links)

        # Replace content[0] with hyperlinks to display in admonition
        self.content[0] = linkjoin

        ad = Admonition(self.name, [_('Tags')], self.options,
                        self.content, self.lineno, self.content_offset,
                        self.block_text, self.state, self.state_machine)

        return [targetnode] + ad.run() 
Example #11
Source File: docstring.py    From cotk with Apache License 2.0 5 votes vote down vote up
def _parse_warns_section(self, section: str) -> List[str]:
        return self._format_fields(_('Warns'), self._consume_fields()) 
Example #12
Source File: docstring.py    From cotk with Apache License 2.0 5 votes vote down vote up
def _parse_parameters_section(self, section: str) -> List[str]:
        fields = self._consume_fields()
        if self._config.napoleon_use_param:
            return self._format_docutils_params(fields)
        else:
            return self._format_fields(_('Parameters'), fields) 
Example #13
Source File: docstring.py    From cotk with Apache License 2.0 5 votes vote down vote up
def _parse_yields_section(self, section: str) -> List[str]:
        fields = self._consume_returns_section()
        return self._format_fields(_('Yields'), fields) 
Example #14
Source File: __init__.py    From cotk with Apache License 2.0 5 votes vote down vote up
def __getattr__(self, name: str) -> Any:
        try:
            return self[name.replace('_', '-')]
        except KeyError:
            return None 
Example #15
Source File: __init__.py    From cotk with Apache License 2.0 5 votes vote down vote up
def add_content(self, more_content: Any, no_docstring: bool = False) -> None:
        if self.doc_as_attr:
            classname = safe_getattr(self.object, '__qualname__', None)
            if not classname:
                classname = safe_getattr(self.object, '__name__', None)
            if classname:
                module = safe_getattr(self.object, '__module__', None)
                parentmodule = safe_getattr(self.parent, '__module__', None)
                if module and module != parentmodule:
                    classname = str(module) + '.' + str(classname)
                content = StringList([_('alias of :class:`%s`') % classname], source='')
                super().add_content(content, no_docstring=True)
        else:
            super().add_content(more_content) 
Example #16
Source File: pbDomain.py    From opbasm with MIT License 5 votes vote down vote up
def get_index_text(self, name):
        if self.objtype == 'function':
            return _('%s') % name
        elif self.objtype == 'macro':
            return _('%s') % name
        elif self.objtype == 'var':
            return _('%s (PicoBlaze variable)') % name
        else:
            return '' 
Example #17
Source File: pbDomain.py    From opbasm with MIT License 5 votes vote down vote up
def clear_doc(self, docname):
        for fullname, (fn, _) in self.data['objects'].items():
            if fn == docname:
                del self.data['objects'][fullname] 
Example #18
Source File: exercise.py    From sphinxcontrib-jupyter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self):
        self.assert_has_content()

        num = self.env.new_serialno(self.node_class_str)
        target_id = f"{self.node_class_str}-{num:d}"
        targetnode = nodes.target('', '', ids=[target_id])
        _path = self.env.docname.replace("/", "-")
        node_id = f"{_path}-{num}"

        node = self.node_class("\n".join(self.content))
        node["_id"] = node_id
        node["classes"] = [self.options.get("class", None)]
        node["label"] = self.options.get("label", None)
        title_root = self.options.get("title", self.title_root)
        node["title_root"] = title_root

        title = _(f"{title_root} {num + 1}")

        para = nodes.paragraph()
        para += nodes.strong(title, title)
        node += para

        self.state.nested_parse(self.content, self.content_offset, node)

        if not hasattr(self.env, self.env_attr):
            setattr(self.env, self.env_attr, dict())

        getattr(self.env, self.env_attr)[node_id] = {
            'docname': self.env.docname,
            'lineno': self.lineno,
            'node_copy': node.deepcopy(),
            'target': targetnode,
            "number": num,
            "label": node["label"],
            "title_root": title_root,
        }
        return [targetnode, node] 
Example #19
Source File: csharp.py    From sphinx-csharp with MIT License 5 votes vote down vote up
def parse_param_signature(sig):
    """ Parse a parameter signature of the form: type name (= default)? """
    match = PARAM_SIG_RE.match(sig.strip())
    if not match:
        raise RuntimeError('Parameter signature invalid, got ' + sig)
    groups = match.groups()
    modifiers = groups[0].split()
    typ, name, _, default = groups[-4:]
    return ParamTuple(name=name, typ=typ,
                      default=default, modifiers=modifiers) 
Example #20
Source File: csharp.py    From sphinx-csharp with MIT License 5 votes vote down vote up
def parse_attr_signature(sig):
    """ Parse an attribute signature """
    match = ATTR_SIG_RE.match(sig.strip())
    if not match:
        raise RuntimeError('Attribute signature invalid, got ' + sig)
    name, _, params = match.groups()
    if params is not None and params.strip() != '':
        params = split_sig(params)
        params = [parse_param_signature(x) for x in params]
    else:
        params = []
    return (name, params) 
Example #21
Source File: csharp.py    From sphinx-csharp with MIT License 5 votes vote down vote up
def get_index_text(self, name):
        if self.objtype == 'directive':
            return _('%s (directive)') % name
        if self.objtype == 'role':
            return _('%s (role)') % name
        return '' 
Example #22
Source File: csharp.py    From sphinx-csharp with MIT License 5 votes vote down vote up
def handle_signature(self, sig, signode):
        typ, _, _ = parse_type_signature(sig)
        desc_name = 'class %s' % sig
        signode += addnodes.desc_name(desc_name, desc_name)
        return self.get_fullname(typ) 
Example #23
Source File: __init__.py    From sphinx-confluence with MIT License 5 votes vote down vote up
def depart_desc_signature(self, node):
        """ Copy-paste from original method """
        self.add_permalink_ref(node, _('Permalink to this definition'))
        self.body.append('</div>') 
Example #24
Source File: __init__.py    From sphinx-confluence with MIT License 5 votes vote down vote up
def underscore_to_camelcase(text):
    return ''.join(word.title() if i else word for i, word in enumerate(text.split('_'))) 
Example #25
Source File: pdfbuilder.py    From rst2pdf with MIT License 5 votes vote down vote up
def genindex_nodes(genindexentries):
    indexlabel = _('Index')
    indexunder = '=' * len(indexlabel)
    output = ['DUMMY', '=====', '.. _genindex:\n\n', indexlabel, indexunder, '']

    for key, entries in genindexentries:
        output.append('.. cssclass:: heading4\n\n%s\n\n' % key)  # initial
        for entryname, entryvalue in entries:
            links, subitems = entryvalue[0:2]
            if links:
                output.append('`%s <#%s>`_' % (entryname, nodes.make_id(links[0][1])))
                for i, link in enumerate(links[1:]):
                    output[-1] += ' `[%s] <#%s>`_ ' % (i + 1, nodes.make_id(link[1]))
                output.append('')
            else:
                output.append(entryname)
            if subitems:
                for subentryname, subentrylinks in subitems:
                    if subentrylinks:
                        output.append(
                            '    `%s <%s>`_' % (subentryname, subentrylinks[0])
                        )
                        for i, link in enumerate(subentrylinks[1:]):
                            output[-1] += ' `[%s] <%s>`_ ' % (i + 1, link)
                        output.append('')
                    else:
                        output.append(subentryname)
                        output.append('')

    doctree = docutils.core.publish_doctree('\n'.join(output))
    return doctree[1] 
Example #26
Source File: symbolator_sphinx.py    From symbolator with MIT License 5 votes vote down vote up
def text_visit_symbolator(self, node):
    # type: (nodes.NodeVisitor, symbolator) -> None
    if 'alt' in node.attributes:
        self.add_text(_('[symbol: %s]') % node['alt'])
    else:
        self.add_text(_('[symbol]'))
    raise nodes.SkipNode 
Example #27
Source File: symbolator_sphinx.py    From symbolator with MIT License 5 votes vote down vote up
def man_visit_symbolator(self, node):
    # type: (nodes.NodeVisitor, symbolator) -> None
    if 'alt' in node.attributes:
        self.body.append(_('[symbol: %s]') % node['alt'])
    else:
        self.body.append(_('[symbol]'))
    raise nodes.SkipNode 
Example #28
Source File: pdvegaplot.py    From pdvega with MIT License 5 votes vote down vote up
def generic_visit_pdvega_plot(self, node):
    # TODO: generate PNGs and insert them here
    if 'alt' in node.attributes:
        self.body.append(_('[ graph: %s ]') % node['alt'])
    else:
        self.body.append(_('[ graph ]'))
    raise nodes.SkipNode 
Example #29
Source File: protobufdomain.py    From ga4gh-schemas with Apache License 2.0 5 votes vote down vote up
def get_index_text(self,name):
    if self.objtype == 'fixed':
      return _('%s (Protobuf fixed-width value)') % name
    if self.objtype == 'enum':
      return _('%s (Protobuf enum)') % name
    if self.objtype == 'message':
      return _('%s (Protobuf message)') % name
    if self.objtype == 'error':
      return _('%s (Protobuf error)') % name
    if self.objtype == 'rpc':
      return _('%s (Protobuf RPC)') % name 
Example #30
Source File: rst.py    From restbuilder with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_image(self, node):
        self.new_state(0)
        if 'uri' in node:
            self.add_text(_('.. image:: %s') % node['uri'])
        elif 'target' in node.attributes:
            self.add_text(_('.. image: %s') % node['target'])
        elif 'alt' in node.attributes:
            self.add_text(_('[image: %s]') % node['alt'])
        else:
            self.add_text(_('[image]'))
        self.end_state(wrap=False)
        raise nodes.SkipNode