我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用docutils.nodes.reference()。
def doctree_resolved(app, doctree, docname): secnums = app.builder.env.toc_secnumbers for node in doctree.traverse(nodes.reference): if 'refdocname' in node: refdocname = node['refdocname'] if refdocname in secnums: secnum = secnums[refdocname] toclist = app.builder.env.tocs[refdocname] for child in node.traverse(): if isinstance(child, nodes.Text): text = child.astext() anchorname = None for refnode in toclist.traverse(nodes.reference): if refnode.astext() == text: anchorname = refnode['anchorname'] if anchorname is None: continue linktext = '.'.join(map(str, secnum[anchorname])) child.parent.replace(child, nodes.Text(linktext))
def expand_show_urls(self): show_urls = self.document.settings.env.config.latex_show_urls if show_urls is False or show_urls == 'no': return for node in self.document.traverse(nodes.reference): uri = node.get('refuri', '') if uri.startswith(URI_SCHEMES): if uri.startswith('mailto:'): uri = uri[7:] if node.astext() != uri: index = node.parent.index(node) if show_urls == 'footnote': if list(traverse_parent(node, nodes.topic)): # should not expand references in topics pass else: footnote_nodes = self.create_footnote(uri) for i, fn in enumerate(footnote_nodes): node.parent.insert(index + i + 1, fn) self.expanded = True else: # all other true values (b/w compat) textnode = nodes.Text(" (%s)" % uri) node.parent.insert(index + 1, textnode)
def visit_footnote_reference(self, node): num = node.astext().strip() try: footnode, used = self.footnotestack[-1][num] except (KeyError, IndexError): raise nodes.SkipNode # if a footnote has been inserted once, it shouldn't be repeated # by the next reference if used: if self.table or self.in_term or self.in_title: self.body.append('\\protect\\footnotemark[%s]' % num) else: self.body.append('\\footnotemark[%s]' % num) elif self.footnote_restricted: self.footnotestack[-1][num][1] = True self.body.append('\\protect\\footnotemark[%s]' % num) self.pending_footnotes.append(footnode) else: self.footnotestack[-1][num][1] = True footnode.walkabout(self) raise nodes.SkipChildren
def stylesheet_call(self, path): """Return code to reference or embed stylesheet file `path`""" if self.settings.embed_stylesheet: try: content = io.FileInput(source_path=path, encoding='utf-8').read() self.settings.record_dependencies.add(path) except IOError, err: msg = u"Cannot embed stylesheet '%s': %s." % ( path, SafeString(err.strerror)) self.document.reporter.error(msg) return '<--- %s --->\n' % msg return self.embedded_stylesheet % content # else link to style file: if self.settings.stylesheet_path: # adapt path relative to output (cf. config.html#stylesheet-path) path = utils.relative_path(self.settings._destination, path) return self.stylesheet_link % self.encode(path)
def visit_reference(self, node): atts = {'class': 'reference'} if 'refuri' in node: atts['href'] = node['refuri'] if ( self.settings.cloak_email_addresses and atts['href'].startswith('mailto:')): atts['href'] = self.cloak_mailto(atts['href']) self.in_mailto = True atts['class'] += ' external' else: assert 'refid' in node, \ 'References must have "refuri" or "refid" attribute.' atts['href'] = '#' + node['refid'] atts['class'] += ' internal' if not isinstance(node.parent, nodes.TextElement): assert len(node) == 1 and isinstance(node[0], nodes.image) atts['class'] += ' image-reference' self.body.append(self.starttag(node, 'a', '', **atts))
def substitution_reference(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.substitution_ref, nodes.substitution_reference) if len(inlines) == 1: subref_node = inlines[0] if isinstance(subref_node, nodes.substitution_reference): subref_text = subref_node.astext() self.document.note_substitution_ref(subref_node, subref_text) if endstring[-1:] == '_': reference_node = nodes.reference( '|%s%s' % (subref_text, endstring), '') if endstring[-2:] == '__': reference_node['anonymous'] = 1 else: reference_node['refname'] = normalize_name(subref_text) self.document.note_refname(reference_node) reference_node += subref_node inlines = [reference_node] return before, inlines, remaining, sysmessages
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 pep_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: pepnum = int(text) if pepnum < 0 or pepnum > 9999: raise ValueError except ValueError: msg = inliner.reporter.error( 'PEP number must be a number from 0 to 9999; "%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.pep_reference; so this is correct: ref = (inliner.document.settings.pep_base_url + inliner.document.settings.pep_file_url_template % pepnum) set_classes(options) return [nodes.reference(rawtext, 'PEP ' + utils.unescape(text), refuri=ref, **options)], []
def rfc_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: rfcnum = int(text) if rfcnum <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'RFC number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.rfc_reference, so this is correct: ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum set_classes(options) node = nodes.reference(rawtext, 'RFC ' + utils.unescape(text), refuri=ref, **options) return [node], []
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 _strong_node(self, refuri, text_nodes): cp = docutils_nodes.inline(classes=['link-container']) n1 = docutils_nodes.strong() n1.extend(text_nodes) cp.append(n1) paramlink = docutils_nodes.reference( '', '', docutils_nodes.Text(u"¶", u"¶"), refid="", # paramlink is our own CSS class, headerlink # is theirs. Trying to get everything we can for existing # symbols... classes=['paramlink', 'headerlink'] ) cp.append(paramlink) return cp
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ app = inliner.document.settings.env.app #app.info('user link %r' % text) ref = 'https://www.github.com/' + text node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], []
def make_link_node(rawtext, app, link_text, slug, options): """ Creates a link to a trac ticket. :param rawtext: text being replaced with link node :param app: sphinx application context :param link_text: text for the link :param slug: ID of the thing to link to :param options: options dictionary passed to role func """ options = options or {} base_url = app.config.twisted_url if not base_url: raise ValueError( "'twisted_url' isn't set in our config") ref = base_url.rstrip('/') + '/' + slug set_classes(options) return reference(rawtext, link_text, refuri=ref, **options)
def render_response(code, message): code = int(code.strip()) if code == 226: url = 'http://www.ietf.org/rfc/rfc3229.txt' elif code == 418: url = 'http://www.ietf.org/rfc/rfc2324.txt' elif code == 429: url = 'http://tools.ietf.org/html/rfc6585#section-4' elif code == 449: url = 'http://msdn.microsoft.com/en-us/library/dd891478(v=prot.10).aspx' elif code in WEBDAV_STATUS_CODES: url = 'http://tools.ietf.org/html/rfc4918#section-11.%d' % ( WEBDAV_STATUS_CODES.index(code) + 1) elif code in HTTP_STATUS_CODES: url = 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html' \ '#sec10.' + ('%d.%d' % (code // 100, 1 + code % 100)) else: url = '' status = HTTP_STATUS_CODES.get(code, '') text = '%d %s' % (code, status) # return addnodes.download_reference(text, text, refuri=url, reftarget='_blank') return nodes.reference(text, text, refuri=url) # return addnodes.desc_annotation(text, text)
def build_reference_node(self, fromdocname, builder, docname, labelid, sectname, rolename, **options): nodeclass = options.pop('nodeclass', nodes.reference) newnode = nodeclass('', '', internal=True, **options) innernode = nodes.inline(sectname, sectname) if innernode.get('classes') is not None: innernode['classes'].append('std') innernode['classes'].append('std-' + rolename) 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
def get_objects(self): # handle the special 'doc' reference here for doc in self.env.all_docs: yield (doc, clean_astext(self.env.titles[doc]), 'doc', doc, '', -1) for (prog, option), info in iteritems(self.data['progoptions']): yield (option, option, 'option', info[0], info[1], 1) for (type, name), info in iteritems(self.data['objects']): yield (name, name, type, info[0], info[1], self.object_types[type].attrs['searchprio']) for name, info in iteritems(self.data['labels']): yield (name, info[2], 'label', info[0], info[1], -1) # add anonymous-only labels as well non_anon_labels = set(self.data['labels']) for name, info in iteritems(self.data['anonlabels']): if name not in non_anon_labels: yield (name, name, 'label', info[0], info[1], -1)
def build_reference_node(self, fromdocname, builder, docname, labelid, sectname, **options): nodeclass = options.pop('nodeclass', nodes.reference) newnode = nodeclass('', '', internal=True, **options) innernode = nodes.inline(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
def make_link_role(base_url, prefix): def role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) has_explicit_title, title, part = split_explicit_title(text) try: full_url = base_url % part except (TypeError, ValueError): inliner.reporter.warning( 'unable to expand %s extlink with base URL %r, please make ' 'sure the base contains \'%%s\' exactly once' % (typ, base_url), line=lineno) full_url = base_url + part if not has_explicit_title: if prefix is None: title = full_url else: title = prefix + part pnode = nodes.reference(title, title, internal=False, refuri=full_url) return [pnode], [] return role
def write_doc(self, docname, doctree): self.info() n = 0 for node in doctree.traverse(nodes.reference): if 'refuri' not in node: continue uri = node['refuri'] lineno = None while lineno is None: node = node.parent if node is None: break lineno = node.line self.wqueue.put((uri, docname, lineno), False) n += 1 done = 0 while done < n: self.process_result(self.rqueue.get()) done += 1 if self.broken: self.app.statuscode = 1
def get_refnodes(self, doctree, result): """Collect section titles, their depth in the toc and the refuri.""" # XXX: is there a better way than checking the attribute # toctree-l[1-8] on the parent node? if isinstance(doctree, nodes.reference) and 'refuri' in doctree: refuri = doctree['refuri'] if refuri.startswith('http://') or refuri.startswith('https://') \ or refuri.startswith('irc:') or refuri.startswith('mailto:'): return result classes = doctree.parent.attributes['classes'] for level in range(8, 0, -1): # or range(1, 8)? if (_toctree_template % level) in classes: result.append({ 'level': level, 'refuri': self.esc(refuri), 'text': ssp(self.esc(doctree.astext())) }) break else: for elem in doctree.children: result = self.get_refnodes(elem, result) return result
def post_process_images(self, doctree): """Pick the best candidate for an image and link down-scaled images to their high res version. """ Builder.post_process_images(self, doctree) if self.config.html_scaled_image_link: for node in doctree.traverse(nodes.image): scale_keys = ('scale', 'width', 'height') if not any((key in node) for key in scale_keys) or \ isinstance(node.parent, nodes.reference): # docutils does unfortunately not preserve the # ``target`` attribute on images, so we need to check # the parent node here. continue uri = node['uri'] reference = nodes.reference('', '', internal=True) if uri in self.images: reference['refuri'] = posixpath.join(self.imgpath, self.images[uri]) else: reference['refuri'] = uri node.replace_self(reference) reference.append(node)
def expand_show_urls(self): show_urls = self.document.settings.env.config.latex_show_urls if show_urls is False or show_urls == 'no': return for node in self.document.traverse(nodes.reference): uri = node.get('refuri', '') if uri.startswith(URI_SCHEMES): if uri.startswith('mailto:'): uri = uri[7:] if node.astext() != uri: index = node.parent.index(node) if show_urls == 'footnote': footnote_nodes = self.create_footnote(uri) for i, fn in enumerate(footnote_nodes): node.parent.insert(index + i + 1, fn) self.expanded = True else: # all other true values (b/w compat) textnode = nodes.Text(" (%s)" % uri) node.parent.insert(index + 1, textnode)
def get_changelog(self, repo, commit): item = nodes.list_item() item.append(self._make_message_node(commit.message, commit.hexsha)) item.append(nodes.inline(text=six.text_type(' by '))) item.append(nodes.emphasis(text=six.text_type(commit.author.name))) item.append(nodes.inline(text=six.text_type(' at '))) commit_date = datetime.fromtimestamp(commit.authored_date) item.append(nodes.emphasis(text=six.text_type(commit_date))) if OPTION_WITH_REF_URL in self.options: ref_url = repo.get_commit_url(commit.hexsha) ref = nodes.reference('', commit.hexsha, refuri=ref_url) item.append(nodes.paragraph('', '', ref)) if OPTION_INCLUDE_DIFF in self.options: diff = repo.get_diff(commit.hexsha) item.append(self._make_diff_node(diff, commit.hexsha)) return item
def get_changelog(self, repo, commit): item = nodes.list_item() item.append(self._make_message_node(commit['summary'], commit['sha'])) item.append(nodes.inline(text=six.text_type(' by '))) item.append(nodes.emphasis(text=six.text_type(commit['user']))) item.append(nodes.inline(text=six.text_type(' at '))) item.append(nodes.emphasis(text=six.text_type(commit['date']))) if OPTION_WITH_REF_URL in self.options: ref_url = repo.get_commit_url(commit['sha']) ref = nodes.reference('', commit['sha'], refuri=ref_url) item.append(nodes.paragraph('', '', ref)) if OPTION_INCLUDE_DIFF in self.options: diff = repo.get_diff(commit['revision']) item.append(self._make_diff_node(diff, commit['sha'])) return item
def stylesheet_call(self, path): """Return code to reference or embed stylesheet file `path`""" if self.settings.embed_stylesheet: try: content = io.FileInput(source_path=path, encoding='utf-8').read() self.settings.record_dependencies.add(path) except IOError as err: msg = "Cannot embed stylesheet '%s': %s." % ( path, SafeString(err.strerror)) self.document.reporter.error(msg) return '<--- %s --->\n' % msg return self.embedded_stylesheet % content # else link to style file: if self.settings.stylesheet_path: # adapt path relative to output (cf. config.html#stylesheet-path) path = utils.relative_path(self.settings._destination, path) return self.stylesheet_link % self.encode(path)
def html_page_context(app, pagename, templatename, context, doctree): # Build a list of the local table of contents entries to appear in # the sidebar try: toc = app.builder.env.get_toc_for(pagename, app.builder) except KeyError: # Pages like genindex may not show up in the list of pages # with table of contents, and that breaks # environment.get_toc_for, which throws an KeyError. pass else: toc_menu = [] for node in toc.traverse(nodes.reference): # Skip the node at the top that points back to this page if node['refuri'] == '#': continue toc_menu.append({ 'title': str(node.children[0]), 'href': node['anchorname'], }) context['toc_menu'] = toc_menu # Only show comments when we are rendering a page inside a module # directory, to prevent people from commenting on the main page, # about page, index, etc. # context['show_comments'] = '/' in pagename # Use the last modified date from git instead of applying a single # value to the entire site. context['last_updated'] = _get_last_updated(app, pagename)
def create_footnote(self, uri): label = nodes.label('', '#') para = nodes.paragraph() para.append(nodes.reference('', nodes.Text(uri), refuri=uri, nolinkurl=True)) footnote = nodes.footnote(uri, label, para, auto=1) footnote['names'].append('#') self.document.note_autofootnote(footnote) label = nodes.Text('#') footnote_ref = nodes.footnote_reference('[#]_', label, auto=1, refid=footnote['ids'][0]) self.document.note_autofootnote_ref(footnote_ref) footnote.add_backref(footnote_ref['ids'][0]) return [footnote, footnote_ref]
def make_issue_reference(issue, content_node): reference = nodes.reference() reference['refuri'] = issue.url if issue.title: reference['reftitle'] = issue.title reference.append(content_node) return reference