Python docutils.nodes.reference() Examples
The following are 30
code examples of docutils.nodes.reference().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
docutils.nodes
, or try the search function
.
Example #1
Source File: sphinxext.py From bioconda-utils with MIT License | 6 votes |
def setup(app): """Set up sphinx extension""" app.add_domain(CondaDomain) app.add_directive('autorecipes', AutoRecipesDirective) app.add_directive('lint-check', LintDescriptionDirective) app.connect('builder-inited', generate_recipes) app.connect('env-updated', LintDescriptionDirective.finalize) app.connect('missing-reference', resolve_required_by_xrefs) app.connect('html-page-context', add_ribbon) app.add_config_value('bioconda_repo_url', '', 'env') app.add_config_value('bioconda_recipes_path', 'recipes', 'env') app.add_config_value('bioconda_config_file', 'config.yml', 'env') app.add_config_value('bioconda_other_channels', {}, 'env') return { 'version': "0.0.1", 'parallel_read_safe': True, 'parallel_write_safe': True }
Example #2
Source File: speciescatalog.py From stdpopsim with GNU General Public License v3.0 | 6 votes |
def make_field_list(self, data): field_list = nodes.field_list() for name, text, citations in data: field = nodes.field() field_name = nodes.field_name(text=name) field_body = nodes.field_body() para = nodes.paragraph(text=text) if citations is not None and len(citations) > 0: para += nodes.Text(" (") for i, citation in enumerate(citations): text = f"{citation.author}, {citation.year}" para += nodes.reference( internal=False, refuri=citation.doi, text=text) if i != len(citations)-1: para += nodes.Text("; ") para += nodes.Text(")") field_body += para field += field_name field += field_body field_list += field return field_list
Example #3
Source File: roles.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def make_link_node(rawtext, app, url_type, 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 url_type: base for our url :param link_text: text for the link :param slug: ID of the thing to link to :param options: options dictionary passed to role func """ base_url = getattr(app.config, url_type, None) if not base_url: raise ValueError("'%s' isn't set in our config" % url_type) ref = base_url.format(slug = slug) set_classes(options) return reference(rawtext, link_text, refuri = ref, **options)
Example #4
Source File: speciescatalog.py From stdpopsim with GNU General Public License v3.0 | 6 votes |
def models_table(self, species): table = nodes.table() tgroup = nodes.tgroup(cols=2) for _ in range(2): colspec = nodes.colspec(colwidth=1) tgroup.append(colspec) table += tgroup thead = nodes.thead() tgroup += thead row = nodes.row() entry = nodes.entry() entry += nodes.paragraph(text="ID") row += entry entry = nodes.entry() entry += nodes.paragraph(text="Description") row += entry thead.append(row) rows = [] for model in species.demographic_models: row = nodes.row() rows.append(row) mid = self.get_demographic_model_id(species, model) entry = nodes.entry() para = nodes.paragraph() entry += para para += nodes.reference(internal=True, refid=mid, text=model.id) row += entry entry = nodes.entry() entry += nodes.paragraph(text=model.description) row += entry tbody = nodes.tbody() tbody.extend(rows) tgroup += tbody return table
Example #5
Source File: peps.py From faces with GNU General Public License v2.0 | 6 votes |
def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', ' at ') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
Example #6
Source File: roles.py From faces with GNU General Public License v2.0 | 6 votes |
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)], []
Example #7
Source File: roles.py From faces with GNU General Public License v2.0 | 6 votes |
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], []
Example #8
Source File: states.py From faces with GNU General Public License v2.0 | 6 votes |
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
Example #9
Source File: states.py From faces with GNU General Public License v2.0 | 6 votes |
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)
Example #10
Source File: _html_base.py From faces with GNU General Public License v2.0 | 6 votes |
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)
Example #11
Source File: peps.py From faces with GNU General Public License v2.0 | 6 votes |
def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', ' at ') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
Example #12
Source File: roles.py From faces with GNU General Public License v2.0 | 6 votes |
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)], []
Example #13
Source File: roles.py From faces with GNU General Public License v2.0 | 6 votes |
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], []
Example #14
Source File: states.py From faces with GNU General Public License v2.0 | 6 votes |
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
Example #15
Source File: states.py From faces with GNU General Public License v2.0 | 6 votes |
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)
Example #16
Source File: _html_base.py From faces with GNU General Public License v2.0 | 6 votes |
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))
Example #17
Source File: custom_roles.py From Telethon with MIT License | 6 votes |
def tl_role(name, rawtext, text, lineno, inliner, options=None, content=None): """ Link to the TL reference. 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. """ if options is None: options = {} # TODO Report error on type not found? # Usage: # msg = inliner.reporter.error(..., line=lineno) # return [inliner.problematic(rawtext, rawtext, msg)], [msg] app = inliner.document.settings.env.app node = make_link_node(rawtext, app, text, options) return [node], []
Example #18
Source File: sphinxext.py From bioconda-utils with MIT License | 6 votes |
def resolve_required_by_xrefs(app, env, node, contnode): """Now that all recipes and packages have been parsed, we are called here for each ``pending_xref`` node that sphinx has not been able to resolve. We handle specifically the ``requiredby`` reftype created by the `RequiredByField` fieldtype allowed in ``conda:package::`` directives, where we replace the ``pending_ref`` node with a bullet list of reference nodes pointing to the package pages that "depended" on the package. """ if node['reftype'] == 'requiredby' and node['refdomain'] == 'conda': target = node['reftarget'] docname = node['refdoc'] backrefs = env.domains['conda'].data['backrefs'].get(target, set()) listnode = nodes.bullet_list() for back_docname, back_target in backrefs: par = nodes.paragraph() name_node = addnodes.literal_strong(back_target, back_target, classes=['xref', 'backref']) refnode = make_refnode(app.builder, docname, back_docname, back_target, name_node) refnode.set_class('conda-package') par += refnode listnode += nodes.list_item('', par) return listnode
Example #19
Source File: sphinxext.py From bioconda-utils with MIT License | 6 votes |
def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder, role, target, node, contnode): """Resolve the ``pending_xref`` **node** with the given **role** and **target**.""" for objtype in self.objtypes_for_role(role) or []: if (objtype, target) in self.data['objects']: node = make_refnode( builder, fromdocname, self.data['objects'][objtype, target][0], self.data['objects'][objtype, target][1], contnode, target + ' ' + objtype) node.set_class('conda-package') return node if objtype == "package": for channel, urlformat in env.app.config.bioconda_other_channels.items(): if RepoData().get_package_data(channels=channel, name=target): uri = urlformat.format(target) node = nodes.reference('', '', internal=False, refuri=uri, classes=[channel]) node += contnode return node return None # triggers missing-reference
Example #20
Source File: states.py From faces with GNU General Public License v2.0 | 5 votes |
def rfc_reference(self, match, lineno): text = match.group(0) if text.startswith('RFC'): rfcnum = int(match.group('rfcnum')) ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum else: raise MarkupMismatch unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)]
Example #21
Source File: peps.py From faces with GNU General Public License v2.0 | 5 votes |
def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass
Example #22
Source File: references.py From faces with GNU General Public License v2.0 | 5 votes |
def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference')
Example #23
Source File: references.py From faces with GNU General Public License v2.0 | 5 votes |
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')
Example #24
Source File: references.py From faces with GNU General Public License v2.0 | 5 votes |
def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if target['refuri'] not in notes: notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if ref['refuri'] not in notes: notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist)
Example #25
Source File: speciescatalog.py From stdpopsim with GNU General Public License v3.0 | 5 votes |
def get_target(self, tid): """ Returns a target node for the specified ID. This took a lot of digging through the Docutils and Sphinx sources to figure out: it appears that including the 'names' argument to the target node and calling note_explicit_target are essential to allow us to cross reference these targets from the rest of the documentation. """ target = nodes.target('', '', ids=[tid], names=[tid]) self.state.document.note_explicit_target(target) return target
Example #26
Source File: sphinxext.py From typhon with MIT License | 5 votes |
def arts_docserver_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Create a link to ARTS docserver. Parameters: name (str): The role name used in the document. rawtext (str): The entire markup snippet, with role. text (str): The text marked with the role. lineno (str): The line number where rawtext appears in the input. inliner (str): The inliner instance that called us. options (dict): Directive options for customization. content (list): The directive content for customization. Returns: list, list: Nodes to insert into the document, System messages. """ if content is None: content = [] if options is None: options = {} url = 'http://radiativetransfer.org/docserver-trunk/all/{}'.format(text) node = nodes.reference(rawtext, text, refuri=url, **options) return [node], []
Example #27
Source File: states.py From faces with GNU General Public License v2.0 | 5 votes |
def reference(self, match, lineno, anonymous=False): referencename = match.group('refname') refname = normalize_name(referencename) referencenode = nodes.reference( referencename + match.group('refend'), referencename, name=whitespace_normalize_name(referencename)) if anonymous: referencenode['anonymous'] = 1 else: referencenode['refname'] = refname self.document.note_refname(referencenode) string = match.string matchstart = match.start('whole') matchend = match.end('whole') return (string[:matchstart], [referencenode], string[matchend:], [])
Example #28
Source File: states.py From faces with GNU General Public License v2.0 | 5 votes |
def anonymous_reference(self, match, lineno): return self.reference(match, lineno, anonymous=1)
Example #29
Source File: states.py From faces with GNU General Public License v2.0 | 5 votes |
def pep_reference(self, match, lineno): text = match.group(0) if text.startswith('pep-'): pepnum = int(match.group('pepnum1')) elif text.startswith('PEP'): pepnum = int(match.group('pepnum2')) else: raise MarkupMismatch ref = (self.document.settings.pep_base_url + self.document.settings.pep_file_url_template % pepnum) unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)]
Example #30
Source File: parts.py From faces with GNU General Public License v2.0 | 5 votes |
def build_contents(self, node, level=0): level += 1 sections = [sect for sect in node if isinstance(sect, nodes.section)] entries = [] autonum = 0 depth = self.startnode.details.get('depth', sys.maxint) for section in sections: title = section[0] auto = title.get('auto') # May be set by SectNum. entrytext = self.copy_and_filter(title) reference = nodes.reference('', '', refid=section['ids'][0], *entrytext) ref_id = self.document.set_id(reference) entry = nodes.paragraph('', '', reference) item = nodes.list_item('', entry) if ( self.backlinks in ('entry', 'top') and title.next_node(nodes.reference) is None): if self.backlinks == 'entry': title['refid'] = ref_id elif self.backlinks == 'top': title['refid'] = self.toc_id if level < depth: subsects = self.build_contents(section, level) item += subsects entries.append(item) if entries: contents = nodes.bullet_list('', *entries) if auto: contents['classes'].append('auto-toc') return contents else: return []