Python sphinx.util.nodes.make_refnode() Examples

The following are 22 code examples of sphinx.util.nodes.make_refnode(). 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.util.nodes , or try the search function .
Example #1
Source File: sphinx_cfg_options.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def create_option_reference(self, option, config, context):
        par = nodes.paragraph()
        innernode = addnodes.literal_strong(option.dispname, option.dispname)
        par += self.make_refnode(option.docname, option.anchor, innernode)
        if option.config != config:
            par += nodes.Text(" (from ")
            par += self._make_config_xref(option.config)
            par += nodes.Text(")")
        if option.context is not None:
            opt_context = option.context
            if opt_context.startswith(context):
                opt_context = opt_context[len(context):]
            if opt_context:
                par += nodes.Text(" in ")
                par += addnodes.literal_emphasis(option.context, option.context)
        return par 
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: sphinx_cfg_options.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        if not target:
            return None
        if typ == "config":
            config = self.master_configs.get(target, None)
            if config is None:
                return None
            return make_refnode(builder, fromdocname, config.docname, config.anchor, contnode,
                                config.dispname)
        elif typ == "option":
            config_options = self.config_options
            split = target.split('.')
            if len(split) < 2:
                return None
            for i in range(1, len(split)):
                config, entry_name = '.'.join(split[:i]), '.'.join(split[i:])
                for option_entry in config_options.get(config, []):
                    if option_entry.dispname == entry_name:  # match!
                        return make_refnode(builder, fromdocname, option_entry.docname,
                                            option_entry.anchor, contnode, option_entry.dispname)
            return None
        return None 
Example #4
Source File: sphinxext.py    From bioconda-utils with MIT License 6 votes vote down vote up
def resolve_required_by_xrefs(app, env, node, contnode):
    """Now that all recipes and packages have been parsed, we are called here
    for each ``pending_xref`` node that sphinx has not been able to resolve.

    We handle specifically the ``requiredby`` reftype created by the
    `RequiredByField` fieldtype allowed in ``conda:package::``
    directives, where we replace the ``pending_ref`` node with a bullet
    list of reference nodes pointing to the package pages that
    "depended" on the package.
    """
    if node['reftype'] == 'requiredby' and node['refdomain'] == 'conda':
        target = node['reftarget']
        docname = node['refdoc']
        backrefs = env.domains['conda'].data['backrefs'].get(target, set())
        listnode = nodes.bullet_list()
        for back_docname, back_target in backrefs:
            par = nodes.paragraph()
            name_node = addnodes.literal_strong(back_target, back_target,
                                      classes=['xref', 'backref'])
            refnode = make_refnode(app.builder, docname,
                                   back_docname, back_target, name_node)
            refnode.set_class('conda-package')
            par += refnode
            listnode += nodes.list_item('', par)
        return listnode 
Example #5
Source File: sphinxext.py    From bioconda-utils with MIT License 6 votes vote down vote up
def resolve_xref(self, env: BuildEnvironment, fromdocname: str,
                     builder, role, target, node, contnode):
        """Resolve the ``pending_xref`` **node** with the given **role** and **target**."""
        for objtype in self.objtypes_for_role(role) or []:
            if (objtype, target) in self.data['objects']:
                node = make_refnode(
                    builder, fromdocname,
                    self.data['objects'][objtype, target][0],
                    self.data['objects'][objtype, target][1],
                    contnode, target + ' ' + objtype)
                node.set_class('conda-package')
                return node

            if objtype == "package":
                for channel, urlformat in env.app.config.bioconda_other_channels.items():
                    if RepoData().get_package_data(channels=channel, name=target):
                        uri = urlformat.format(target)
                        node = nodes.reference('', '', internal=False,
                                               refuri=uri, classes=[channel])
                        node += contnode
                        return node

        return None  # triggers missing-reference 
Example #6
Source File: httpdomain.py    From nltk-server with MIT License 6 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder, typ, target,
                     node, contnode):
        try:
            info = self.data[str(typ)][target]
        except KeyError:
            text = contnode.rawsource
            role = self.roles.get(typ)
            if role is None:
                return nodes.emphasis(text, text)
            resnode = role.result_nodes(env.get_doctree(fromdocname),
                                        env, node, None)[0][0]
            if isinstance(resnode, addnodes.pending_xref):
                text = node[0][0]
                reporter = env.get_doctree(fromdocname).reporter
                reporter.error('Cannot resolve reference to %r' % text,
                               line=node.line)
                return nodes.problematic(text, text)
            return resnode
        else:
            anchor = http_resource_anchor(typ, target)
            title = typ.upper() + ' ' + target
            return make_refnode(builder, fromdocname, info[0], anchor,
                                contnode, title) 
Example #7
Source File: layout.py    From sphinxcontrib-needs with MIT License 6 votes vote down vote up
def meta_id(self):
        """
        Returns the current need id as clickable and linked reference.

        Usage::

            <<meta_id()>>

        :return: docutils node
        """
        from sphinx.util.nodes import make_refnode
        id_container = nodes.inline(classes=["needs-id"])

        nodes_id_text = nodes.Text(self.need['id'], self.need['id'])
        id_ref = make_refnode(self.app.builder,
                              # fromdocname=self.need['docname'],
                              fromdocname=self.fromdocname,
                              todocname=self.need['docname'],
                              targetid=self.need['id'],
                              child=nodes_id_text.deepcopy(),
                              title=self.need['id'])
        id_container += id_ref
        return id_container 
Example #8
Source File: apidoc.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        targets = self.data['targets'].get(typ, {})
        try:
            todocname, targetname = targets[target]
        except KeyError:
            raise RuntimeError("MISSING REFERENCE: api:%s:%s" % (typ, target))

        return make_refnode(builder, fromdocname,
                            todocname, targetname,
                            contnode, target) 
Example #9
Source File: sphinx_cfg_options.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def create_option_reference_table_row(self, option, config, context):
        row = nodes.row("")
        par = self.create_option_reference(option, config, context)
        row += nodes.entry("", par)
        if self.builder.config.cfg_options_default_in_summary_table:
            par = nodes.paragraph()
            if option.default:
                par += nodes.literal(option.default, option.default)
            row += nodes.entry("", par)
        par = nodes.paragraph()
        par += nodes.Text(option.summary)
        if option.summarycropped:
            par += self.make_refnode(option.docname, option.anchor, nodes.Text(" [...]"))
        row += nodes.entry("", par)
        return row 
Example #10
Source File: viewcode.py    From megaman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def missing_reference(app, env, node, contnode):
    # resolve our "viewcode" reference nodes -- they need special treatment
    if node['reftype'] == 'viewcode':
        return make_refnode(app.builder, node['refdoc'], node['reftarget'],
                            node['refid'], contnode) 
Example #11
Source File: pbDomain.py    From opbasm with MIT License 5 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder,
                     typ, target, node, contnode):

        if target not in self.data['objects']:
            return None
        obj = self.data['objects'][target]
        return make_refnode(builder, fromdocname, obj[0], 'pb.' + target,
                            contnode, target) 
Example #12
Source File: viewcode.py    From gatspy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def missing_reference(app, env, node, contnode):
    # resolve our "viewcode" reference nodes -- they need special treatment
    if node['reftype'] == 'viewcode':
        return make_refnode(app.builder, node['refdoc'], node['reftarget'],
                            node['refid'], contnode) 
Example #13
Source File: configdomain.py    From couchdb-documentation with Apache License 2.0 5 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        if typ == "section":
            info = self.data[typ][target]
            title = "[%s]" % target
        elif typ == "option":
            assert "/" in target, "option without section: %r" % target
            section, option = target.split("/", 1)
            info = self.data[typ][target]
            title = option
        else:
            assert "unknown role %r for target %r" % (typ, target)
        return make_refnode(builder, fromdocname, info[0], target, contnode, title) 
Example #14
Source File: httpdomain.py    From couchdb-documentation with Apache License 2.0 5 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        try:
            info = self.data[str(typ)][target]
        except KeyError:
            text = contnode.rawsource
            if typ == "statuscode":
                return http_statuscode_role(None, text, text, None, None)[0][0]
            elif typ == "mailheader":
                return http_header_role(None, text, text, None, None)[0][0]
            else:
                return nodes.emphasis(text, text)
        else:
            anchor = http_resource_anchor(typ, target)
            title = typ.upper() + " " + target
            return make_refnode(builder, fromdocname, info[0], anchor, contnode, title) 
Example #15
Source File: viewcode.py    From supersmoother with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def missing_reference(app, env, node, contnode):
    # resolve our "viewcode" reference nodes -- they need special treatment
    if node['reftype'] == 'viewcode':
        return make_refnode(app.builder, node['refdoc'], node['reftarget'],
                            node['refid'], contnode) 
Example #16
Source File: protobufdomain.py    From ga4gh-schemas with Apache License 2.0 5 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
    if target not in self.data['objects']:
      return None
    obj = self.data['objects'][target]
    return make_refnode(builder, fromdocname, obj[0], 'protobuf.' + target, contnode, target) 
Example #17
Source File: _exttools.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
		objtypes = self.objtypes_for_role(typ) or []
		for objtype in objtypes:
			if (objtype, target) in self.data['objects']:
				docname, labelid = self.data['objects'][objtype, target]
				break
		else:
			docname, labelid = '', ''
		if not docname:
			return None
		return make_refnode(builder, fromdocname, docname, labelid, contnode) 
Example #18
Source File: sphinx_cfg_options.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def _make_config_xref(self, config):
        node = nodes.Text(config, config)
        match = [(obj_entry.docname, obj_entry.anchor) for obj_entry in self.domain.get_objects()
                 if obj_entry.name == config and obj_entry.typ == 'config']
        if len(match) > 0:
            docname, anchor = match[0]
            node = self.make_refnode(docname, anchor, node)
        return node 
Example #19
Source File: sphinx_cfg_options.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def make_refnode(self, docname, anchor, innernode):
        try:
            refnode = make_refnode(self.builder, self.docname, docname, anchor, innernode)
        except NoUri:  # ignore if no URI can be determined, e.g. for LaTeX output
            refnode = innernode
        return refnode 
Example #20
Source File: need_part.py    From sphinxcontrib-needs with MIT License 4 votes vote down vote up
def update_need_with_parts(env, need, part_nodes):
    for part_node in part_nodes:
        content = part_node.children[0].children[0]  # ->inline->Text
        result = part_pattern.match(content)
        if result is not None:
            inline_id = result.group(1)
            part_content = result.group(2)
        else:
            part_content = content
            inline_id = hashlib.sha1(part_content.encode("UTF-8")).hexdigest().upper()[:3]

        if 'parts' not in need.keys():
            need['parts'] = {}

        if inline_id in need['parts'].keys():
            log.warning("part_need id {} in need {} is already taken. need_part may get overridden.".format(
                inline_id, need['id']))

        need['parts'][inline_id] = {
            'id': inline_id,
            'content': part_content,
            'document': need["docname"],
            'links_back': [],
            'is_part': True,
            'is_need': False,
            'links': [],
        }

        part_id_ref = '{}.{}'.format(need['id'], inline_id)
        part_id_show = inline_id
        part_node['reftarget'] = part_id_ref

        part_link_text = ' {}'.format(part_id_show)
        part_link_node = nodes.Text(part_link_text, part_link_text)
        part_text_node = nodes.Text(part_content, part_content)

        from sphinx.util.nodes import make_refnode

        part_ref_node = make_refnode(env.app.builder,
                                     need['docname'],
                                     need['docname'],
                                     part_id_ref,
                                     part_link_node)
        part_ref_node["classes"] += ['needs-id']

        part_node.children = []
        node_need_part_line = nodes.inline(ids=[part_id_ref], classes=["need-part"])
        node_need_part_line.append(part_text_node)
        node_need_part_line.append(part_ref_node)
        part_node.append(node_need_part_line) 
Example #21
Source File: gssapi_find_missing.py    From python-gssapi with ISC License 4 votes vote down vote up
def _missing_ref(app, env, node, contnode):
    # skip non-elements
    if not isinstance(contnode, nodes.Element):
        return

    if node.get('refdomain') != 'py':
        return

    options = env.domains['py'].find_obj(
        env, None, None, node.get('reftarget'), node.get('reftype'), 1)

    if not options:
        return

    is_raw = node.get('py:module').startswith('gssapi.raw')

    if len(options) > 1:
        raw_opts = []
        non_raw_opts = []
        for opt in options:
            full_name, type_info = opt
            lib_name, mod_name, _mod_type = type_info
            if mod_name.startswith('gssapi.raw'):
                raw_opts.append(opt)
            else:
                non_raw_opts.append(opt)

        if is_raw:
            if raw_opts:
                choice = raw_opts[0]
            elif non_raw_opts:
                choice = non_raw_opts[0]
            else:
                return
        else:
            if non_raw_opts:
                choice = non_raw_opts[0]
            elif raw_opts:
                choice = raw_opts[0]
            else:
                return
    else:
        choice = options[0]

    choice_name, choice_info = choice
    gssapi, choice_mod, choice_type = choice_info

    if choice_type == 'module':
        return env.domains['py']._make_module_refnode(
            app.builder, node.get('refdoc'), choice_name, contnode)
    else:
        return make_refnode(app.builder, node.get('refdoc'), choice_mod,
                            choice_name, contnode, choice_name) 
Example #22
Source File: eql.py    From edgedb with Apache License 2.0 4 votes vote down vote up
def resolve_xref(self, env, fromdocname, builder,
                     type, target, node, contnode):

        objects = self.data['objects']
        expected_type = self._role_to_object_type[type]

        target = target.replace(' ', '-')
        if expected_type == 'keyword':
            targets = [f'keyword::{target}']
        elif expected_type == 'operator':
            targets = [f'operator::{target}']
        elif expected_type == 'statement':
            targets = [f'statement::{target}']
        elif expected_type in {'type', 'function', 'constraint'}:
            targets = [f'{expected_type}::{target}']
            if '::' not in target:
                targets.append(f'{expected_type}::std::{target}')
        else:
            targets = [target]

        docname = None
        obj_type = None
        obj_desc = None
        for target in targets:
            try:
                docname, obj_type, obj_desc = objects[target]
            except KeyError:
                continue

        if docname is None:
            if not node.get('eql-auto-link'):
                raise shared.DomainError(
                    f'cannot resolve :eql:{type}: targeting {target!r}')
            else:
                return

        if obj_type != expected_type:
            raise shared.DomainError(
                f'cannot resolve :eql:{type}: targeting {target!r}: '
                f'the type of referred object {expected_type!r} '
                f'does not match the reftype')

        if node['reftype'] in self.desc_roles:
            node = d_nodes.Text(obj_desc)
        else:
            node = s_nodes_utils.make_refnode(
                builder, fromdocname, docname, target, contnode, None)
            node['eql-type'] = obj_type

        return node