我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用docutils.nodes.literal()。
def default_departure(self, node): """Default node depart method.""" self.level -= 1 if not self.in_simple: self.output.append(self.indent*self.level) self.output.append(node.endtag()) if isinstance(node, (nodes.FixedTextElement, nodes.literal)): self.fixed_text -= 1 if isinstance(node, self.simple_nodes): self.in_simple -= 1 if not self.in_simple: self.output.append(self.newline) # specific visit and depart methods # ---------------------------------
def definition_list_item(self, termline): indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() itemnode = nodes.definition_list_item( '\n'.join(termline + list(indented))) lineno = self.state_machine.abs_line_number() - 1 (itemnode.source, itemnode.line) = self.state_machine.get_source_and_line(lineno) termlist, messages = self.term(termline, lineno) itemnode += termlist definition = nodes.definition('', *messages) itemnode += definition if termline[0][-2:] == '::': definition += self.reporter.info( 'Blank line missing before literal block (after the "::")? ' 'Interpreted as a definition list item.', line=lineno+1) self.nested_parse(indented, input_offset=line_offset, node=definition) return itemnode, blank_finish
def coq_code_role(role, rawtext, text, lineno, inliner, options={}, content=[]): #pylint: disable=dangerous-default-value """And inline role for Coq source code""" options['language'] = 'Coq' return code_role(role, rawtext, text, lineno, inliner, options, content) ## Too heavy: ## Forked from code_role to use our custom tokenizer; this doesn't work for ## snippets though: for example CoqDoc swallows the parentheses around this: ## “(a: A) (b: B)” # set_classes(options) # classes = ['code', 'coq'] # code = utils.unescape(text, 1) # node = nodes.literal(rawtext, '', *highlight_using_coqdoc(code), classes=classes) # return [node], [] # TODO pass different languages?
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 write_dl(self, rows, col_max=30, col_spacing=2): """Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column. """ rows = list(rows) dl = nodes.bullet_list() self._node.append(dl) for (option, help_text) in rows: item = nodes.list_item() dl.append(item) p = nodes.paragraph() p.append(nodes.literal('', option)) p.append(nodes.Text(': ')) p.append(nodes.Text(help_text)) item.append(p)
def handle_signature(self, sig, signode): path = self.get_display_path() signode['is_multiline'] = True line = addnodes.desc_signature_line() line['add_permalink'] = True for x in path: line += addnodes.desc_addname(x + '.', x + '.') line += addnodes.desc_name(sig, sig) if 'required' in self.options: line += addnodes.desc_annotation(' (required)', ' (required)') signode += line if 'default' in self.options: line = addnodes.desc_signature_line() line += addnodes.desc_type('Default: ', 'Default: ') line += nodes.literal(self.options['default'], self.options['default']) signode += line return sig
def handle_signature(self, sig, signode): if 'hidden' in self.options: return sig path = self.get_display_path() signode['is_multiline'] = True line = addnodes.desc_signature_line() line['add_permalink'] = True for x in path: line += addnodes.desc_addname(x + '.', x + '.') line += addnodes.desc_name(sig, sig) if 'required' in self.options: line += addnodes.desc_annotation(' (required)', ' (required)') signode += line if 'default' in self.options: line = addnodes.desc_signature_line() line += addnodes.desc_type('Default: ', 'Default: ') line += nodes.literal(self.options['default'], self.options['default']) signode += line return sig
def code_role(role, rawtext, text, lineno, inliner, options={}, content=[]): r'''code_role override or create if older docutils used. This only creates a literal node without parsing the code. This will be done later in sphinx. This override is not really needed, but it might give some speed ''' set_classes(options) language = options.get('language', '') classes = ['code'] if 'classes' in options: classes.extend(options['classes']) if language and language not in classes: classes.append(language) node = nodes.literal(rawtext, text, classes=classes, language=language) #import rpdb2 ; rpdb2.start_embedded_debugger('foo') return [node], []
def apply(self): config = self.document.settings.env.config github_project = config.github_project issue_pattern = config.github_issue_pattern if isinstance(issue_pattern, str_t): issue_pattern = re.compile(issue_pattern) for node in self.document.traverse(nodes.Text): parent = node.parent if isinstance(parent, (nodes.literal, nodes.FixedTextElement)): continue text = text_t(node) new_nodes = [] last_issue_ref_end = 0 for match in issue_pattern.finditer(text): head = text[last_issue_ref_end:match.start()] if head: new_nodes.append(nodes.Text(head)) last_issue_ref_end = match.end() issuetext = match.group(0) issue_id = match.group(1) refnode = pending_xref() refnode['reftarget'] = issue_id refnode['reftype'] = 'issue' refnode['github_project'] = github_project reftitle = issuetext refnode.append(nodes.inline( issuetext, reftitle, classes=['xref', 'issue'])) new_nodes.append(refnode) if not new_nodes: continue tail = text[last_issue_ref_end:] if tail: new_nodes.append(nodes.Text(tail)) parent.replace(node, new_nodes)
def get_tokens(self, txtnodes): # A generator that yields ``(texttype, nodetext)`` tuples for a list # of "Text" nodes (interface to ``smartquotes.educate_tokens()``). texttype = {True: 'literal', # "literal" text is not changed: False: 'plain'} for txtnode in txtnodes: nodetype = texttype[isinstance(txtnode.parent, (nodes.literal, nodes.math, nodes.image, nodes.raw, nodes.problematic))] yield (nodetype, txtnode.astext())
def default_visit(self, node): """Default node visit method.""" if not self.in_simple: self.output.append(self.indent*self.level) self.output.append(node.starttag(xml.sax.saxutils.quoteattr)) self.level += 1 # @@ make nodes.literal an instance of FixedTextElement? if isinstance(node, (nodes.FixedTextElement, nodes.literal)): self.fixed_text += 1 if isinstance(node, self.simple_nodes): self.in_simple += 1 if not self.in_simple: self.output.append(self.newline)
def literal(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.literal, nodes.literal, restore_backslashes=True) return before, inlines, remaining, sysmessages
def text(self, match, context, next_state): if context: self.messages.append( self.reporter.error('Inconsistent literal block quoting.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError
def code_role(role, rawtext, text, lineno, inliner, options={}, content=[]): set_classes(options) language = options.get('language', '') classes = ['code'] if 'classes' in options: classes.extend(options['classes']) if language and language not in classes: classes.append(language) try: tokens = Lexer(utils.unescape(text, 1), language, inliner.document.settings.syntax_highlight) except LexerError, error: msg = inliner.reporter.warning(error) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] node = nodes.literal(rawtext, '', classes=classes) # analyse content and add nodes for every token for classes, value in tokens: # print (classes, value) if classes: node += nodes.inline(value, value, classes=classes) else: # insert as Text to decrease the verbosity of the output node += nodes.Text(value, value) return [node], []
def get_tokens(self, txtnodes): # A generator that yields ``(texttype, nodetext)`` tuples for a list # of "Text" nodes (interface to ``smartquotes.educate_tokens()``). texttype = {True: 'literal', # "literal" text is not changed: False: 'plain'} for txtnode in txtnodes: nodetype = texttype[isinstance(txtnode.parent, self.literal_nodes)] yield (nodetype, txtnode.astext())
def build_list(binaries): if not binaries: return [nodes.Text("")] l = nodes.bullet_list() for binary in binaries: li = nodes.list_item() li.append(nodes.literal(text=binary)) l.append(li) return [l]
def run(self): camisole.languages.load_builtins() all_langs = camisole.languages.all().values() self.options['widths'] = 'auto' title, messages = self.make_title() headers = [[nodes.paragraph(text="Language")], [nodes.paragraph(text="Class")], [nodes.paragraph(text="Binaries")]] for f in self.package_finders: headers.append([nodes.paragraph(text=f"{f.name} packages")]) table_body = [] for cls in sorted(all_langs, key=lambda e: e.name.lower()): binaries = set(b.cmd_name for b in cls.required_binaries()) if not binaries: continue body = [[nodes.paragraph(text=cls.name)], [nodes.literal(text=cls.__name__)], build_list(binaries)] for f in self.package_finders: body.append(build_list(f.for_binaries(binaries))) table_body.append(body) table = [headers] + table_body self.check_table_dimensions(table, 1, 0) table_node = self.build_table_from_list(table, 'auto', 1, 0) if title: table_node.insert(0, title) return [table_node] + messages
def token_xrefs(text): retnodes = [] pos = 0 for m in token_re.finditer(text): if m.start() > pos: txt = text[pos:m.start()] retnodes.append(nodes.Text(txt, txt)) refnode = addnodes.pending_xref( m.group(1), reftype='token', refdomain='std', reftarget=m.group(1)) refnode += nodes.literal(m.group(1), m.group(1), classes=['xref']) retnodes.append(refnode) pos = m.end() if pos < len(text): retnodes.append(nodes.Text(text[pos:], text[pos:])) return retnodes
def visit_pending_xref(self, node): text = node.astext() self.parent.append(nodes.literal(text, text)) raise nodes.SkipNode
def emph_literal_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) pos = 0 retnode = nodes.literal(role=typ.lower(), classes=[typ]) for m in _litvar_re.finditer(text): if m.start() > pos: txt = text[pos:m.start()] retnode += nodes.Text(txt, txt) retnode += nodes.emphasis(m.group(1), m.group(1)) pos = m.end() if pos < len(text): retnode += nodes.Text(text[pos:], text[pos:]) return [retnode], []
def apply(self): def is_inline(node): return isinstance(node, (nodes.literal, nodes.emphasis, nodes.strong)) for node in self.document.traverse(is_inline): if any(is_inline(subnode) for subnode in node): pos = node.parent.index(node) for subnode in reversed(node[1:]): node.remove(subnode) if is_inline(subnode): node.parent.insert(pos + 1, subnode) else: newnode = node.__class__('', subnode, **node.attributes) node.parent.insert(pos + 1, newnode)
def NotationRole(role, rawtext, text, lineno, inliner, options={}, content=[]): #pylint: disable=unused-argument, dangerous-default-value """And inline role for notations""" notation = utils.unescape(text, 1) position = inliner.reporter.get_source_and_line(lineno) return [nodes.literal(rawtext, '', parse_notation(notation, *position, rawtext=rawtext))], []
def run(self): # Uses a ‘container’ instead of a ‘literal_block’ to disable # Pygments-based post-processing (we could also set rawsource to '') content = '\n'.join(self.content) options = self.arguments[0].split() if self.arguments else ['in'] if 'all' in options: options.extend(['in', 'out']) node = nodes.container(content, coqtop_options = list(set(options)), classes=['coqtop', 'literal-block']) self.add_name(node) return [node]
def run(self): # Uses a ‘container’ instead of a ‘literal_block’ to disable # Pygments-based post-processing (we could also set rawsource to '') content = '\n'.join(self.content) node = nodes.inline(content, '', *highlight_using_coqdoc(content)) wrapper = nodes.container(content, node, classes=['coqdoc', 'literal-block']) return [wrapper]
def _create_cli_paragraph(self, feature): ''' Create a paragraph which represents the CLI commands of the feature The paragraph will have a bullet list of CLI commands. ''' para = nodes.paragraph() para.append(nodes.strong(text="CLI commands:")) commands = nodes.bullet_list() for c in feature.cli.split(";"): cli_command = nodes.list_item() cli_command += nodes.literal(text=c, classes=["sp_cli"]) commands.append(cli_command) para.append(commands) return para
def code_role(role, rawtext, text, lineno, inliner, options={}, content=[]): set_classes(options) language = options.get('language', '') classes = ['code'] if 'classes' in options: classes.extend(options['classes']) if language and language not in classes: classes.append(language) try: tokens = Lexer(utils.unescape(text, 1), language, inliner.document.settings.syntax_highlight) except LexerError as error: msg = inliner.reporter.warning(error) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] node = nodes.literal(rawtext, '', classes=classes) # analyse content and add nodes for every token for classes, value in tokens: # print (classes, value) if classes: node += nodes.inline(value, value, classes=classes) else: # insert as Text to decrease the verbosity of the output node += nodes.Text(value, value) return [node], []
def write_usage(self, prog, args='', prefix='Usage: '): """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line. """ title = nodes.subtitle() title.append(nodes.literal('', '{} {}'.format(self._topname, prog))) usage = nodes.paragraph() usage.append(nodes.Text(prefix)) usage.append(nodes.literal('', '{} {} {}'.format(self._topname, prog, args))) self._node.append(title) self._node.append(usage)