def run(self): if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = '', self.name self.env = self.state.document.settings.env self.indexnode = addnodes.index(entries=[]) obj = self.make_obj() node = addnodes.desc() node.document = self.state.document node['domain'] = self.domain # 'desctype' is a backwards compatible attribute node['objtype'] = node['desctype'] = self.objtype node['noindex'] = noindex = ('noindex' in self.options) node.name = obj.name obj.docname = self.env.docname objects = self.env.domaindata['envy']['objects'] signode = addnodes.desc_signature('', '') signode['first'] = True node.append(signode) self.make_signature(obj, signode) if not noindex and self.name not in objects: # only add target and index entry if this is the first # description of the object with this name in this desc block #self.add_target_and_index(self.name, sig, signode) nid = obj.iname + '-' + self.name signode['names'].append(nid) signode['ids'].append(nid) self.state.document.note_explicit_target(signode) for loc in self.locs: signode = addnodes.desc_signature('', '') signode['first'] = False node.append(signode) signode += addnodes.desc_name(loc, loc) node.append(uplink_placeholder(self.name)) if self.name in objects: other = objects[self.name] self.state_machine.reporter.warning('duplicate object {}, other instance in {}'.format(self.name, self.env.doc2path(other.docname))) objects[self.name] = obj contentnode = addnodes.desc_content() node.append(contentnode) self.env.temp_data['object'] = self.name self.state.nested_parse(self.content, self.content_offset, contentnode) self.env.temp_data['object'] = None contentnode += self.after_content() return [self.indexnode, node]
def render(self): title = self.title() rettype, name, arglist, const, signature = self.directive.parse_title(title) fullname = self.directive.get_full_name(name) if self.data_object.kind == "function": # set True that this might be a structure method self.directive.sphinx_directive.typemethod_set = True target = self.directive.create_target(fullname) if self.data_object.kind == "function": self.directive.sphinx_directive.typemethod_set = False # add a signature node signode = addnodes.desc_signature(signature, '') signode['first'] = False signode += addnodes.desc_type('', '') self.directive.add_return_type(signode[-1] , rettype) name = self.directive.add_sig_name(signode, name) self.directive.add_sig_args(signode, arglist, const) description_nodes = self.description() content_node = addnodes.desc_content('') content_node += description_nodes target.extend(signode) term = self.node_factory.term("","", ids=[name], *target ) entry = self.node_factory.definition_list_item("",term, content_node) return [entry]
def create_target(self, name): if not self.noindex and name not in self.sphinx_directive.names: # only add target and index entry if this is the first # description of the object with this name in this desc block self.sphinx_directive.names.append(name) if name not in self.sphinx_directive.state.document.ids: signode = addnodes.desc_signature() signode['names'].append(name) signode['ids'].append(name) signode['first'] = (not self.sphinx_directive.names) self.sphinx_directive.state.document.note_explicit_target(signode) inv = self.sphinx_directive.env.domaindata['c']['objects'] if name in inv: self.sphinx_directive.env.warn( self.sphinx_directive.env.docname, 'duplicate C object description of %s, ' % name + 'other instance in ' + self.sphinx_directive.env.doc2path(inv[name][0]), self.sphinx_directive.lineno) inv[name] = (self.sphinx_directive.env.docname, self.sphinx_directive.objtype) else: signode = [] indextext = self.get_index_text(name) if indextext: self.sphinx_directive.indexnode['entries'].append(('single', indextext, name, '')) return signode return []
def run(self): self.desctype = self.name self.env = self.state.document.settings.env self.indexnode = addnodes.index(entries=[]) node = addnodes.desc() node.document = self.state.document node['desctype'] = self.desctype node['noindex'] = noindex = ('noindex' in self.options) self.names = [] signatures = self.get_signatures() for i, sig in enumerate(signatures): # add a signature node for each signature in the current unit # and add a reference target for it signode = addnodes.desc_signature(sig, '') signode['first'] = False node.append(signode) try: # name can also be a tuple, e.g. (classname, objname) name = self.parse_signature(sig, signode) except ValueError, err: # signature parsing failed signode.clear() signode += addnodes.desc_name(sig, sig) continue # we don't want an index entry here if not noindex and name not in self.names: # only add target and index entry if this is the first # description of the object with this name in this desc block self.names.append(name) self.add_target_and_index(name, sig, signode)
def run(self): """Run this directive. In addition to the normal processing of the :class:`EmacsLispSymbol` directive, also prepend an additional signature that describes the keybinding of the documented command, if any. """ result_nodes = EmacsLispSymbol.run(self) # Insert a dedicated signature for the key binding before all other # signatures, but only for commands. Nothing else has key bindings. binding = self.options.get('binding') if binding: binding = self.with_prefix_arg(binding) desc_node = result_nodes[-1] assert isinstance(desc_node, addnodes.desc) signode = addnodes.desc_signature(binding, '') # No clue what this property is for, but ObjectDescription sets it # for its signatures, so we should do as well for our signature. signode['first'] = False desc_node.insert(0, signode) signode += addnodes.desc_name(binding, binding) return result_nodes
def run(self): #no good # node = nodes.paragraph('', 'Hi there!', # ids=['foo'], # names = ['foobar'] # ) #works # node = nodes.section(names=['foobar']) # self.state.document.note_explicit_target(node) # node.append(nodes.paragraph('', "foo foo")) #no good # node = nodes.admonition(names=['foobar']) # self.state.document.note_explicit_target(node) # node.append(nodes.paragraph('', "foo foo")) # node = nodes.paragraph('', 'foo foo', names=['foobar']) # self.state.document.note_explicit_target(node) #This doesn't properly render desc = addnodes.desc('', addnodes.desc_signature('', addnodes.desc_name('', 'namename'), addnodes.desc_parameterlist('', addnodes.desc_parameter('', 'def') ), names=['namename'], fullname="namename", ids=['namename'], module=None, first=False), desctype="function", domain="py", objtype='objtype') #no link (because didn't properly render?) self.state.document.note_explicit_target(desc) return [desc]
def render(self): title = self.title() rettype, name, arglist, const, signature = self.directive.parse_title(title) target = self.directive.create_target(name) # add a signature node signode = addnodes.desc_signature(signature, '') signode['first'] = False signode += addnodes.desc_type('', '') self.directive.add_return_type(signode[-1] , rettype) name = self.directive.add_sig_name(signode, name) self.directive.set_name(name) self.directive.add_sig_args(signode, arglist, const) self.directive.before_content() description_nodes = self.description() content_node = addnodes.desc_content('') content_node += description_nodes self.directive.after_content() target.extend(signode) term = self.node_factory.term("","", ids=[name], *target ) entry = self.node_factory.definition_list_item("",term, content_node) return [entry]
def envy_resolve(app, doctree, fromdocname): objects = app.env.domaindata['envy']['objects'] # add uplink info for holder in doctree.traverse(uplink_placeholder): obj = objects[holder.name] links = [] for sp, pos, name, variants in obj.uplinks: signode = addnodes.desc_signature('', '') signode['first'] = False signode += make_refnode(app.builder, fromdocname, sp.docname, sp.iname + '-' + sp.name, addnodes.desc_addname(sp.name, sp.name), sp.name) text = ' {}: {}'.format(pos, name) signode += addnodes.desc_name(text, text) if variants is not None: text = ' [{}]'.format(variants) signode += addnodes.desc_annotation(text, text) links.append(signode) holder.replace_self(links) # add subnode list for holder in doctree.traverse(sub_placeholder): obj = objects[holder.name] add_variant = False for pos, name, child, variants in obj.subs: if variants is not None: add_variant = True table = nodes.table() headers = [(1, 'Address'), (1, 'Name'), (10, 'Description')] if add_variant: headers.insert(1, (1, 'Variants')) tgroup = nodes.tgroup(cols=len(headers)) table += tgroup for colwidth, header in headers: tgroup += nodes.colspec(colwidth=colwidth) thead = nodes.thead() tgroup += thead headrow = nodes.row() for colwidth, header in headers: entry = nodes.entry() para = nodes.paragraph() entry += para para += nodes.Text(header, header) headrow += entry thead += headrow tbody = nodes.tbody() tgroup += tbody for pos, name, child, variants in obj.subs: row = nodes.row() row += wrap_text_entry(pos) if add_variant: row += wrap_text_entry('all' if variants is None else variants) row += wrap_text_entry(name) entry = nodes.entry() para = nodes.paragraph() entry += para para += make_refnode(app.builder, fromdocname, child.docname, child.iname + '-' + child.name, nodes.Text(child.brief, child.brief), obj.brief) row += entry tbody += row holder.replace_self([table])
def build_signature(self): """Returns the signature of the process.""" signature = addnodes.desc_signature(first=False, fullname=self.signature) signature += addnodes.desc_annotation(text=self.annotation) signature += addnodes.desc_addname(text=self.module_name + '.') signature += addnodes.desc_name(text=self.class_name) return signature
def parse(sig): m = py_sig_re.match(sig) if m is None: raise ValueError name_prefix, name, arglist, retann = m.groups() signode = addnodes.desc_signature(sig, '') _pseudo_parse_arglist(signode, arglist) return signode.astext()
def run(self): """Same as :meth:`sphinx.directives.ObjectDescription` but using :class:`FortranDocFieldTransformer`""" if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = '', self.name self.env = self.state.document.settings.env self.indexnode = addnodes.index(entries=[]) node = addnodes.desc() node.document = self.state.document node['domain'] = self.domain # 'desctype' is a backwards compatible attribute node['objtype'] = node['desctype'] = self.objtype node['noindex'] = noindex = ('noindex' in self.options) self.names = [] signatures = self.get_signatures() for i, sig in enumerate(signatures): # add a signature node for each signature in the current unit # and add a reference target for it signode = addnodes.desc_signature(sig, '') signode['first'] = False node.append(signode) try: # name can also be a tuple, e.g. (classname, objname); # this is strictly domain-specific (i.e. no assumptions may # be made in this base class) name = self.handle_signature(sig, signode) except ValueError: # signature parsing failed signode.clear() signode += addnodes.desc_name(sig, sig) continue # we don't want an index entry here if not isinstance(name[0], str): name = (str(name), name[1]) if not noindex and name not in self.names: # only add target and index entry if this is the first # description of the object with this name in this desc block self.names.append(name) self.add_target_and_index(name, sig, signode) modname = signode.get('module') typename = signode.get('type') contentnode = addnodes.desc_content() node.append(contentnode) if self.names: # needed for association of version{added,changed} directives self.env.temp_data['object'] = self.names[0] self.before_content() self.state.nested_parse(self.content, self.content_offset, contentnode) FortranDocFieldTransformer( self, modname=modname, typename=typename).transform_all(contentnode) self.env.temp_data['object'] = None self.after_content() return [self.indexnode, node]
def run(self) -> List[nodes.Node]: # noqa: D102 if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = '', self.name self.indexnode = addnodes.index(entries=[]) node = OptionDesc() node.document = self.state.document node["domain"] = self.domain # 'desctype' is a backwards compatible attribute node["objtype"] = node["desctype"] = self.objtype node["noindex"] = noindex = ("noindex" in self.options) if self.domain: node["classes"].append(self.domain) self.names: List[Any] = [] signatures = self.get_signatures() for i, sig in enumerate(signatures): # add a signature node for each signature in the current unit # and add a reference target for it signode = addnodes.desc_signature(sig, '') self.set_source_info(signode) node.append(signode) try: # name can also be a tuple, e.g. (classname, objname); # this is strictly domain-specific (i.e. no assumptions may # be made in this base class) name = self.handle_signature(sig, signode) except ValueError: # signature parsing failed signode.clear() signode += addnodes.desc_name(sig, sig) continue # we don't want an index entry here if name not in self.names: self.names.append(name) if not noindex: # only add target and index entry if this is the first # description of the object with this name in this desc block self.add_target_and_index(name, sig, signode) contentnode = addnodes.desc_content() node.append(contentnode) if self.names: # needed for association of version{added,changed} directives self.env.temp_data["object"] = self.names[0] self.before_content() self.state.nested_parse(self.content, self.content_offset, contentnode) self.transform_content(contentnode) self.env.app.emit("object-description-transform", self.domain, self.objtype, contentnode) DocFieldTransformer(self).transform_all(contentnode) self.env.temp_data["object"] = None self.after_content() return [self.indexnode, node]
def run(self): self.env = env = self.state.document.settings.env # normalize whitespace in fullname like XRefRole does fullname = ws_re.sub(' ', self.arguments[0].strip()) targetname = '%s-%s' % (self.ref_type, fullname) # keep the target; this may be used to generate a BBIndex later targets = env.domaindata['bb']['targets'].setdefault(self.ref_type, {}) targets[fullname] = env.docname, targetname # make up the descriptor: a target and potentially an index descriptor node = nodes.target('', '', ids=[targetname]) ret = [node] # add the target to the document self.state.document.note_explicit_target(node) # append the index node if necessary entries = [] for tpl in self.indextemplates: colon = tpl.find(':') if colon != -1: indextype = tpl[:colon].strip() indexentry = tpl[colon + 1:].strip() % (fullname, ) else: indextype = 'single' indexentry = tpl % (fullname, ) entries.append( (indextype, indexentry, targetname, targetname, None)) if entries: inode = addnodes.index(entries=entries) ret.insert(0, inode) # if the node has content, set up a signature and parse the content if self.has_content: descnode = addnodes.desc() descnode['domain'] = 'bb' descnode['objtype'] = self.ref_type descnode['noindex'] = True signode = addnodes.desc_signature(fullname, '') if self.name_annotation: annotation = "%s " % self.name_annotation signode += addnodes.desc_annotation(annotation, annotation) signode += addnodes.desc_name(fullname, fullname) descnode += signode contentnode = addnodes.desc_content() self.state.nested_parse(self.content, 0, contentnode) DocFieldTransformer(self).transform_all(contentnode) descnode += contentnode ret.append(descnode) return ret
def run(self): """Same as :meth:`sphinx.directives.ObjectDescription` but using :class:`FortranDocFieldTransformer`""" if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = '', self.name self.env = self.state.document.settings.env self.indexnode = addnodes.index(entries=[]) node = addnodes.desc() node.document = self.state.document node['domain'] = self.domain # 'desctype' is a backwards compatible attribute node['objtype'] = node['desctype'] = self.objtype node['noindex'] = noindex = ('noindex' in self.options) self.names = [] signatures = self.get_signatures() for i, sig in enumerate(signatures): # add a signature node for each signature in the current unit # and add a reference target for it signode = addnodes.desc_signature(sig, '') signode['first'] = False node.append(signode) try: # name can also be a tuple, e.g. (classname, objname); # this is strictly domain-specific (i.e. no assumptions may # be made in this base class) name = self.handle_signature(sig, signode) except ValueError: # signature parsing failed signode.clear() signode += addnodes.desc_name(sig, sig) continue # we don't want an index entry here if not isinstance(name[0], unicode): name = (unicode(name), name[1]) if not noindex and name not in self.names: # only add target and index entry if this is the first # description of the object with this name in this desc block self.names.append(name) self.add_target_and_index(name, sig, signode) modname = signode.get('module') typename = signode.get('type') contentnode = addnodes.desc_content() node.append(contentnode) if self.names: # needed for association of version{added,changed} directives self.env.temp_data['object'] = self.names[0] self.before_content() self.state.nested_parse(self.content, self.content_offset, contentnode) FortranDocFieldTransformer(self, modname=modname, typename=typename).transform_all(contentnode) self.env.temp_data['object'] = None self.after_content() return [self.indexnode, node]
def run(self): self.env = env = self.state.document.settings.env # normalize whitespace in fullname like XRefRole does fullname = ws_re.sub(' ', self.arguments[0].strip()) targetname = '%s-%s' % (self.ref_type, fullname) # keep the target; this may be used to generate a BBIndex later targets = env.domaindata['bb']['targets'].setdefault(self.ref_type, {}) targets[fullname] = env.docname, targetname # make up the descriptor: a target and potentially an index descriptor node = nodes.target('', '', ids=[targetname]) ret = [node] # add the target to the document self.state.document.note_explicit_target(node) # append the index node if necessary entries = [] for tpl in self.indextemplates: colon = tpl.find(':') if colon != -1: indextype = tpl[:colon].strip() indexentry = tpl[colon + 1:].strip() % (fullname,) else: indextype = 'single' indexentry = tpl % (fullname,) entries.append( (indextype, indexentry, targetname, targetname, None)) if entries: inode = addnodes.index(entries=entries) ret.insert(0, inode) # if the node has content, set up a signature and parse the content if self.has_content: descnode = addnodes.desc() descnode['domain'] = 'bb' descnode['objtype'] = self.ref_type descnode['noindex'] = True signode = addnodes.desc_signature(fullname, '') if self.name_annotation: annotation = "%s " % self.name_annotation signode += addnodes.desc_annotation(annotation, annotation) signode += addnodes.desc_name(fullname, fullname) descnode += signode contentnode = addnodes.desc_content() self.state.nested_parse(self.content, 0, contentnode) DocFieldTransformer(self).transform_all(contentnode) descnode += contentnode ret.append(descnode) return ret
def getArgsContent(Args): Container = desc('', desc_signature(text='Args'), objtype="Args") for name, Arg in Args.items(): Content = desc_content() Content.append(desc_name(text='%s: ' % name)) Content.append(compact_paragraph(text=getArgDesc(Arg))) Container.append(Content) return Container
def __init__(self, directive, refkey, key_elem, doc): label = nodes.strong('@provides', '@provides') sep = nodes.Text(': ', ': ') par = addnodes.desc_signature('<autodoc>', '', label, sep, key_elem) update_attrs(par, directive) self.name = 'py:ibkey' super(ibkey, self).__init__() self += par self += doc update_attrs(self, directive)
def run(self): if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = '', self.name self.indexnode = addnodes.index(entries=[]) node = addnodes.desc() node.document = self.state.document node['domain'] = self.domain node['classes'].append('csharp') node['objtype'] = node['desctype'] = self.objtype node['noindex'] = noindex = ('noindex' in self.options) self.names = [] signatures = self.get_signatures() for i, sig in enumerate(signatures): beforesignode = CSNodes.EmptyNode() node.append(beforesignode) signode = addnodes.desc_signature(sig, '') signode['first'] = False node.append(signode) self.before_sig(beforesignode) try: name = self.handle_signature(sig, signode) except ValueError: signode.clear() signode += addnodes.desc_name(sig, sig) continue if name not in self.names: self.names.append(name) if not noindex: self.add_target_and_index(name, sig, signode) aftersignode = CSNodes.EmptyNode() node.append(aftersignode) self.after_sig(aftersignode) contentnode = addnodes.desc_content() node.append(contentnode) self.before_content_node(contentnode) if self.names: self.env.temp_data['object'] = self.names[0] self.before_content() self.state.nested_parse(self.content, self.content_offset, contentnode) self.after_content_node(contentnode) DocFieldTransformer(self).transform_all(contentnode) self.env.temp_data['object'] = None self.after_content() return [self.indexnode, node]
def make_process_header(self, slug, typ, version, source_uri, description, inputs): """Generate a process definition header. :param str slug: process' slug :param str typ: process' type :param str version: process' version :param str source_uri: url to the process definition :param str description: process' description :param dict inputs: process' inputs """ node = addnodes.desc() signode = addnodes.desc_signature(slug, "") node.append(signode) node["objtype"] = node["desctype"] = typ signode += addnodes.desc_annotation(typ, typ, classes=["process-type"]) signode += addnodes.desc_addname("", "") signode += addnodes.desc_name(slug + " ", slug + " ") paramlist = addnodes.desc_parameterlist() for field_schema, _, _ in iterate_schema({}, inputs, ""): field_type = field_schema["type"] field_name = field_schema["name"] field_default = field_schema.get("default", None) field_default = "" if field_default is None else "={}".format( field_default) param = addnodes.desc_parameter("", "", noemph=True) param += nodes.emphasis(field_type, field_type, classes=["process-type"]) # separate by non-breaking space in the output param += nodes.strong(text="\xa0\xa0" + field_name) paramlist += param signode += paramlist signode += nodes.reference( "", nodes.Text("[Source: v{}]".format(version)), refuri=source_uri, classes=["viewcode-link"], ) desc = nodes.paragraph() desc += nodes.Text(description, description) return [node, desc]
def make_process_header(self, slug, typ, version, source_uri, description, inputs): """Generate a process definition header. :param str slug: process' slug :param str typ: process' type :param str version: process' version :param str source_uri: url to the process definition :param str description: process' description :param dict inputs: process' inputs """ node = addnodes.desc() signode = addnodes.desc_signature(slug, '') node.append(signode) node['objtype'] = node['desctype'] = typ signode += addnodes.desc_annotation(typ, typ, classes=['process-type']) signode += addnodes.desc_addname('', '') signode += addnodes.desc_name(slug + ' ', slug + ' ') paramlist = addnodes.desc_parameterlist() for field_schema, _, _ in iterate_schema({}, inputs, ''): field_type = field_schema['type'] field_name = field_schema['name'] field_default = field_schema.get('default', None) field_default = '' if field_default is None else '={}'.format( field_default) param = addnodes.desc_parameter('', '', noemph=True) param += nodes.emphasis(field_type, field_type, classes=['process-type']) # separate by non-breaking space in the output param += nodes.strong(text='\xa0\xa0' + field_name) paramlist += param signode += paramlist signode += nodes.reference('', nodes.Text('[Source: v{}]'.format(version)), refuri=source_uri, classes=['viewcode-link']) desc = nodes.paragraph() desc += nodes.Text(description, description) return [node, desc]
def generate(self, all_members=False): """ :rtype: List[nodes.Node] """ objname = self.item.name prefixed = (self.item['sourcemodule'].name + '.' + objname) if self.item['sourcemodule'] else None objtype = self.objtype assert objtype, '%s has no objtype' % type(self) root = addnodes.desc(domain='js', desctype=objtype, objtype=objtype) with addto( root, addnodes.desc_signature( module=self.modname or '', fullname=objname, )) as s: s['class'] = self.classname s['ids'] = [] if objname: s['ids'].append(objname) if prefixed: s['ids'].append(prefixed) if objtype: s += addnodes.desc_annotation( objtype, objtype, nodes.Text(' '), ) env = self.env if objname: env.domaindata['js']['objects'][objname] = (env.docname, objtype) if prefixed: env.domaindata['js']['objects'][prefixed] = (env.docname, objtype) # TODO: linkcode_resolve s += self.make_signature() with addto(root, addnodes.desc_content()) as c: # must be here otherwise nested_parse(self.content) will not have # the prefix set self.env.temp_data.setdefault('autojs:prefix', []).append(self.item.name) c += self.make_content(all_members=all_members) self.env.temp_data['autojs:prefix'].pop() return [root]
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]
def _make_index_section(self, obj, title, id): section = self._make_section(title) subobjs = obj.filter_by_id(id) kwargs = { 'refdomain': 'cpp', 'refexplicit': False, } if subobjs: lst = addnodes.desc() lst['objtype'] = 'function function-index' for obj in subobjs: desc = addnodes.desc_signature() span = nodes.inline() try: kwargs['reftype'] = 'func' if obj.rv is not None: span += addnodes.desc_type(text=str(obj.rv)) except AttributeError: kwargs['reftype'] = 'member' span += addnodes.desc_type(text=str(obj.typename)) desc += span desc += nodes.Text(u' ') name = unicode(obj.name) kwargs['reftarget'] = unicode(obj.get_name()) name = name.split('::')[-1] desc_name = addnodes.desc_name() refnode = addnodes.pending_xref('', **kwargs) innernode = nodes.literal(text=name) innernode.attributes['classes'].extend(['xref', 'cpp', 'cpp-func']) refnode += innernode desc_name += refnode desc += desc_name try: paramlist = addnodes.desc_parameterlist() for param_obj in obj.signature: param = addnodes.desc_parameter('', '', noemph=True) if param_obj.type is not None: param += nodes.Text(str(param_obj.type) + ' ') param += nodes.emphasis(text=str(param_obj.name)) paramlist += param desc += paramlist if obj.const: desc += nodes.Text(u' const') except AttributeError: pass lst += desc section += lst return section return None
def check(name, input, idDict, output=None): # first a simple check of the AST if output is None: output = input ast = parse(name, input) res = str(ast) if res != output: print("") print("Input: ", input) print("Result: ", res) print("Expected: ", output) raise DefinitionError("") rootSymbol = Symbol(None, None, None, None, None, None) symbol = rootSymbol.add_declaration(ast, docname="TestDoc") parentNode = addnodes.desc() signode = addnodes.desc_signature(input, '') parentNode += signode ast.describe_signature(signode, 'lastIsName', symbol, options={}) idExpected = [None] for i in range(1, _max_id + 1): if i in idDict: idExpected.append(idDict[i]) else: idExpected.append(idExpected[i - 1]) idActual = [None] for i in range(1, _max_id + 1): try: id = ast.get_id(version=i) assert id is not None idActual.append(id[len(_id_prefix[i]):]) except NoOldIdError: idActual.append(None) res = [True] for i in range(1, _max_id + 1): res.append(idExpected[i] == idActual[i]) if not all(res): print("input: %s" % input.rjust(20)) for i in range(1, _max_id + 1): if res[i]: continue print("Error in id version %d." % i) print("result: %s" % idActual[i]) print("expected: %s" % idExpected[i]) print(rootSymbol.dump(0)) raise DefinitionError("")
def run(self): env = self.state.document.settings.env package = env.temp_data.get('el:package') keymap_list = DATA.get(package, {}).get('keymap', []) keymap_name = self.arguments[0] for keymap in keymap_list: if keymap['name'] == keymap_name: break else: return [ self.state.reporter.warning( "Keymap {0} not found".format(keymap_name)) ] nodelist = [] mapdoc = keymap['doc'] if mapdoc: nd = nodes.paragraph() lines = string2lines(doc_to_rst(mapdoc)) if lines and lines[-1].startswith('(fn '): lines = lines[:-1] self.state.nested_parse(StringList(lines), 0, nd) nodelist.append(nd) exclude = self.options.get('exclude', []) replace = self.options.get('replace', []) for keybind in filter_by_exclude_regexp_list(keymap['data'], exclude, lambda x: x['func']): desc = addnodes.desc() desc['domain'] = 'el' desc['objtype'] = 'keybind' desc['noindex'] = False signode = addnodes.desc_signature() # signode += addnodes.desc_annotation("", 'keybind ') key = simple_sed(replace, keybind['key']) signode += addnodes.desc_name("", key) signode += addnodes.desc_addname("", " " + keybind['func']) desc += signode if keybind['doc']: nd = addnodes.desc_content() lines = string2lines(doc_to_rst(keybind['doc'])) if lines and lines[-1].startswith('(fn '): lines = lines[:-1] self.state.nested_parse(StringList(lines), 0, nd) desc += nodes.definition("", nd) nodelist.append(desc) return nodelist
def check(name, input, idDict, output=None): # first a simple check of the AST if output is None: output = input ast = parse(name, input) res = text_type(ast) if res != output: print("") print("Input: ", text_type(input)) print("Result: ", res) print("Expected: ", output) raise DefinitionError("") rootSymbol = Symbol(None, None, None, None, None, None) symbol = rootSymbol.add_declaration(ast, docname="TestDoc") parentNode = addnodes.desc() signode = addnodes.desc_signature(input, '') parentNode += signode ast.describe_signature(signode, 'lastIsName', symbol, options={}) idExpected = [None] for i in range(1, _max_id + 1): if i in idDict: idExpected.append(idDict[i]) else: idExpected.append(idExpected[i - 1]) idActual = [None] for i in range(1, _max_id + 1): try: id = ast.get_id(version=i) assert id is not None idActual.append(id[len(_id_prefix[i]):]) except NoOldIdError: idActual.append(None) res = [True] for i in range(1, _max_id + 1): res.append(idExpected[i] == idActual[i]) if not all(res): print("input: %s" % text_type(input).rjust(20)) for i in range(1, _max_id + 1): if res[i]: continue print("Error in id version %d." % i) print("result: %s" % str(idActual[i])) print("expected: %s" % str(idExpected[i])) print(rootSymbol.dump(0)) raise DefinitionError("")
def run(self): if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = '', self.name self.env = self.state.document.settings.env obj_name, = self.arguments for obj in self.gen_type.instances: if obj.name == obj_name: break else: raise ValueError('unknown instance {}'.format(obj_name)) node = addnodes.desc() node.document = self.state.document node['domain'] = self.domain node['objtype'] = node['desctype'] = self.objtype node['noindex'] = False node.name = obj.slug pobj = GenObjPlaceholder(self.env.docname, obj.brief) genobjs = self.env.domaindata['envy']['genobjs'] signode = addnodes.desc_signature('', '') signode['first'] = True node.append(signode) self.make_signature(obj, signode) signode['names'].append(obj.name) signode['ids'].append(obj.slug) self.state.document.note_explicit_target(signode) if obj.slug in genobjs: other = genobjs[obj.slug] self.state_machine.reporter.warning('duplicate object {}, other instance in {}'.format(obj.slug, self.env.doc2path(other.docname))) genobjs[obj.slug] = pobj contentnode = addnodes.desc_content() node.append(contentnode) vl = ViewList() doc = prepare_docstring(obj.doc or '') for line in doc: vl.append(line, obj_name) self.state.nested_parse(vl, 0, contentnode) return [ node ]
def make_nodes(var_name): var_obj = Variables.__dict__[var_name] if isinstance(var_obj, DefaultedProperty): desc_str = var_obj._func.__doc__ else: desc_str = var_obj.__doc__ desc_str = desc_str or "NO DESC" sig = addnodes.desc() sig.append(nodes.target("", "", ids=[var_name])) sig.append(addnodes.desc_signature(var_name, var_name)) desc = nodes.paragraph() for line in desc_str.split("\n"): desc += nodes.line(line, line) sig["objtype"] = sig["desctype"] = "var" return sig, desc
def document(self): eid = (self.tag, self.fqname) if eid in self.documented: return [build_paragraph(get_xref(self.tag, eid[1]))] else: self.documented.append(eid) rv = [self.target_node(self.tag, self.ns_name, self.name)] data = addnodes.desc(objtype=self.tag) targetid = get_target_id(self.tag, self.ns_name, self.name) header = addnodes.desc_signature('', '', first=True, ids=[targetid]) if self.include['doc']: header.extend([nodes.emphasis(self.tag, self.tag), text(" "), self.tname]) data.append(header) contents = nodes.definition() if self.include['doc']: contents.append(self.get_doc(self.entity)) contents.extend(getattr(self, "document_%s" % self.tag)()) data.append(contents) rv.append(data) if self.parent is None: # avoid adding duplicate dependencies added = [(self.type, self.name)] for typ, name, entity in self.dependencies: if not name: name = entity.get('name') if (typ, name) in added: continue ns_name, name = self.split_ns(name) ns_uri = self.namespaces[ns_name] if not entity: try: entity = self.entities[ns_uri][typ][name] except KeyError: self.app.warn("Dependency %s not found in schemas" % get_target_id(typ, ns_name, name)) continue doc = self.get_documentor(entity, name=name, ns_uri=ns_uri) rv.extend(doc.document()) added.append((typ, name)) return rv
def __init__(self, directive, env, docname, source_class, source_file, lineno, refkey, key_elem, doc): filename = env.doc2path(docname, base=None) linktext = "{0} ({1}:{2})".format(source_class, source_file, lineno) refnode = nodes.reference('', '', nodes.emphasis(linktext, linktext)) refnode['refdocname'] = docname refnode['refuri'] = "{0}#{1}".format( env.app.builder.get_target_uri(docname), refkey) origentry = nodes.inline('', '', nodes.Text(' (', ' ('), refnode, nodes.Text(')', ')')) entry_header = addnodes.desc_signature('', '', key_elem, origentry) entry_content = doc super(iblist_entry, self).__init__('', entry_header, entry_content) update_attrs(self, directive)
def run(self): env = self.state.document.settings.env package = env.temp_data.get('el:package') keymap_list = DATA.get(package, {}).get('keymap', []) keymap_name = self.arguments[0] for keymap in keymap_list: if keymap['name'] == keymap_name: break else: return [self.state.reporter.warning( "Keymap {0} not found".format(keymap_name))] nodelist = [] mapdoc = keymap['doc'] if mapdoc: nd = nodes.paragraph() lines = string2lines(doc_to_rst(mapdoc)) if lines and lines[-1].startswith('(fn '): lines = lines[:-1] self.state.nested_parse(StringList(lines), 0, nd) nodelist.append(nd) exclude = self.options.get('exclude', []) replace = self.options.get('replace', []) for keybind in filter_by_exclude_regexp_list( keymap['data'], exclude, lambda x: x['func']): desc = addnodes.desc() desc['domain'] = 'el' desc['objtype'] = 'keybind' desc['noindex'] = False signode = addnodes.desc_signature() # signode += addnodes.desc_annotation("", 'keybind ') key = simple_sed(replace, keybind['key']) signode += addnodes.desc_name("", key) signode += addnodes.desc_addname("", " " + keybind['func']) desc += signode if keybind['doc']: nd = addnodes.desc_content() lines = string2lines(doc_to_rst(keybind['doc'])) if lines and lines[-1].startswith('(fn '): lines = lines[:-1] self.state.nested_parse(StringList(lines), 0, nd) desc += nodes.definition("", nd) nodelist.append(desc) return nodelist
def make_process_header(self, slug, typ, version, source_uri, description, inputs): """Generate a process definition header. :param str slug: process' slug :param str typ: process' type :param str version: process' version :param str source_uri: url to the process definition :param str description: process' description :param dict inputs: process' inputs """ node = addnodes.desc() signode = addnodes.desc_signature(slug, '') node.append(signode) node['objtype'] = node['desctype'] = typ signode += addnodes.desc_annotation(typ, typ, classes=['process-type']) signode += addnodes.desc_addname('', '') signode += addnodes.desc_name(slug + ' ', slug + ' ') paramlist = addnodes.desc_parameterlist() for field_schema, _, _ in iterate_schema({}, inputs, ''): field_type = field_schema['type'] field_name = field_schema['name'] field_default = field_schema.get('default', None) field_default = '' if field_default is None else '={}'.format(field_default) param = addnodes.desc_parameter('', '', noemph=True) param += nodes.emphasis(field_type, field_type, classes=['process-type']) # separate by non-breaking space in the output param += nodes.strong(text=u'\xa0\xa0' + field_name) paramlist += param signode += paramlist signode += nodes.reference('', nodes.Text('[Source: v{}]'.format(version)), refuri=source_uri, classes=['viewcode-link']) desc = nodes.paragraph() desc += nodes.Text(description, description) return [node, desc]
def format_operation(self, operations): c = n.container() for op in operations: p = addnodes.desc(objtype='endpoint') p += addnodes.desc_signature('nickname', op['nickname']) p += addnodes.desc_addname('method', op['httpMethod']) p += addnodes.desc_content(text=op['summary']) if 'parameters' in op.keys(): p += addnodes.desc_annotation(text='Parameters: ') params = self.format_parameters(op['parameters']) p += params if op.get('responseClass'): response = self.format_response_class(op['responseClass']) p += response c += p return c
def format_operation(self, operations): c = n.container() for op in operations: p = addnodes.desc(objtype="endpoint") p += addnodes.desc_signature("nickname", op["nickname"]) p += addnodes.desc_addname("method", op["httpMethod"]) p += addnodes.desc_content(text=op["summary"]) if "parameters" in op.keys(): p += addnodes.desc_annotation(text="Parameters: ") params = self.format_parameters(op["parameters"]) p += params if op.get("responseClass"): response = self.format_response_class(op["responseClass"]) p += response c += p return c
def run(self): nodes = ObjectDescription.run(self) # Insert a dedicated signature for the key binding before all other # signatures, but only for commands. Nothing else has key bindings. binding = self.options.get('binding') if binding: binding = self.with_prefix_arg(binding) desc_node = nodes[-1] assert isinstance(desc_node, addnodes.desc) signode = addnodes.desc_signature(binding, '') # No clue what this property is for, but ObjectDescription sets it # for its signatures, so we should do as well for our signature. signode['first'] = False desc_node.insert(0, signode) signode += addnodes.desc_name(binding, binding) return nodes
def transform_module_section(section_node, title_node, env): fullmodname = section_node['names'][0] where = section_node.first_child_matching_class(section_prelude_end_class) content_children = list(ipop_child(section_node, where + 1)) if title_node is None: signature_children = [literal('', fullmodname)] else: signature_children = list(ipop_child(title_node)) signature_node = desc_signature('', '', *signature_children, classes=['title', 'module'], names=[fullmodname]) content_node = desc_content('', *content_children) desc_node = desc('', signature_node, content_node, desctype='module', objtype='module', classes=['definition']) section_node.append(desc_node) add_toc(desc_node, env, section_node)
def generate(self, all_members=False): """ :rtype: List[nodes.Node] """ objname = self.item.name prefixed = (self.item['sourcemodule'].name + '.' + objname) if self.item['sourcemodule'] else None objtype = self.objtype assert objtype, '%s has no objtype' % type(self) root = addnodes.desc(domain='js', desctype=objtype, objtype=objtype) with addto(root, addnodes.desc_signature( module=self.modname or '', fullname=objname, )) as s: s['class'] = self.classname s['ids'] = [] if objname: s['ids'].append(objname) if prefixed: s['ids'].append(prefixed) if objtype: s += addnodes.desc_annotation( objtype, objtype, nodes.Text(' '), ) env = self.env if objname: env.domaindata['js']['objects'][objname] = (env.docname, objtype) if prefixed: env.domaindata['js']['objects'][prefixed] = (env.docname, objtype) # TODO: linkcode_resolve s += self.make_signature() with addto(root, addnodes.desc_content()) as c: # must be here otherwise nested_parse(self.content) will not have # the prefix set self.env.temp_data.setdefault('autojs:prefix', []).append(self.item.name) c += self.make_content(all_members=all_members) self.env.temp_data['autojs:prefix'].pop() return [root]
def _make_enum_documentation(self, obj): def get_entry(node): para = addnodes.compact_paragraph() para += node entry = nodes.entry() entry += para return entry desc = addnodes.desc_signature() desc['ids'].append(obj.get_id()) first = False desc += nodes.emphasis(text=u'enum') desc += nodes.Text(u' ') desc += addnodes.desc_name(text=obj.get_name()) desc.attributes['first'] = True content = addnodes.desc_content() if obj.brief(): para = nodes.paragraph() para += nodes.emphasis(text='Brief: ') para += nodes.Text(' '.join(obj.brief())) content += para table, body = nodes.table(), nodes.tbody() tgroup = nodes.tgroup(cols=3) thead = nodes.thead() for it in [20, 10, 70]: tgroup += nodes.colspec(colwidth=it) tgroup += thead tgroup += body table += tgroup head_row = nodes.row() for it in ['Name', 'Value', 'Brief']: head_row += get_entry(nodes.Text(it)) thead += head_row for val in sorted(obj.values): row = nodes.row() row += get_entry(nodes.literal(text=val.name)) tmp = [val.value if val.value is not None else '', ' '.join(val.brief())] for it in tmp: row += get_entry(nodes.Text(it)) body += row content += table return (desc, content)
def run(self): name = self.arguments[0] dname = addnodes.desc_name(name, name) dcontent = addnodes.desc_content() self.state.nested_parse(self.content, self.content_offset, dcontent) dcontent, fields = _split_content(dcontent) dcontent.append(_group_fields(fields)) signature = addnodes.desc_signature(name, "") signature.append(dname) signature.append(dcontent) if ":" in self.name: domain, objtype = self.name.split(":", 1) else: domain, objtype = "", self.name description = addnodes.desc() description["domain"] = domain description["objtype"] = objtype description.append(signature) if name not in self.state.document.ids: signature["names"].append(name) signature["ids"].append(name) signature["first"] = True self.state.document.note_explicit_target(signature) env = self.state.document.settings.env objects = env.domaindata["tosca"]["objects"] if name in objects: msg = "duplicate TOSCA type {}, other in {}" self.state_machine.reporter.warning(msg.format( name, env.doc2path(objects[name].doc) ), line=self.lineno) objects[name] = ToscaObject(env.docname, objtype) indexnode = addnodes.index(entries=[("single", name, name, "", None)]) return [indexnode, description]
def _make_typedef_documentation(self, obj): kwargs = { 'refdomain': 'cpp', 'refexplicit': False, } content = addnodes.desc_signature() content['ids'].append(obj.get_id()) content.attributes['first'] = True span = nodes.inline() span += nodes.emphasis(text = u'typedef ') if obj._ref is None or obj._ref is '' or self._get_obj_by_refid(obj._ref) is None: span += addnodes.desc_type(text = obj._type) else: ref = self._get_obj_by_refid(obj._ref) kwargs['reftarget'] = unicode(ref.get_name()) kwargs['reftype'] = qiapidoc.data.types.get_obj_type(ref) refname = addnodes.desc_name() refnode = addnodes.pending_xref('', **kwargs) innernode = nodes.literal(text = unicode(ref.name)) innernode.attributes['classes'].extend(['xref', 'cpp', 'cpp-func']) refnode += innernode refname += refnode span += refname content += span if obj._args is '': content += nodes.Text(u' ') span = nodes.inline() span += addnodes.desc_type(text = obj.rawname) content += span if obj._args is not '': content += nodes.inline() + addnodes.desc_type(text = obj._args) span = nodes.inline() span += nodes.Text(obj._desc) return content, span
def run(self): if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = '', self.name self.env = self.state.document.settings.env self.indexnode = addnodes.index(entries=[]) node = addnodes.desc() node.document = self.state.document node['domain'] = self.domain node['objtype'] = node['desctype'] = self.objtype node['noindex'] = False try: signature = self.arguments[0] if self.objtype == 'schema': signode = addnodes.desc_signature(signature) signode['first'] = False node += signode except: signature = None headernode = addnodes.desc_name() headernode += nodes.inline('', _(self.objtype) + ' ') if signature is not None: headernode += nodes.emphasis('', signature) if _is_compositional(self.options['type']): if signature is not None: headernode += nodes.inline('', ' -- ') _describe_type(self.options['type'], headernode, contains=self.options['contains']) node.append(headernode) contentnode = addnodes.desc_content() node.append(contentnode) self.state.nested_parse(self.content, self.content_offset, contentnode) type = self.options['type'] if type in __transformers__: __transformers__[type](self).transform_all(contentnode) return [addnodes.index(entries=[]), node]
def handle_ada_decl(self, decl): # type: (lal.BasicDecl) -> Tuple[List[nodes.Node], N.desc_content] # Get the documentation content doc, annotations = self.get_documentation(decl) # Create sphinx nodes self.indexnode = N.index(entries=[]) node = N.desc() node.document = self.state.document signode = N.desc_signature('', '') signode['first'] = False node.append(signode) # Do decl-type specific stuff in specialized methods handlers = [ (lal.BasicSubpDecl, lal.ExprFunction, self.handle_subprogram_decl), (lal.BaseTypeDecl, self.handle_type_decl), (lal.ObjectDecl, self.handle_object_decl), (lal.PackageRenamingDecl, self.handle_package_renaming_decl), (lal.GenericPackageInstantiation, self.handle_package_inst), (lal.GenericSubpInstantiation, self.handle_subp_inst), (lal.ExceptionDecl, self.handle_exception_decl), ] for h in handlers: types, handler = h[:-1], h[-1] if isinstance(decl, types): handler(decl, node, signode, annotations) break else: self.handle_decl_generic(decl, node, signode, annotations) # Create the documentation's content content_node = N.desc_content() node.append(content_node) rst = ViewList() for i, l in enumerate(doc, 1): rst.append(l, 'no_file.rst', i) nested_parse_with_titles(self.state, rst, content_node) return [self.indexnode, node], content_node
def check(name, input, idv1output=None, idv2output=None, output=None): # first a simple check of the AST if output is None: output = input ast = parse(name, input) res = text_type(ast) if res != output: print("") print("Input: ", text_type(input)) print("Result: ", res) print("Expected: ", output) raise DefinitionError("") rootSymbol = Symbol(None, None, None, None, None, None) symbol = rootSymbol.add_declaration(ast, docname="TestDoc") parentNode = addnodes.desc() signode = addnodes.desc_signature(input, '') parentNode += signode ast.describe_signature(signode, 'lastIsName', symbol, options={}) if idv2output: idv2output = "_CPPv2" + idv2output try: idv1 = ast.get_id_v1() assert idv1 is not None except NoOldIdError: idv1 = None try: idv2 = ast.get_id_v2() assert idv2 is not None except NoOldIdError: idv2 = None if idv1 != idv1output or idv2 != idv2output: print("input: %s" % text_type(input).rjust(20)) print(" %s %s" % ("Id v1".rjust(20), "Id v2".rjust(20))) print("result: %s %s" % (str(idv1).rjust(20), str(idv2).rjust(20))) print("expected: %s %s" % (str(idv1output).rjust(20), str(idv2output).rjust(20))) print(rootSymbol.dump(0)) raise DefinitionError("") ids.append(ast.get_id_v2())
def parse_section(self, node): matched = re.search("^(.*?)\s*\((.*)\)\s*$", node[0].astext()) if not matched: return objname = matched.group(1).strip() typename = matched.group(2).strip() desc = sphinxnodes.desc(domain="js", desctype="data", objtype="data") sig = sphinxnodes.desc_signature(object="", fullname=objname, first=False) sig["names"].append(objname) sig["ids"].append(objname.replace("$", "_S_")) sig += sphinxnodes.desc_name(text="%s (%s)" % (objname, typename)) content = sphinxnodes.desc_content() node.pop(0) transpose_subnodes(node, content) node.replace_self(desc) desc.append(sig) desc.append(content)
def check(name, input, idv1output=None, idv2output=None, output=None): # first a simple check of the AST if output is None: output = input ast = parse(name, input) res = text_type(ast) if res != output: print("") print("Input: ", text_type(input)) print("Result: ", res) print("Expected: ", output) raise DefinitionError("") rootSymbol = Symbol(None, None, None, None, None, None) symbol = rootSymbol.add_declaration(ast, docname="Test") parentNode = addnodes.desc() signode = addnodes.desc_signature(input, '') parentNode += signode ast.describe_signature(signode, 'lastIsName', symbol) if idv2output: idv2output = "_CPPv2" + idv2output try: idv1 = ast.get_id_v1() assert idv1 is not None except NoOldIdError: idv1 = None try: idv2 = ast.get_id_v2() assert idv2 is not None except NoOldIdError: idv2 = None if idv1 != idv1output or idv2 != idv2output: print("input: %s" % text_type(input).rjust(20)) print(" %s %s" % ("Id v1".rjust(20), "Id v2".rjust(20))) print("result: %s %s" % (str(idv1).rjust(20), str(idv2).rjust(20))) print("expected: %s %s" % (str(idv1output).rjust(20), str(idv2output).rjust(20))) print(rootSymbol.dump(0)) raise DefinitionError("") ids.append(ast.get_id_v2())
def _get_links(self) -> Generator[addnodes.desc, None, None]: """Get the linkable inputs/outputs as sphinx nodes.""" linkable = summary.get_linkable_declarations( self.obj.declarations.values()) for attr in ("input", "output", "memory"): decls = getattr(linkable, attr, []) if decls: block_desc = addnodes.desc(classes=["linkable"]) name = { "input": "Inputs", "output": "Outputs", "memory": "Memory", }[attr] sig = addnodes.desc_signature( classes=[f"linkable_{attr}"], ids=[f"{self.obj.name}._linkable_{attr}_"], ) sig += addnodes.desc_name(text=f"Linkable {name}") block_desc += sig block_desc += _to_link_table(self.obj.name, decls) yield block_desc
def transform_module_section(section_node, title_node, env): fullmodname = section_node["names"][0] where = section_node.first_child_matching_class(section_prelude_end_class) content_children = list(ipop_child(section_node, where + 1)) if title_node is None: signature_children = [literal("", fullmodname)] else: signature_children = list(ipop_child(title_node)) signature_node = desc_signature( "", "", *signature_children, classes=["title", "module"], names=[fullmodname] ) content_node = desc_content("", *content_children) desc_node = desc( "", signature_node, content_node, desctype="module", objtype="module", classes=["definition"], ) section_node.append(desc_node) add_toc(desc_node, env, section_node)
def run(self): #no good # node = nodes.paragraph('', 'Hi there!', # ids=['foo'], # names = ['foobar'] # ) #works # node = nodes.section(names=['foobar']) # self.state.document.note_explicit_target(node) # node.append(nodes.paragraph('', "foo foo")) #no good # node = nodes.admonition(names=['foobar']) # self.state.document.note_explicit_target(node) # node.append(nodes.paragraph('', "foo foo")) # node = nodes.paragraph('', 'foo foo', names=['foobar']) # self.state.document.note_explicit_target(node) #This doesn't properly render desc = addnodes.desc('', addnodes.desc_signature( '', addnodes.desc_name('', 'namename'), addnodes.desc_parameterlist( '', addnodes.desc_parameter('', 'def')), names=['namename'], fullname="namename", ids=['namename'], module=None, first=False), desctype="function", domain="py", objtype='objtype') #no link (because didn't properly render?) self.state.document.note_explicit_target(desc) return [desc]
def _build_option(self, parser, action, custom_content): """ Build single program option :param parser: pre-configured ArgumentParser instance :param action: source Action :param custom_content: custom content for options :return: node forming program option """ def get_id(progname, name): id = 'cmdoption-{}'.format(progname) if not name.startswith('-'): id += '-arg-' id += name return id fmt = parser._get_formatter() result = nodes.container() signature = addnodes.desc_signature(ids=[], allnames=[], first=False) self.state.document.note_explicit_target(signature) description = self._build_option_description(fmt, action, custom_content) content = addnodes.desc_content('', description) result.append(addnodes.desc('', signature, content, objtype='option')) progname = self._get_program_name(parser) synopses = [] for option in self._get_option_group(fmt, action): signature['ids'].append(get_id(progname, option['name'])) signature['allnames'].append(option['name']) signature.append(addnodes.desc_name(text=option['name'])) if 'args' in option: signature.append(addnodes.desc_addname(text=option['args'])) signature.append(addnodes.desc_addname(text=', ')) synopses.append(option['synopsis']) signature.pop() index = self._build_option_index(progname, signature['ids'], signature['allnames'], synopses) result.append(index) return result
def run(self): # type: () -> List[nodes.Node] """ Main directive entry function, called by docutils upon encountering the directive. This directive is meant to be quite easily subclassable, so it delegates to several additional methods. What it does: * find out if called as a domain-specific directive, set self.domain * create a `desc` node to fit all description inside * parse standard options, currently `noindex` * create an index node if needed as self.indexnode * parse all given signatures (as returned by self.get_signatures()) using self.handle_signature(), which should either return a name or raise ValueError * add index entries using self.add_target_and_index() * parse the content and handle doc fields in it """ if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = '', self.name self.indexnode = addnodes.index(entries=[]) node = addnodes.desc() node.document = self.state.document node['domain'] = self.domain # 'desctype' is a backwards compatible attribute node['objtype'] = node['desctype'] = self.objtype node['noindex'] = noindex = ('noindex' in self.options) self.names = [] # type: List[unicode] signatures = self.get_signatures() for i, sig in enumerate(signatures): # add a signature node for each signature in the current unit # and add a reference target for it signode = addnodes.desc_signature(sig, '') signode['first'] = False node.append(signode) try: # name can also be a tuple, e.g. (classname, objname); # this is strictly domain-specific (i.e. no assumptions may # be made in this base class) name = self.handle_signature(sig, signode) except ValueError: # signature parsing failed signode.clear() signode += addnodes.desc_name(sig, sig) continue # we don't want an index entry here if name not in self.names: self.names.append(name) if not noindex: # only add target and index entry if this is the first # description of the object with this name in this desc block self.add_target_and_index(name, sig, signode) contentnode = addnodes.desc_content() node.append(contentnode) if self.names: # needed for association of version{added,changed} directives self.env.temp_data['object'] = self.names[0] self.before_content() self.state.nested_parse(self.content, self.content_offset, contentnode) DocFieldTransformer(self).transform_all(contentnode) self.env.temp_data['object'] = None self.after_content() return [self.indexnode, node]