我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用docutils.nodes.target()。
def run(self): env = self.state.document.settings.env modname = self.arguments[0].strip() noindex = 'noindex' in self.options env.temp_data['php:namespace'] = modname env.temp_data['php:class'] = None env.domaindata['php']['namespaces'][modname] = ( env.docname, self.options.get('synopsis', ''), 'deprecated' in self.options) targetnode = nodes.target('', '', ids=['namespace-' + modname], ismod=True) self.state.document.note_explicit_target(targetnode) ret = [targetnode] # the synopsis isn't printed; in fact, it is only used in the # modindex currently if not noindex: indextext = _('%s (namespace)') % modname inode = addnodes.index(entries=[('single', indextext, 'namespace-' + modname, modname, None)]) ret.append(inode) return ret
def process_link(self, env, refnode, has_explicit_title, title, target): if not has_explicit_title: if title.startswith("::"): title = title[2:] target = target.lstrip('~') # only has a meaning for the title # if the first character is a tilde, don't display the module/class # parts of the contents if title[0:1] == '~': m = re.search(r"(?:\\|[:]{2})(.*)\Z", title) if m: title = m.group(1) if not title.startswith("$"): refnode['php:namespace'] = env.temp_data.get('php:namespace') refnode['php:class'] = env.temp_data.get('php:class') return title, target
def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) if target['ids']: naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in utils.uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1
def hyperlink_target(self, match): pattern = self.explicit.patterns.target lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented( match.end(), until_blank=True, strip_indent=False) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] escaped = block[0] blockindex = 0 while True: targetmatch = pattern.match(escaped) if targetmatch: break blockindex += 1 try: escaped += block[blockindex] except IndexError: raise MarkupError('malformed hyperlink target.') del block[:blockindex] block[0] = (block[0] + ' ')[targetmatch.end()-len(escaped)-1:].strip() target = self.make_target(block, blocktext, lineno, targetmatch.group('name')) return [target], blank_finish
def parse_target(self, block, block_text, lineno): """ Determine the type of reference of a target. :Return: A 2-tuple, one of: - 'refname' and the indirect reference name - 'refuri' and the URI - 'malformed' and a system_message node """ if block and block[-1].strip()[-1:] == '_': # possible indirect target reference = ' '.join([line.strip() for line in block]) refname = self.is_reference(reference) if refname: return 'refname', refname reference = ''.join([''.join(line.split()) for line in block]) return 'refuri', unescape(reference)
def add_target(self, targetname, refuri, target, lineno): target.line = lineno if targetname: name = normalize_name(unescape(targetname)) target['names'].append(name) if refuri: uri = self.inliner.adjust_uri(refuri) if uri: target['refuri'] = uri else: raise ApplicationError('problem with URI: %r' % refuri) self.document.note_explicit_target(target, self.parent) else: # anonymous target if refuri: target['refuri'] = refuri target['anonymous'] = 1 self.document.note_anonymous_target(target)
def parse_target(self, block, block_text, lineno): """ Determine the type of reference of a target. :Return: A 2-tuple, one of: - 'refname' and the indirect reference name - 'refuri' and the URI - 'malformed' and a system_message node """ if block and block[-1].strip()[-1:] == '_': # possible indirect target reference = ' '.join([line.strip() for line in block]) refname = self.is_reference(reference) if refname: return 'refname', refname ref_parts = split_escaped_whitespace(' '.join(block)) reference = ' '.join(''.join(unescape(part).split()) for part in ref_parts) return 'refuri', reference
def run(self): 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.name, fullname) node = nodes.target('', '', ids=[targetname]) self.state.document.note_explicit_target(node) ret = [node] if self.indextemplate: indexentry = self.indextemplate % (fullname,) indextype = 'single' colon = indexentry.find(':') if colon != -1: indextype = indexentry[:colon].strip() indexentry = indexentry[colon+1:].strip() inode = addnodes.index(entries=[(indextype, indexentry, targetname, '', None)]) ret.insert(0, inode) name = self.name if ':' in self.name: _, name = self.name.split(':', 1) env.domaindata['std']['objects'][name, fullname] = \ env.docname, targetname return ret
def add_target_and_index(self, name_cls, sig, signode): modname = self.options.get( 'module', self.env.ref_context.get('py:module')) fullname = (modname and modname + '.' or '') + name_cls[0] # note target if fullname not in self.state.document.ids: signode['names'].append(fullname) signode['ids'].append(fullname) signode['first'] = (not self.names) self.state.document.note_explicit_target(signode) objects = self.env.domaindata['py']['objects'] if fullname in objects: self.state_machine.reporter.warning( 'duplicate object description of %s, ' % fullname + 'other instance in ' + self.env.doc2path(objects[fullname][0]) + ', use :noindex: for one of them', line=self.lineno) objects[fullname] = (self.env.docname, self.objtype) indextext = self.get_index_text(modname, name_cls) if indextext: self.indexnode['entries'].append(('single', indextext, fullname, ''))
def run(self): env = self.state.document.settings.env modname = self.arguments[0].strip() noindex = 'noindex' in self.options env.ref_context['py:module'] = modname ret = [] if not noindex: env.domaindata['py']['modules'][modname] = \ (env.docname, self.options.get('synopsis', ''), self.options.get('platform', ''), 'deprecated' in self.options) # make a duplicate entry in 'objects' to facilitate searching for # the module in PythonDomain.find_obj() env.domaindata['py']['objects'][modname] = (env.docname, 'module') targetnode = nodes.target('', '', ids=['module-' + modname], ismod=True) self.state.document.note_explicit_target(targetnode) # the platform and synopsis aren't printed; in fact, they are only # used in the modindex currently ret.append(targetnode) indextext = _('%s (module)') % modname inode = addnodes.index(entries=[('single', indextext, 'module-' + modname, '')]) ret.append(inode) return ret
def process_link(self, env, refnode, has_explicit_title, title, target): refnode['py:module'] = env.ref_context.get('py:module') refnode['py:class'] = env.ref_context.get('py:class') if not has_explicit_title: title = title.lstrip('.') # only has a meaning for the target target = target.lstrip('~') # only has a meaning for the title # if the first character is a tilde, don't display the module/class # parts of the contents if title[0:1] == '~': title = title[1:] dot = title.rfind('.') if dot != -1: title = title[dot+1:] # if the first character is a dot, search more specific namespaces first # else search builtins first if target[0:1] == '.': target = target[1:] refnode['refspecific'] = True return title, target
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): modname = node.get('py:module') clsname = node.get('py:class') results = [] # always search in "refspecific" mode with the :any: role matches = self.find_obj(env, modname, clsname, target, None, 1) for name, obj in matches: if obj[1] == 'module': results.append(('py:mod', self._make_module_refnode(builder, fromdocname, name, contnode))) else: results.append(('py:' + self.role_for_objtype(obj[1]), make_refnode(builder, fromdocname, obj[0], name, contnode, name))) return results
def run(self): 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.name, fullname) node = nodes.target('', '', ids=[targetname]) self.state.document.note_explicit_target(node) ret = [node] if self.indextemplate: indexentry = self.indextemplate % (fullname,) indextype = 'single' colon = indexentry.find(':') if colon != -1: indextype = indexentry[:colon].strip() indexentry = indexentry[colon+1:].strip() inode = addnodes.index(entries=[(indextype, indexentry, targetname, '')]) ret.insert(0, inode) name = self.name if ':' in self.name: _, name = self.name.split(':', 1) env.domaindata['std']['objects'][name, fullname] = \ env.docname, targetname return ret
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): results = [] ltarget = target.lower() # :ref: lowercases its target automatically for role in ('ref', 'option'): # do not try "keyword" res = self.resolve_xref(env, fromdocname, builder, role, ltarget if role == 'ref' else target, node, contnode) if res: results.append(('std:' + role, res)) # all others for objtype in self.object_types: key = (objtype, target) if objtype == 'term': key = (objtype, ltarget) if key in self.data['objects']: docname, labelid = self.data['objects'][key] results.append(('std:' + self.role_for_objtype(objtype), make_refnode(builder, fromdocname, docname, labelid, contnode))) return results
def process_todos(app, doctree): # collect all todos in the environment # this is not done in the directive itself because it some transformations # must have already been run, e.g. substitutions env = app.builder.env if not hasattr(env, 'todo_all_todos'): env.todo_all_todos = [] for node in doctree.traverse(todo_node): try: targetnode = node.parent[node.parent.index(node) - 1] if not isinstance(targetnode, nodes.target): raise IndexError except IndexError: targetnode = None newnode = node.deepcopy() del newnode['ids'] env.todo_all_todos.append({ 'docname': env.docname, 'source': node.source or env.doc2path(env.docname), 'lineno': node.line, 'todo': newnode, 'target': targetnode, })
def run(self): latex = '\n'.join(self.content) if self.arguments and self.arguments[0]: latex = self.arguments[0] + '\n\n' + latex node = displaymath() node['latex'] = latex node['label'] = self.options.get('name', None) if node['label'] is None: node['label'] = self.options.get('label', None) node['nowrap'] = 'nowrap' in self.options node['docname'] = self.state.document.settings.env.docname ret = [node] set_source_info(self, node) if hasattr(self, 'src'): node.source = self.src if node['label']: tnode = nodes.target('', '', ids=['equation-' + node['label']]) self.state.document.note_explicit_target(tnode) ret.insert(0, tnode) return ret
def run(self): self.assert_has_content() title = self.arguments[0] content = '\n'.join(self.content) math_node = self.make_math_node(self.prepare_latex(content)) tid = nodes.make_id(title) target = nodes.target('', '', ids=['inference-' + tid]) self.state.document.note_explicit_target(target) term, desc = nodes.term('', title), nodes.description('', math_node) dli = nodes.definition_list_item('', term, desc) dl = nodes.definition_list(content, target, dli) set_source_info(self, dl) return [dl]
def GrammarProductionRole(typ, rawtext, text, lineno, inliner, options={}, content=[]): """An inline role to declare grammar productions that are not in fact included in a `productionlist` directive. Useful to informally introduce a production, as part of running text """ #pylint: disable=dangerous-default-value, unused-argument env = inliner.document.settings.env targetid = 'grammar-token-{}'.format(text) target = nodes.target('', '', ids=[targetid]) inliner.document.note_explicit_target(target) code = nodes.literal(rawtext, text, role=typ.lower()) node = nodes.inline(rawtext, '', target, code, classes=['inline-grammar-production']) set_role_source_info(inliner, lineno, node) env.domaindata['std']['objects']['token', text] = env.docname, targetid return [node], []
def _calc_spans(self, rows, nrcols): # calculate colspan for row in rows: target = None for c in range(nrcols): if row[c] is not None: # try to extend colspan on this cell target = row[c] else: if target is not None: # extend colspan target[1] += 1 # convert arrays to tuples # arrays are needed to patch up colspan and rowspan # the table builder requires each cell to be a tuple, not an array for row in rows: for c in range(nrcols): if row[c] is not None: row[c] = tuple(row[c])
def run(self): env = self.state.document.settings.env targetid = "tag-%d" % env.new_serialno('tag') targetnode = nodes.target('', '', ids=[targetid]) # The tags fetched from the custom directive are one piece of text # sitting in self.content[0] taggs = self.content[0].split(", ") links = [] for tagg in taggs: # Create Sphinx doc refs of format :ref:`Tagname<Tagname>` link = ":ref:`" + tagg + "<" + tagg + ">`" links.append(link) # Put links back in a single comma-separated string together linkjoin = ", ".join(links) # Replace content[0] with hyperlinks to display in admonition self.content[0] = linkjoin ad = Admonition(self.name, [_('Tags')], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) return [targetnode] + ad.run()
def run(self): lineno = self.state_machine.abs_line_number() target = nodes.target() section = nodes.section(classes=["detail-control"]) # env = self.state.document.settings.env # env.app.info("Parent %s" % self.state.parent.attributes) node = rest_method() # TODO(sdague): this is a super simplistic parser, should be # more robust. method, sep, url = self.content[0].partition(' ') node['method'] = method node['url'] = url node['target'] = self.state.parent.attributes['ids'][0] # We need to build a temporary target that we can replace # later in the processing to get the TOC to resolve correctly. temp_target = "%s-selector" % node['target'] target = nodes.target(ids=[temp_target]) self.state.add_target(temp_target, '', target, lineno) section += node return [target, section]
def rest_method_html(self, node): tmpl = """ <div class="row operation-grp"> <div class="col-md-1 operation"> <a name="%(target)s" class="operation-anchor" href="#%(target)s"> <span class="glyphicon glyphicon-link"></span></a> <span class="label label-success">%(method)s</span> </div> <div class="col-md-5">%(url)s</div> <div class="col-md-5">%(desc)s</div> <div class="col-md-1"> <button class="btn btn-info btn-sm btn-detail" data-target="#%(target)s-detail" data-toggle="collapse" id="%(target)s-detail-btn" >detail</button> </div> </div>""" self.body.append(tmpl % node) raise nodes.SkipNode
def run(self): env = self.state.document.settings.env targetid = 'question-%d' % env.new_serialno('question') targetnode = nodes.target('', '', ids=[targetid]) self.options['class'] = ['question'] ad = make_admonition(question, self.name, ['Question'], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) return [targetnode] + ad
def run(self): env = self.state.document.settings.env targetid = 'qiime1users-%d' % env.new_serialno('qiime1users') targetnode = nodes.target('', '', ids=[targetid]) self.options['class'] = ['qiime1'] ad = make_admonition(qiime1users, self.name, ['QIIME 1 Users'], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) return [targetnode] + ad
def add_target_and_index(self, name_cls, sig, signode): if self.objtype == 'global': modname = '' else: modname = self.options.get( 'namespace', self.env.temp_data.get('php:namespace')) separator = separators[self.objtype] if self._is_class_member(): if signode['class']: prefix = modname and modname + NS or '' else: prefix = modname and modname + NS or '' else: prefix = modname and modname + NS or '' fullname = prefix + name_cls[0] # note target if fullname not in self.state.document.ids: signode['names'].append(fullname) signode['ids'].append(fullname) signode['first'] = (not self.names) self.state.document.note_explicit_target(signode) objects = self.env.domaindata['php']['objects'] if fullname in objects: self.env.warn( self.env.docname, 'duplicate object description of %s, ' % fullname + 'other instance in ' + self.env.doc2path(objects[fullname][0]), self.lineno) objects[fullname] = (self.env.docname, self.objtype) indextext = self.get_index_text(modname, name_cls) if indextext: self.indexnode['entries'].append(('single', indextext, fullname, fullname, None))
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): for typ in self.roles: resolve = self.resolve_xref(env, fromdocname, builder, typ, target, node, contnode) if resolve: return [('php:%s' % typ, resolve)] return []
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode): if (typ == 'ns' or typ == 'obj' and target in self.data['namespaces']): docname, synopsis, deprecated = self.data['namespaces'].get( target, ('', '', '') ) if not docname: return None else: title = '%s%s' % (synopsis, (deprecated and ' (deprecated)' or '')) return make_refnode( builder, fromdocname, docname, 'namespace-' + target, contnode, title) else: modname = node.get('php:namespace') clsname = node.get('php:class') searchorder = node.hasattr('refspecific') and 1 or 0 name, obj = self.find_obj(env, modname, clsname, target, typ, searchorder) if not obj: return None else: return make_refnode(builder, fromdocname, obj[0], name, contnode, name)
def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while True: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break
def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target)
def nonexistent_indirect_target(self, target): if target['refname'] in self.document.nameids: self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist')
def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref)