Exemplo n.º 1
0
def doctree_read(app, doctree):
    # Add viewcode nodes for code elements referenced in the document.

    env = app.builder.env
    if not hasattr(env, '_viewcode_modules'):
        env._viewcode_modules = {}

    # handle desc (description) nodes (module contents)
    for objnode in doctree.traverse(addnodes.desc):
        if objnode.get('domain') != 'py':
            continue
        names = set()
        for signode in objnode:
            if not isinstance(signode, addnodes.desc_signature):
                continue
            modname = signode.get('module')
            if not modname:
                continue
            fullname = signode.get('fullname')
            if not _update_tags(env, modname, fullname):
                continue
            if fullname in names:
                # only one link per name, please
                continue
            names.add(fullname)
            pagename = '_modules/' + modname.replace('.', '/')
            # build up an xref and add it to the desc node
            onlynode = addnodes.only(expr='html')
            onlynode += addnodes.pending_xref(
                '', reftype='viewcode', refdomain='std', refexplicit=False,
                reftarget=pagename, refid=fullname,
                refdoc=env.docname)
            onlynode[0] += nodes.inline('', _('[source]'),
                                        classes=['viewcode-link'])
            signode += onlynode

    # handle index nodes (modules themselves)
    for objnode in doctree.traverse(addnodes.index):
        # extract module name by de-munging the "target" field
        index_target = objnode['entries'][0][2]
        if not index_target.startswith('module-'):
            continue
        modname = index_target.replace('module-', '', 1)
        _update_tags(env, modname)
        pagename = '_modules/' + modname.replace('.', '/')
        # build up an xref and add it in a new paragraph after the index node
        xref = addnodes.pending_xref(
            '', reftype='viewcode', refdomain='std', refexplicit=False,
            reftarget=pagename, refid='', refdoc=env.docname)
        xref += nodes.inline('', _('[source]'),
                                    classes=['viewcode-link'])
        idx = objnode.parent.index(objnode) + 1
        objnode.parent.insert(idx, nodes.paragraph('', '', xref))
Exemplo n.º 2
0
    def handle_signature(self, sig, signode):
        name = self.options["name"]
        parameters = json.loads(self.options["parameters"]) if "parameters" in self.options else []
        return_v = json.loads(self.options["return"]) if "return" in self.options else ("", "")
        prefix = self.options["prefix"] if "prefix" in self.options else ""

        if not ("parameters" in self.options) or not ("return" in self.options):
            print("WARNING: No parameters or return set for '" + name + "'")

        signode += nodes.Text(prefix + " ", prefix + u"\xa0")
        xref = addnodes.pending_xref(
            ":ref:`" + return_v[1] + "`",
            refdomain="std",
            reftype="ref",
            reftarget=ws_re.sub(" ", return_v[1].lower()),
            refexplicit=False,
        )
        xref += nodes.Text(return_v[0], return_v[0])
        signode += xref
        signode += nodes.Text(" ", u"\xa0")

        signode += addnodes.desc_name(name, name)
        paramlist = addnodes.desc_parameterlist()
        for tn in parameters:
            param = addnodes.desc_parameter("", "", noemph=True)
            prefix = ""
            if len(tn) > 3 and tn[3] == "True":
                prefix += "ref "
            if len(tn) > 4 and tn[4] == "True":
                prefix += "out "

            if prefix != "":
                param += nodes.Text(prefix + " ", prefix + u"\xa0")

            xref = addnodes.pending_xref(
                ":ref:`" + tn[2] + "`",
                refdomain="std",
                reftype="ref",
                reftarget=ws_re.sub(" ", tn[2].lower()),
                refexplicit=False,
            )
            xref += nodes.Text(tn[0], tn[0])
            param += xref
            param += nodes.emphasis(" " + tn[1], u"\xa0" + tn[1])
            paramlist += param
        signode += paramlist

        return name, ""
Exemplo n.º 3
0
def mkYrefNode(target,text,rawtext,role,explicitText,lineno,options={}):
	"""Create hyperlink to yade target. Targets starting with literal 'yade.' are absolute, but the leading 'yade.' will be stripped from the link text. Absolute tergets are supposed to live in page named yade.[module].html, anchored at #yade.[module2].[rest of target], where [module2] is identical to [module], unless mapped over by moduleMap.
	
	Other targets are supposed to live in yade.wrapper (such as c++ classes)."""

	writer=__builtin__.writer # to make sure not shadowed by a local var
	import string
	if target.startswith('yade.'):
		module='.'.join(target.split('.')[0:2])
		module2=(module if module not in moduleMap.keys() else moduleMap[module])
		if target==module: target='' # to reference the module itself
		uri=('%%%s#%s'%(module2,target) if writer=='latex' else '%s.html#%s'%(module2,target))
		if not explicitText and module!=module2:
			text=module2+'.'+'.'.join(target.split('.')[2:])
		text=string.replace(text,'yade.','',1)
	elif target.startswith('external:'):
		exttarget=target.split(':',1)[1]
		if not explicitText: text=exttarget
		target=exttarget if '.' in exttarget else 'module-'+exttarget
		uri=(('%%external#%s'%target) if writer=='latex' else 'external.html#%s'%target)
	else:
		uri=(('%%yade.wrapper#yade.wrapper.%s'%target) if writer=='latex' else 'yade.wrapper.html#yade.wrapper.%s'%target)
		#print writer,uri
	if 0:
		refnode=addnodes.pending_xref(rawtext,reftype=role,refexplicit=explicitText,reftarget=target)
		#refnode.line=lineno
		#refnode+=nodes.literal(rawtext,text,classes=['ref',role])
		return [refnode],[]
		#ret.rawtext,reftype=role,
	else:
		return nodes.reference(rawtext,docutils.utils.unescape(text),refuri=uri,**options)
Exemplo n.º 4
0
 def attach_type(self, node, type):
     # XXX: link to c?
     text = str(type)
     pnode = addnodes.pending_xref("", refdomain="cpp", reftype="type", reftarget=text, modname=None, classname=None)
     pnode["cpp:parent"] = self.env.temp_data.get("cpp:parent")
     pnode += nodes.Text(text)
     node += pnode
Exemplo n.º 5
0
    def visit_link(self, mdnode):
        ref_node = nodes.reference()
        ref_node['refuri'] = mdnode.destination
        # TODO okay, so this is acutally not always the right line number, but
        # these mdnodes won't have sourcepos on them for whatever reason. This
        # is better than 0 though.
        ref_node.line = (mdnode.sourcepos[0][0] if mdnode.sourcepos
                         else mdnode.parent.sourcepos[0][0])
        if mdnode.title:
            ref_node['title'] = mdnode.title
        next_node = ref_node

        url_check = urlparse(mdnode.destination)
        if not url_check.scheme and not url_check.fragment:
            wrap_node = addnodes.pending_xref(
                reftarget=mdnode.destination,
                reftype='any',
                refexplicit=True,
                refwarn=True
            )
            # TODO also not correct sourcepos
            wrap_node.line = (mdnode.sourcepos[0][0] if mdnode.sourcepos
                              else mdnode.parent.sourcepos[0][0])
            if mdnode.title:
                wrap_node['title'] = mdnode.title
            wrap_node.append(ref_node)
            next_node = wrap_node

        self.current_node.append(next_node)
        self.current_node = ref_node
Exemplo n.º 6
0
    def make_content(self, all_members):
        doc = self.item
        content = addnodes.desc_content()

        if doc.exports or doc.dependencies:
            with addto(content, nodes.field_list()) as fields:
                if doc.exports:
                    with addto(fields, nodes.field()) as field:
                        field += nodes.field_name('Exports', 'Exports')
                        with addto(field, nodes.field_body()) as body:
                            ref = doc['exports'] # warning: not the same as doc.exports
                            label = ref or '<anonymous>'
                            link = addnodes.pending_xref(
                                ref, nodes.paragraph(ref, label),
                                refdomain='js',
                                reftype='any',
                                reftarget=ref,
                            )
                            link['js:module'] = doc.name
                            body += link

                if doc.dependencies:
                    with addto(fields, nodes.field()) as field:
                        self.make_dependencies(field, doc)

        if doc.doc:
            # FIXME: source offset
            self.directive.state.nested_parse(to_list(doc.doc, source=doc['sourcefile']), 0, content)

        self.directive.state.nested_parse(self.directive.content, 0, content)

        content += self.document_properties(all_members)

        return content
    def add_shape_and_attrs(self, signode, modname, ftype, shape, attrs):
        # add shape 
        if shape:
            add_shape(signode, shape, modname=modname)
            #signode += nodes.Text(' '+shape)
        # add type ('float', 'interger', etc)
        if ftype or attrs:
            signode += nodes.emphasis(' [', ' [')
        if ftype:
            refnode = addnodes.pending_xref(
                '', refdomain='f', reftype='type', reftarget=ftype,
                modname=modname,)
            refnode += nodes.emphasis(ftype, ftype)
            signode += refnode
            #tnode = addnodes.desc_type(ftype, ftype)
            #tnode +=
            #signode += addnodes.desc_type(ftype, ftype)
            #signode += 
    #        signode += addnodes.desc_type('', '')
    #        self._parse_type(signode[-1], ftype)
        if attrs:
            if ftype: signode += nodes.emphasis(',',',')
            for iatt,att in enumerate(re.split('\s*,\s*', attrs)):
                if iatt:
                    signode += nodes.emphasis(',',',')
                if att.startswith('parameter'):
                    value = att.split('=')[1]
                    signode += nodes.emphasis('parameter=', 'parameter=')
                    convert_arithm(signode, value, modname=modname)
                else:
                    signode += nodes.emphasis(att,att)
            #signode += nodes.emphasis(attrs, attrs)

        if ftype or attrs:
            signode += nodes.emphasis(']', ']')
Exemplo n.º 8
0
 def make_xref(self, rolename, domain, target, innernode=nodes.emphasis):
     if not rolename:
         return innernode(target, target)
     refnode = addnodes.pending_xref('', refdomain=domain, refexplicit=False,
                                     reftype=rolename, reftarget=target)
     refnode += innernode(target, target)
     return refnode
Exemplo n.º 9
0
 def apply(self):
     config = self.document.settings.env.config
     github_project = config.github_project
     issue_pattern = config.github_issue_pattern
     if isinstance(issue_pattern, str_t):
         issue_pattern = re.compile(issue_pattern)
     for node in self.document.traverse(nodes.Text):
         parent = node.parent
         if isinstance(parent, (nodes.literal, nodes.FixedTextElement)):
             continue
         text = text_t(node)
         new_nodes = []
         last_issue_ref_end = 0
         for match in issue_pattern.finditer(text):
             head = text[last_issue_ref_end:match.start()]
             if head:
                 new_nodes.append(nodes.Text(head))
             last_issue_ref_end = match.end()
             issuetext = match.group(0)
             issue_id = match.group(1)
             refnode = pending_xref()
             refnode['reftarget'] = issue_id
             refnode['reftype'] = 'issue'
             refnode['refdomain'] = 'github'
             refnode['github_project'] = github_project
             reftitle = issuetext
             refnode.append(nodes.inline(
                 issuetext, reftitle, classes=['xref', 'issue']))
             new_nodes.append(refnode)
         if not new_nodes:
             continue
         tail = text[last_issue_ref_end:]
         if tail:
             new_nodes.append(nodes.Text(tail))
         parent.replace(node, new_nodes)
Exemplo n.º 10
0
Arquivo: std.py Projeto: qsnake/sphinx
 def resolve_xref(self, env, fromdocname, builder,
                  typ, target, node, contnode):
     if typ == 'ref':
         if node['refexplicit']:
             # reference to anonymous label; the reference uses
             # the supplied link caption
             docname, labelid = self.data['anonlabels'].get(target, ('',''))
             sectname = node.astext()
         else:
             # reference to named label; the final node will
             # contain the section name after the label
             docname, labelid, sectname = self.data['labels'].get(target,
                                                                  ('','',''))
         if not docname:
             return None
         newnode = nodes.reference('', '', internal=True)
         innernode = nodes.emphasis(sectname, sectname)
         if docname == fromdocname:
             newnode['refid'] = labelid
         else:
             # set more info in contnode; in case the
             # get_relative_uri call raises NoUri,
             # the builder will then have to resolve these
             contnode = addnodes.pending_xref('')
             contnode['refdocname'] = docname
             contnode['refsectname'] = sectname
             newnode['refuri'] = builder.get_relative_uri(
                 fromdocname, docname)
             if labelid:
                 newnode['refuri'] += '#' + labelid
         newnode.append(innernode)
         return newnode
     elif typ == 'keyword':
         # keywords are oddballs: they are referenced by named labels
         docname, labelid, _ = self.data['labels'].get(target, ('','',''))
         if not docname:
             return None
         return make_refnode(builder, fromdocname, docname,
                             labelid, contnode)
     elif typ == 'option':
         progname = node['refprogram']
         docname, labelid = self.data['progoptions'].get((progname, target),
                                                         ('', ''))
         if not docname:
             return None
         return make_refnode(builder, fromdocname, docname,
                             labelid, contnode)
     else:
         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)
Exemplo n.º 11
0
 def make_xref(self, rolename, domain, target,
               innernode=addnodes.literal_emphasis, contnode=None):
     if not rolename:
         return contnode or innernode(target, target)
     refnode = addnodes.pending_xref('', refdomain=domain, refexplicit=False,
                                     reftype=rolename, reftarget=target)
     refnode += contnode or innernode(target, target)
     return refnode
Exemplo n.º 12
0
 def format_type(t):
     ref = addnodes.pending_xref(
         t, addnodes.literal_emphasis(t, t),
         refdomain='js', reftype='class', reftarget=t,
     )
     if mod:
         ref['js:module'] = mod
     return ref
Exemplo n.º 13
0
 def handle_signature(self, sig, signode):
   name = self.options['name']
   parameters = json.loads(self.options['parameters']) if 'parameters' in self.options else []
   return_v = json.loads(self.options['return']) if 'return' in self.options else ("","")
   prefix = self.options['prefix'] if 'prefix' in self.options else ""
 
   if not ('parameters' in self.options) or not ('return' in self.options):
     print("WARNING: No parameters or return set for '" + name + "'")
   
   signode += nodes.Text(prefix + ' ', prefix + u'\xa0')
   xref = addnodes.pending_xref(
     ':ref:`' + return_v[1] + '`',
     refdomain='std',
     reftype='ref',
     reftarget=ws_re.sub(' ', return_v[1].lower()),
     refexplicit=False)
   xref += nodes.Text(return_v[0], return_v[0])
   signode += xref
   signode += nodes.Text(' ', u'\xa0')
     
   signode += addnodes.desc_name(name, name)
   paramlist = addnodes.desc_parameterlist()
   for tn in parameters:
     param = addnodes.desc_parameter('', '', noemph=True)
     prefix = ''
     if len(tn) > 3 and tn[3] == "True":
       prefix += "ref "
     if len(tn) > 4 and tn[4] == "True":
       prefix += "out "
     
     if prefix != "":
       param += nodes.Text(prefix + ' ', prefix + u'\xa0')
       
     xref = addnodes.pending_xref(
       ':ref:`' + tn[2] + '`',
       refdomain='std',
       reftype='ref',
       reftarget=ws_re.sub(' ', tn[2].lower()),
       refexplicit=False)
     xref += nodes.Text(tn[0], tn[0])
     param += xref
     param += nodes.emphasis(' '+tn[1], u'\xa0'+tn[1])
     paramlist += param
   signode += paramlist
   
   return name, ""
Exemplo n.º 14
0
def get_xref(typ, target, title=None):
    if title is None:
        title = target
    ref = addnodes.pending_xref(title,
                                reftype=typ,
                                refdomain="xml",
                                reftarget=target)
    ref.append(nodes.literal(title, title))
    return ref
Exemplo n.º 15
0
def doctree_read(app, doctree):
    env = app.builder.env
    if not hasattr(env, "_viewcode_modules"):
        env._viewcode_modules = {}

    def has_tag(modname, fullname, docname):
        entry = env._viewcode_modules.get(modname, None)
        try:
            analyzer = ModuleAnalyzer.for_module(modname)
        except Exception:
            env._viewcode_modules[modname] = False
            return
        if not isinstance(analyzer.code, str):
            code = analyzer.code.decode(analyzer.encoding)
        else:
            code = analyzer.code
        if entry is None or entry[0] != code:
            analyzer.find_tags()
            entry = code, analyzer.tags, {}
            env._viewcode_modules[modname] = entry
        elif entry is False:
            return
        code, tags, used = entry
        if fullname in tags:
            used[fullname] = docname
            return True

    for objnode in doctree.traverse(addnodes.desc):
        if objnode.get("domain") != "py":
            continue
        names = set()
        for signode in objnode:
            if not isinstance(signode, addnodes.desc_signature):
                continue
            modname = signode.get("module")
            if not modname:
                continue
            fullname = signode.get("fullname")
            if not has_tag(modname, fullname, env.docname):
                continue
            if fullname in names:
                # only one link per name, please
                continue
            names.add(fullname)
            pagename = "_modules/" + modname.replace(".", "/")
            onlynode = addnodes.only(expr="html")
            onlynode += addnodes.pending_xref(
                "",
                reftype="viewcode",
                refdomain="std",
                refexplicit=False,
                reftarget=pagename,
                refid=fullname,
                refdoc=env.docname,
            )
            onlynode[0] += nodes.inline("", _("[source]"), classes=["viewcode-link"])
            signode += onlynode
Exemplo n.º 16
0
 def attach_type(self, node, type):
     # XXX: link to c?
     text = unicode(type)
     pnode = addnodes.pending_xref(
         '', refdomain='matlab', reftype='type',
         reftarget=text, modname=None, classname=None)
     pnode['matlab:parent'] = self.env.temp_data.get('matlab:parent')
     pnode += nodes.Text(text)
     node += pnode
Exemplo n.º 17
0
 def apply(self):
     for citnode in self.document.traverse(nodes.citation_reference):
         cittext = citnode.astext()
         refnode = addnodes.pending_xref(cittext, reftype='citation',
                                         reftarget=cittext, refwarn=True,
                                         ids=citnode["ids"])
         refnode.line = citnode.line or citnode.parent.line
         refnode += nodes.Text('[' + cittext + ']')
         citnode.parent.replace(citnode, refnode)
Exemplo n.º 18
0
 def fake_node(domain, type, target, content, **attrs):
     contnode = nodes.emphasis(content, content)
     node = addnodes.pending_xref("")
     node["reftarget"] = target
     node["reftype"] = type
     node["refdomain"] = domain
     node.attributes.update(attrs)
     node += contnode
     return node, contnode
Exemplo n.º 19
0
def doctree_read(app, doctree):
    env = app.builder.env
    if not hasattr(env, '_viewcode_modules'):
        env._viewcode_modules = {}

    def has_tag(modname, fullname, docname, refname):
        entry = env._viewcode_modules.get(modname, None)
        try:
            analyzer = ModuleAnalyzer.for_module(modname)
        except Exception:
            env._viewcode_modules[modname] = False
            return
        if not isinstance(analyzer.code, text_type):
            code = analyzer.code.decode(analyzer.encoding)
        else:
            code = analyzer.code
        if entry is None or entry[0] != code:
            analyzer.find_tags()
            entry = code, analyzer.tags, {}, refname
            env._viewcode_modules[modname] = entry
        elif entry is False:
            return
        _, tags, used, _ = entry
        if fullname in tags:
            used[fullname] = docname
            return True

    for objnode in doctree.traverse(addnodes.desc):
        if objnode.get('domain') != 'py':
            continue
        names = set()
        for signode in objnode:
            if not isinstance(signode, addnodes.desc_signature):
                continue
            modname = signode.get('module')
            fullname = signode.get('fullname')
            refname = modname
            if env.config.viewcode_import:
                modname = _get_full_modname(app, modname, fullname)
            if not modname:
                continue
            fullname = signode.get('fullname')
            if not has_tag(modname, fullname, env.docname, refname):
                continue
            if fullname in names:
                # only one link per name, please
                continue
            names.add(fullname)
            pagename = '_modules/' + modname.replace('.', '/')
            onlynode = addnodes.only(expr='html')
            onlynode += addnodes.pending_xref(
                '', reftype='viewcode', refdomain='std', refexplicit=False,
                reftarget=pagename, refid=fullname,
                refdoc=env.docname)
            onlynode[0] += nodes.inline('', _('[source]'),
                                        classes=['viewcode-link'])
            signode += onlynode
Exemplo n.º 20
0
 def make_checker_chaining(self):
     symbol = self.lookup_auto_symbol()
     if not symbol:
         return
     next_checkers = symbol.properties.get('flycheck-next-checkers')
     if not next_checkers:
         return
     title = nodes.title('', 'Chained syntax checkers')
     intro = nodes.paragraph()
     intro += nodes.Text('The following syntax checkers are ')
     chained = addnodes.pending_xref(
         'chained', reftype='term', refdomain='std', reftarget='chaining',
         refwarn=True, refexplicit=True, reftitle='chaining',
         refdoc=self.env.docname)
     chained += nodes.emphasis('', 'chained')
     intro += chained
     intro += nodes.Text(' after this syntax checker:')
     checker_list = nodes.enumerated_list()
     para = nodes.paragraph()
     para += checker_list
     outro = nodes.paragraph()
     outro += nodes.Text('The ')
     outro += nodes.strong('', 'first')
     outro += nodes.Text(' suitable syntax checker is used.')
     chaining = nodes.admonition(
         '', title, intro, para, outro,
         classes=['note', 'el-flycheck-checker-chaining'])
     for next_checker in next_checkers:
         xref = addnodes.pending_xref(
             next_checker.checker,
             reftype='flyc-checker', refdomain='el',
             refexplicit=False, reftarget=next_checker.checker,
             refwarn=False, refdoc=self.env.docname)
         set_role_source_info(self.state.inliner, self.lineno, xref)
         xref += nodes.literal('', next_checker.checker,
                               classes=['xref', 'el', 'el-flyc-checker'])
         para = nodes.paragraph()
         para += xref
         if next_checker.warnings_only:
             para += nodes.Text(', if there are only warnings')
         if next_checker.no_errors:
             para += nodes.Text(', if there are no errors')
         checker_list += nodes.list_item('', para)
     return chaining
Exemplo n.º 21
0
    def handle_signature(self, sig, signode):
        if self.display_prefix:
            signode += addnodes.desc_annotation(self.display_prefix, self.display_prefix)

        name = self.options["name"]
        namespace = self.options["namespace"]
        fullname = self.options["fullname"]
        inherits = json.loads(self.options["inherits"]) if "inherits" in self.options else ("", "")
        implements = json.loads(self.options["implements"]) if "implements" in self.options else []

        signode += addnodes.desc_name(name, name)

        toappend = []

        if inherits[0] != "Object" and inherits[0] != "Enum" and inherits[0] != "":
            xref = addnodes.pending_xref(
                ":ref:`" + inherits[1] + "`",
                refdomain="std",
                reftype="ref",
                reftarget=ws_re.sub(" ", inherits[1].lower()),
                refexplicit=False,
            )
            xref += nodes.Text(inherits[0], inherits[0])
            toappend.append(xref)

        for implement in implements:
            if len(toappend) > 0:
                toappend.append(nodes.Text(", ", u",\xa0"))
            xref = addnodes.pending_xref(
                ":ref:`" + implement[1] + "`",
                refdomain="std",
                reftype="ref",
                reftarget=ws_re.sub(" ", implement[1].lower()),
                refexplicit=False,
            )
            xref += nodes.Text(implement[0], implement[0])
            toappend.append(xref)

        if len(toappend) > 0:
            signode += nodes.Text(" : ", u"\xa0:\xa0")
            for a in toappend:
                signode += a

        return name, namespace
Exemplo n.º 22
0
 def handle_signature(self, sig, signode):
   if self.display_prefix:
     signode += addnodes.desc_annotation(self.display_prefix,
                                         self.display_prefix)
     
   name = self.options['name']
   namespace = self.options['namespace']
   fullname = self.options['fullname']
   inherits = json.loads(self.options['inherits']) if 'inherits' in self.options else ("","")
   implements = json.loads(self.options['implements']) if 'implements' in self.options else []
     
   signode += addnodes.desc_name(name, name)
   
   toappend = []
   
   if inherits[0] != "Object" and inherits[0] != "Enum" and inherits[0] != "":
     xref = addnodes.pending_xref(
       ':ref:`' + inherits[1] + '`',
       refdomain='std',
       reftype='ref',
       reftarget=ws_re.sub(' ', inherits[1].lower()),
       refexplicit=False)
     xref += nodes.Text(inherits[0], inherits[0])
     toappend.append(xref)
   
   for implement in implements:
     if len(toappend) > 0:
       toappend.append(nodes.Text(', ', u',\xa0'))
     xref = addnodes.pending_xref(
       ':ref:`' + implement[1] + '`',
       refdomain='std',
       reftype='ref',
       reftarget=ws_re.sub(' ', implement[1].lower()),
       refexplicit=False)
     xref += nodes.Text(implement[0], implement[0])
     toappend.append(xref)
   
   if len(toappend) > 0:
     signode += nodes.Text(' : ', u'\xa0:\xa0')
     for a in toappend:
       signode += a
   
   return name, namespace
    def crossreference_title_ref(self, node, name, desc_type):
        nodetext = node.children[0].astext()
        reftype = DESCTYPE_TO_REFTYPE.get(desc_type, desc_type)

        newnode = pending_xref(nodetext, reftype=reftype, reftarget=name, modname=None, classname=None)
        node.replace_self(newnode)
        newnode += literal(nodetext, nodetext, classes=['xref'])

        # Yay, we found a new ref!
        self.new_pending_refs = True
Exemplo n.º 24
0
def parse_c_type(node, ctype):
    # add cross-ref nodes for all words
    for part in filter(None, wsplit_re.split(ctype)):
        tnode = nodes.Text(part, part)
        if part[0] in string.letters+'_' and part not in stopwords:
            pnode = addnodes.pending_xref(
                '', reftype='ctype', reftarget=part, modname=None, classname=None)
            pnode += tnode
            node += pnode
        else:
            node += tnode
Exemplo n.º 25
0
Arquivo: sphinx.py Projeto: Janno/coq
    def visitHole(self, ctx:TacticNotationsParser.HoleContext):
        hole = ctx.ID().getText()
        token_name = hole[1:]
        node = nodes.inline(hole, token_name, classes=["hole"])

        sub = ctx.SUB()
        if sub:
            sub_index = sub.getText()[2:]
            node += nodes.subscript(sub_index, sub_index)

        return [addnodes.pending_xref(token_name, node, reftype='token', refdomain='std', reftarget=token_name)]
Exemplo n.º 26
0
 def __make_list(self, obj, _lst, _type):
     def get_entry(node):
         para = addnodes.compact_paragraph()
         para += node
         entry = nodes.entry()
         entry += para
         return entry
     table, body, tgroup = nodes.table(), nodes.tbody(), nodes.tgroup(cols=2)
     thead = nodes.thead()
     tgroup += nodes.colspec(colwidth=20)
     tgroup += nodes.colspec(colwidth=80)
     tgroup += thead
     tgroup += body
     table += tgroup
     head_row = nodes.row()
     head_row += get_entry(nodes.Text('Name'))
     head_row += get_entry(nodes.Text('Brief'))
     thead += head_row
     kwargs = {
         'refdomain': 'cpp',
         'refexplicit': False,
         'reftype': _type,
     }
     for it in sorted(_lst):
         row = nodes.row()
         subobj = self._get_obj(unicode(it.get_name()))
         if subobj is not None:
             kwargs['reftarget'] = unicode(it.get_name())
             ref = addnodes.pending_xref('', **kwargs)
             ref += nodes.literal(text=unicode(subobj.name))
         else:
             kwargs['reftarget'] = unicode(it.name)
             ref = addnodes.pending_xref('', **kwargs)
             ref += nodes.literal(text=unicode(it.name))
         row += get_entry(ref)
         texts = None
         if subobj is not None and subobj.brief():
             texts = nodes.Text(' '.join(subobj.brief()))
         row += get_entry(texts)
         body += row
     return table
Exemplo n.º 27
0
 def make_signature(self):
     ret = super(PropertyDocumenter, self).make_signature()
     proptype = self.item.type
     if proptype:
         typeref = addnodes.pending_xref(
             proptype, nodes.Text(proptype, proptype),
             refdomain='js', reftype='class', reftarget=proptype
         )
         typeref['js:module'] = self.item['sourcemodule'].name
         ret.append(nodes.Text(' '))
         ret.append(typeref)
     return ret
Exemplo n.º 28
0
 def apply(self):
     config = self.document.settings.env.config
     tracker_config = TrackerConfig.from_sphinx_config(config)
     issue_pattern = config.issuetracker_issue_pattern
     title_template = config.issuetracker_title_template
     if isinstance(issue_pattern, basestring):
         issue_pattern = re.compile(issue_pattern)
     for node in self.document.traverse(nodes.Text):
         parent = node.parent
         if isinstance(parent, (nodes.literal, nodes.FixedTextElement)):
             # ignore inline and block literal text
             continue
         text = unicode(node)
         new_nodes = []
         last_issue_ref_end = 0
         for match in issue_pattern.finditer(text):
             # catch invalid pattern with too many groups
             if len(match.groups()) != 1:
                 raise ValueError(
                     'issuetracker_issue_pattern must have '
                     'exactly one group: {0!r}'.format(match.groups()))
             # extract the text between the last issue reference and the
             # current issue reference and put it into a new text node
             head = text[last_issue_ref_end:match.start()]
             if head:
                 new_nodes.append(nodes.Text(head))
             # adjust the position of the last issue reference in the
             # text
             last_issue_ref_end = match.end()
             # extract the issue text (including the leading dash)
             issuetext = match.group(0)
             # extract the issue number (excluding the leading dash)
             issue_id = match.group(1)
             # turn the issue reference into a reference node
             refnode = pending_xref()
             refnode['reftarget'] = issue_id
             refnode['reftype'] = 'issue'
             refnode['trackerconfig'] = tracker_config
             reftitle = title_template or issuetext
             refnode.append(nodes.inline(
                 issuetext, reftitle, classes=['xref', 'issue']))
             new_nodes.append(refnode)
         if not new_nodes:
             # no issue references were found, move on to the next node
             continue
         # extract the remaining text after the last issue reference, and
         # put it into a text node
         tail = text[last_issue_ref_end:]
         if tail:
             new_nodes.append(nodes.Text(tail))
         # find and remove the original node, and insert all new nodes
         # instead
         parent.replace(node, new_nodes)
Exemplo n.º 29
0
 def make_field(self, types, domain, item, env=None):
     fieldname = nodes.field_name('', self.label)
     backref = addnodes.pending_xref(
         '',
         refdomain="conda",
         reftype='requiredby', refexplicit=False,
         reftarget=env.ref_context['conda:package'],
         refdoc=env.docname
     )
     backref += nodes.inline('', '')
     fieldbody = nodes.field_body('', backref)
     return nodes.field('', fieldname, fieldbody)
Exemplo n.º 30
0
 def data(self, obj):
     data = obj.attrs[self.field.name]
     if data is None:
         return nodes.Text('-', '-')
     elif data is ...:
         return nodes.Text('?', '?')
     else:
         ref = addnodes.pending_xref(
             '', refdomain='envy', reftype='genobj', reftarget=data.slug,
         )
         ref += nodes.Text(data.name, data.name)
         return ref
Exemplo n.º 31
0
 def make_signature(self):
     cls = self.item.cls
     ret = super(InstanceDocumenter, self).make_signature()
     if cls:
         super_ref = addnodes.pending_xref(
             cls.name, nodes.Text(cls.name, cls.name),
             refdomain='js', reftype='class', reftarget=cls.name
         )
         super_ref['js:module'] = cls['sourcemodule'].name
         ret.append(addnodes.desc_annotation(' instance of ', ' instance of '))
         ret.append(addnodes.desc_type(cls.name, '', super_ref))
     if not ret:
         return [addnodes.desc_name('???', '???')]
     return ret
Exemplo n.º 32
0
 def apply(self):
     # type: () -> None
     for citnode in self.document.traverse(nodes.citation_reference):
         cittext = citnode.astext()
         refnode = addnodes.pending_xref(cittext,
                                         refdomain='std',
                                         reftype='citation',
                                         reftarget=cittext,
                                         refwarn=True,
                                         ids=citnode["ids"])
         refnode.source = citnode.source or citnode.parent.source
         refnode.line = citnode.line or citnode.parent.line
         refnode += nodes.Text('[' + cittext + ']')
         citnode.parent.replace(citnode, refnode)
Exemplo n.º 33
0
 def _parse_type(self, node, ctype):
     # type: (nodes.Element, str) -> None
     # add cross-ref nodes for all words
     for part in [_f for _f in wsplit_re.split(ctype) if _f]:
         tnode = nodes.Text(part, part)
         if part[0] in string.ascii_letters + '_' and \
            part not in self.stopwords:
             pnode = addnodes.pending_xref(
                 '', refdomain='c', reftype='type', reftarget=part,
                 modname=None, classname=None)
             pnode += tnode
             node += pnode
         else:
             node += tnode
Exemplo n.º 34
0
    def run(self):
        version = self.arguments[0].strip()

        node = xnodes.div(classes=["x-version-added"])
        node += nodes.Text("New in version ")
        node += nodes.inline(
            "", "",
            addnodes.pending_xref("",
                                  nodes.Text(version),
                                  refdomain="std",
                                  reftype="doc",
                                  refexplicit=True,
                                  reftarget="/releases/" + version))
        return [node]
Exemplo n.º 35
0
def parse_c_type(node, ctype):
    # add cross-ref nodes for all words
    for part in filter(None, wsplit_re.split(ctype)):
        tnode = nodes.Text(part, part)
        if part[0] in string.letters + '_' and part not in stopwords:
            pnode = addnodes.pending_xref('',
                                          reftype='ctype',
                                          reftarget=part,
                                          modname=None,
                                          classname=None)
            pnode += tnode
            node += pnode
        else:
            node += tnode
Exemplo n.º 36
0
    def run(self):
        tree = self.state.document.settings.env.app.doxyxml

        table = nodes.table()
        tgroup = nodes.tgroup(cols=2)

        tgroup += nodes.colspec(colwidth=50)
        tgroup += nodes.colspec(colwidth=50)

        # header
        tgroup += nodes.thead(
            '',
            nodes.row(
                '', *[
                    nodes.entry('', nodes.line(text=c))
                    for c in ["Function", "Description"]
                ]))

        # rows
        tbody = nodes.tbody()
        for c in self.content:
            name = c.strip()
            query = name.replace("&", " &")

            for elem in tree.findall(
                    "./compounddef/sectiondef/memberdef/[name='%s']" % query):
                args = ', '.join(e.text
                                 for e in elem.findall("./param/declname"))

                ref = addnodes.pending_xref('',
                                            refdomain='cpp',
                                            refexplicit=False,
                                            reftype='func',
                                            reftarget='kitty::' + name)
                ref += nodes.literal(text='%s(%s)' % (name, args))

                reft = nodes.paragraph()
                reft.extend([ref])

                func = nodes.entry('', reft)
                desc = nodes.entry(
                    '',
                    nodes.line(text=elem.findtext("./briefdescription/para")))

                tbody += nodes.row('', func, desc)

        tgroup += tbody
        table += tgroup
        return [table]
Exemplo n.º 37
0
    def run(self):
        missing_options = set(self.option_spec).difference(self.options)
        if missing_options:
            raise ValueError(f"Missing options: {missing_options!r};"
                             f" content: {list(self.content)!r}")
        try:
            wires = getattr(self.env.app, KEY)
        except AttributeError:
            wires = []
            setattr(self.env.app, KEY, wires)
        wires.append(
            WireInfo(
                value=self.content[0],
                type=self.options["type"],
                runtime=self.options["runtime"],
                config=self.options["config"],
                requirements=self.options["requirements"].split(),
            ))

        node = addnodes.desc()
        node["objtype"] = "wire"
        signode = addnodes.desc_signature("", "")
        signode += addnodes.desc_annotation("type", "type:")
        signode += addnodes.desc_name(self.options["type"],
                                      self.options["type"])
        signode += addnodes.desc_annotation("config", "config:")
        signode += addnodes.pending_xref(
            "",
            addnodes.desc_addname(self.options["config"],
                                  self.options["config"]),
            refdomain="proto",
            reftype="message",
            reftarget=self.options["config"],
        )
        node.append(signode)

        contentnode = addnodes.desc_content()
        if self.options["requirements"]:
            contentnode += nodes.paragraph("", "Requirements:")
            bullet_list = nodes.bullet_list("")
            for requirement in self.options["requirements"].split():
                bullet_list += nodes.list_item("",
                                               nodes.literal("", requirement))
            contentnode += bullet_list
        else:
            contentnode += nodes.paragraph("", "No requirements")
        node.append(contentnode)

        return [node]
Exemplo n.º 38
0
    def make_super(self):
        doc = self.item
        if not doc.superclass:
            return []

        sup_link = addnodes.pending_xref(
            doc.superclass.name, nodes.paragraph(doc.superclass.name, doc.superclass.name),
            refdomain='js', reftype='class', reftarget=doc.superclass.name,
        )
        sup_link['js:module'] = doc.superclass['sourcemodule'].name
        return nodes.field(
            '',
            nodes.field_name("Extends", "Extends"),
            nodes.field_body(doc.superclass.name, sup_link),
        )
Exemplo n.º 39
0
def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xref:
    """Convert a type string to a cross reference node."""
    if text == 'None':
        reftype = 'obj'
    else:
        reftype = 'class'

    if env:
        kwargs = {'py:module': env.ref_context.get('py:module'),
                  'py:class': env.ref_context.get('py:class')}
    else:
        kwargs = {}

    return pending_xref('', nodes.Text(text),
                        refdomain='py', reftype=reftype, reftarget=text, **kwargs)
Exemplo n.º 40
0
 def apply(self, **kwargs):
     # type: (Any) -> None
     for node in self.document.traverse(nodes.citation_reference):
         target = node.astext()
         ref = addnodes.pending_xref(target,
                                     refdomain='std',
                                     reftype='citation',
                                     reftarget=target,
                                     refwarn=True,
                                     support_smartquotes=False,
                                     ids=node["ids"],
                                     classes=node.get('classes', []))
         ref += nodes.inline(target, '[%s]' % target)
         copy_source_info(node, ref)
         node.replace_self(ref)
Exemplo n.º 41
0
def create_ref_node(raw_text, text, target):
    if not target:
        return nodes.Text(text, text)

    if url_re_prog.match(target):
        return nodes.reference(raw_text, text, refuri=target)

    node = addnodes.pending_xref(raw_text)
    node['reftype'] = 'ref'
    node['refdomain'] = 'std'
    node['reftarget'] = target
    node['refwarn'] = True
    node['refexplicit'] = True
    node += nodes.Text(text, text)
    return node
Exemplo n.º 42
0
    def apply(self, **kwargs: Any) -> None:
        domain = cast(CitationDomain, self.env.get_domain('citation'))
        for node in self.document.findall(nodes.citation_reference):
            target = node.astext()
            ref = pending_xref(target, refdomain='citation', reftype='ref',
                               reftarget=target, refwarn=True,
                               support_smartquotes=False,
                               ids=node["ids"],
                               classes=node.get('classes', []))
            ref += nodes.inline(target, '[%s]' % target)
            copy_source_info(node, ref)
            node.replace_self(ref)

            # register reference node to domain
            domain.note_citation_reference(ref)
Exemplo n.º 43
0
Arquivo: std.py Projeto: th0/test2
def token_xrefs(text):
    retnodes = []
    pos = 0
    for m in token_re.finditer(text):
        if m.start() > pos:
            txt = text[pos:m.start()]
            retnodes.append(nodes.Text(txt, txt))
        refnode = addnodes.pending_xref(
            m.group(1), reftype='token', refdomain='std', reftarget=m.group(1))
        refnode += nodes.literal(m.group(1), m.group(1), classes=['xref'])
        retnodes.append(refnode)
        pos = m.end()
    if pos < len(text):
        retnodes.append(nodes.Text(text[pos:], text[pos:]))
    return retnodes
Exemplo n.º 44
0
    def _generate_sigbody(self, node):
        row1 = xnodes.div(classes=["sig-qualifier"])
        ref = addnodes.pending_xref("",
                                    nodes.Text(self.qualifier),
                                    reftarget=self.qualifier[:-1],
                                    reftype="class",
                                    refdomain="py")
        # Note: `ref` cannot be added directly: docutils requires that
        # <reference> nodes were nested inside <TextElement> nodes.
        row1 += nodes.generated("", "", ref)
        node += row1

        row2 = xnodes.div(classes=["sig-main"])
        self._generate_sigmain(row2)
        node += row2
Exemplo n.º 45
0
 def make_xref(self,
               rolename,
               domain,
               target,
               innernode=addnodes.literal_emphasis,
               contnode=None):
     if not rolename:
         return contnode or innernode(target, target)
     refnode = addnodes.pending_xref('',
                                     refdomain=domain,
                                     refexplicit=False,
                                     reftype=rolename,
                                     reftarget=target)
     refnode += contnode or innernode(target, target)
     return refnode
Exemplo n.º 46
0
    def visit_link(self, mdnode):
        ref_node = nodes.reference()
        # Check destination is supported for cross-linking and remove extension
        destination = mdnode.destination
        _, ext = splitext(destination)

        # Check if the destination starts with a url scheme, since internal and
        # external links need to be handled differently.
        url_check = urlparse(destination)
        known_url_schemes = self.config.get('known_url_schemes')
        if known_url_schemes:
            scheme_known = url_check.scheme in known_url_schemes
        else:
            scheme_known = bool(url_check.scheme)

        # TODO check for other supported extensions, such as those specified in
        # the Sphinx conf.py file but how to access this information?
        if not scheme_known and ext.replace('.', '') in self.supported:
            destination = destination.replace(ext, '')
        ref_node['refuri'] = destination
        # TODO okay, so this is acutally not always the right line number, but
        # these mdnodes won't have sourcepos on them for whatever reason. This
        # is better than 0 though.
        ref_node.line = self._get_line(mdnode)
        if mdnode.title:
            ref_node['title'] = mdnode.title
        next_node = ref_node

        # If there's not a url scheme (e.g. 'https' for 'https:...' links),
        # or there is a scheme but it's not in the list of known_url_schemes,
        # then assume it's a cross-reference and pass it to Sphinx as an `:any:` ref.
        if not url_check.fragment and not scheme_known:
            wrap_node = addnodes.pending_xref(
                reftarget=unquote(destination),
                reftype='any',
                refdomain=None,  # Added to enable cross-linking
                refexplicit=True,
                refwarn=True
            )
            # TODO also not correct sourcepos
            wrap_node.line = self._get_line(mdnode)
            if mdnode.title:
                wrap_node['title'] = mdnode.title
            wrap_node.append(ref_node)
            next_node = wrap_node

        self.current_node.append(next_node)
        self.current_node = ref_node
Exemplo n.º 47
0
def label_ref_node(docname, ref_to, title):
    """Generate a node that references a label"""
    txt = Text(title, rawsource=title)
    newchild = inline(':ref:`%s`' % ref_to,
                      '',
                      txt,
                      classes=['xref', 'std', 'std-ref'])
    newnode = pending_xref(':ref:`%s`' % ref_to,
                           newchild,
                           reftype='ref',
                           refwarn='True',
                           reftarget=ref_to,
                           refexplicit='False',
                           refdomain='std',
                           refdoc=docname)
    return newnode
Exemplo n.º 48
0
 def _parse_type(self, node, gotype):
     # add cross-ref nodes for all words
     for part in filter(None, wsplit_re.split(gotype)):
         tnode = nodes.Text(part, part)
         if part[0] in string.ascii_letters+'_' and \
                part not in self.stopwords:
             pnode = addnodes.pending_xref('',
                                           refdomain='go',
                                           reftype='type',
                                           reftarget=part,
                                           modname=None,
                                           classname=None)
             pnode += tnode
             node += pnode
         else:
             node += tnode
Exemplo n.º 49
0
    def apply(self):
        # type: () -> None
        # mark citation labels as not smartquoted
        for citnode in self.document.traverse(nodes.citation):
            citnode[0]['support_smartquotes'] = False

        for citnode in self.document.traverse(nodes.citation_reference):
            cittext = citnode.astext()
            refnode = addnodes.pending_xref(cittext, refdomain='std', reftype='citation',
                                            reftarget=cittext, refwarn=True,
                                            support_smartquotes=False,
                                            ids=citnode["ids"])
            refnode.source = citnode.source or citnode.parent.source
            refnode.line = citnode.line or citnode.parent.line
            refnode += nodes.Text('[' + cittext + ']')
            citnode.parent.replace(citnode, refnode)
Exemplo n.º 50
0
    def make_mixins(self):
        doc = self.item
        if not doc.mixins:
            return []

        ret = nodes.field('', nodes.field_name("Mixes", "Mixes"))
        with addto(ret, nodes.field_body()) as body:
            with addto(body, nodes.bullet_list()) as mixins:
                for mixin in sorted(doc.mixins, key=lambda m: m.name):
                    mixin_link = addnodes.pending_xref(
                        mixin.name, nodes.paragraph(mixin.name, mixin.name),
                        refdomain='js', reftype='mixin', reftarget=mixin.name
                    )
                    mixin_link['js:module'] = mixin['sourcemodule'].name
                    mixins += nodes.list_item('', mixin_link)
        return ret
Exemplo n.º 51
0
def markup_funcs(docname, app, node):
    cdom = app.env.domains['c']
    t = node.astext()
    done = 0
    repl = []
    for m in RE_function.finditer(t):
        #
        # Include any text prior to function() as a normal text node.
        #
        if m.start() > done:
            repl.append(nodes.Text(t[done:m.start()]))
        #
        # Go through the dance of getting an xref out of the C domain
        #
        target = m.group(1)[:-2]
        target_text = nodes.Text(target + '()')
        xref = None
        if target not in Skipfuncs:
            lit_text = nodes.literal(classes=['xref', 'c', 'c-func'])
            lit_text += target_text
            pxref = addnodes.pending_xref('',
                                          refdomain='c',
                                          reftype='function',
                                          reftarget=target,
                                          modname=None,
                                          classname=None)
            #
            # XXX The Latex builder will throw NoUri exceptions here,
            # work around that by ignoring them.
            #
            try:
                xref = cdom.resolve_xref(app.env, docname, app.builder,
                                         'function', target, pxref, lit_text)
            except NoUri:
                xref = None
        #
        # Toss the xref into the list if we got it; otherwise just put
        # the function text.
        #
        if xref:
            repl.append(xref)
        else:
            repl.append(target_text)
        done = m.end()
    if done < len(t):
        repl.append(nodes.Text(t[done:]))
    return repl
Exemplo n.º 52
0
def handle_method(signature_node, module, object_name, cache):
    """
    Styles ``automethod`` entries.

    Adds link to originating class for inherited methods.
    """
    *class_names, attr_name = object_name.split(".")  # Handle nested classes
    class_ = module
    for class_name in class_names:
        class_ = getattr(class_, class_name, None)
        if class_ is None:
            return
    try:
        inspected_attr = cache[class_][attr_name]
        defining_class = inspected_attr.defining_class
    except KeyError:
        # TODO: This is a hack to handle bad interaction between enum and inspect
        defining_class = class_
    if defining_class is not class_:
        reftarget = "{}.{}".format(defining_class.__module__,
                                   defining_class.__name__)
        xref_node = addnodes.pending_xref("",
                                          refdomain="py",
                                          refexplicit=True,
                                          reftype="class",
                                          reftarget=reftarget)
        name_node = nodes.literal("",
                                  "{}".format(defining_class.__name__),
                                  classes=["descclassname"])
        xref_node.append(name_node)
        desc_annotation = list(
            signature_node.traverse(addnodes.desc_annotation))
        index = len(desc_annotation)
        class_annotation = addnodes.desc_addname()
        class_annotation.extend([nodes.Text("("), xref_node, nodes.Text(").")])
        class_annotation["xml:space"] = "preserve"
        signature_node.insert(index, class_annotation)
    else:
        is_overridden = False
        for class_ in defining_class.__mro__[1:]:
            if hasattr(class_, attr_name):
                is_overridden = True
        if is_overridden:
            emphasis = nodes.emphasis("overridden ",
                                      "overridden ",
                                      classes=["property"])
            signature_node.insert(0, emphasis)
Exemplo n.º 53
0
    def handle_signature(self, sig, signode):
        container_class_name = self.env.temp_data.get('kotlin:class')

        match = var_sig.match(sig)
        if not match:
            self.warn('invalid variable/constant documentation string "%s", ' %
                      sig)
            return

        match = match.groupdict()

        if self.objtype == 'var':
            signode += addnodes.desc_addname("var", "var ")
        elif self.objtype == 'val':
            signode += addnodes.desc_addname("val", "val ")

        name = match['name'].strip()
        signature = name
        signode += addnodes.desc_name(name, name)
        if match['type']:
            typ = match['type'].strip()
            #signature += '-' + typ
            # signode += addnodes.desc_type(typ, " : " + typ)
            # Add ref
            typeNode = addnodes.desc_type(' : ', ' : ')
            typeXref = addnodes.pending_xref('',
                                             refdomain='kotlin',
                                             reftype='type',
                                             reftarget=typ)
            typeXref += nodes.Text(typ, typ)
            typeNode += typeXref
            signode += typeNode

        if match['value'] and len(match['value']) > 0:
            value = match['value'].strip()
            signode += addnodes.desc_addname(value, " = " + value)
        elif match['value']:
            signode += addnodes.desc_addname('{ ... }', ' = { ... }')

        #signature += "-" + self.objtype

        if container_class_name:
            name = container_class_name + '.' + name
            signature = container_class_name + '.' + signature

        return name, signature, True
Exemplo n.º 54
0
def token_xrefs(text: str, productionGroup: str = '') -> List[Node]:
    if len(productionGroup) != 0:
        productionGroup += ':'
    retnodes = []  # type: List[Node]
    pos = 0
    for m in token_re.finditer(text):
        if m.start() > pos:
            txt = text[pos:m.start()]
            retnodes.append(nodes.Text(txt, txt))
        refnode = pending_xref(m.group(1), reftype='token', refdomain='std',
                               reftarget=productionGroup + m.group(1))
        refnode += nodes.literal(m.group(1), m.group(1), classes=['xref'])
        retnodes.append(refnode)
        pos = m.end()
    if pos < len(text):
        retnodes.append(nodes.Text(text[pos:], text[pos:]))
    return retnodes
Exemplo n.º 55
0
    def visitHole(self, ctx: TacticNotationsParser.HoleContext):
        hole = ctx.ID().getText()
        token_name = hole[1:]
        node = nodes.inline(hole, token_name, classes=["hole"])

        sub = ctx.SUB()
        if sub:
            sub_index = sub.getText()[2:]
            node += nodes.subscript(sub_index, sub_index)

        return [
            addnodes.pending_xref(token_name,
                                  node,
                                  reftype='token',
                                  refdomain='std',
                                  reftarget=token_name)
        ]
Exemplo n.º 56
0
def add_class_def(node, classDef):
    """Add reference on classDef to node """

    ref = addnodes.pending_xref(
        reftarget=classDef,
        reftype="class",
        refdomain=
        "py",  # py:class="None" py:module="altair" refdoc="user_guide/marks"
        refexplicit=False,
        # refdoc="",
        refwarn=False)
    ref["py:class"] = "None"
    ref["py:module"] = "altair"

    ref += nodes.literal(text=classDef, classes=["xref", "py", "py-class"])
    node += ref
    return node
Exemplo n.º 57
0
 def __init__(self, sexp, types=None, show_defaults=False):
     if not isinstance(sexp, list):
         self.sexp = _read(sexp)
     else:
         self.sexp = sexp
     self.types = types
     if self.types:
         for i, type in enumerate(self.types):
             type_node = addnodes.pending_xref('',
                                               refdomain='cl',
                                               reftype='type',
                                               reftarget=type)
             # type = " " + type
             type_node += addnodes.desc_type(type, type)
             self.sexp[i] = [self.sexp[i], type_node]
     self.show_defaults = show_defaults
     self.show_defaults = True
Exemplo n.º 58
0
 def make_xref(self,
               rolename,       # type: str
               domain,         # type: str
               target,         # type: str
               innernode=addnodes.literal_emphasis,  # type: Type[TextlikeNode]
               contnode=None,  # type: nodes.Node
               env=None,       # type: BuildEnvironment
               ):
     # type: (...) -> nodes.Node
     if not rolename:
         return contnode or innernode(target, target)
     refnode = addnodes.pending_xref('', refdomain=domain, refexplicit=False,
                                     reftype=rolename, reftarget=target)
     refnode += contnode or innernode(target, target)
     if env:
         env.get_domain(domain).process_field_xref(refnode)
     return refnode
Exemplo n.º 59
0
    def _build_ref_node(self, target):
        ref = addnodes.pending_xref('', refdomain='java', reftype='type', reftarget=target, modname=None, classname=None)
        ref['java:outertype'] = self.get_type()

        package = self.env.temp_data.get('java:imports', dict()).get(target, None)

        if not package and target in java_dot_lang:
            package = 'java.lang'

        if package:
            ref['java:imported'] = True
            ref['java:package'] = package
        else:
            ref['java:imported'] = False
            ref['java:package'] = self.get_package()

        return ref
Exemplo n.º 60
0
    def handle_signature(self, sig, signode):
        name = self.options['name']
        type_v = json.loads(self.options['type'])

        xref = addnodes.pending_xref(':ref:`' + type_v[1] + '`',
                                     refdomain='std',
                                     reftype='ref',
                                     reftarget=ws_re.sub(
                                         ' ', type_v[1].lower()),
                                     refexplicit=False)
        xref += nodes.Text(type_v[0], type_v[0])
        signode += xref
        signode += nodes.Text(' ', u'\xa0')

        signode += addnodes.desc_name(name, name)

        return name, ""