我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用docutils.nodes.literal_block()。
def apply(self): pending = self.startnode parent = pending.parent child = pending while parent: # Check for appropriate following siblings: for index in range(parent.index(child) + 1, len(parent)): element = parent[index] if (isinstance(element, nodes.Invisible) or isinstance(element, nodes.system_message)): continue element['classes'] += pending.details['class'] pending.parent.remove(pending) return else: # At end of section or container; apply to sibling child = parent parent = parent.parent error = self.document.reporter.error( 'No suitable element following "%s" directive' % pending.details['directive'], nodes.literal_block(pending.rawsource, pending.rawsource), line=pending.line) pending.replace_self(error)
def get_column_widths(self, max_cols): if type(self.widths) == list: if len(self.widths) != max_cols: error = self.state_machine.reporter.error( '"%s" widths do not match the number of columns in table ' '(%s).' % (self.name, max_cols), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) col_widths = self.widths elif max_cols: col_widths = [100 // max_cols] * max_cols else: error = self.state_machine.reporter.error( 'No table data detected in CSV file.', nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) if self.widths == 'auto': widths = 'auto' elif self.widths: # "grid" or list of integers widths = 'given' else: widths = self.widths return widths, col_widths
def run(self): if not self.arguments: if '' in roles._roles: # restore the "default" default role del roles._roles[''] return [] role_name = self.arguments[0] role, messages = roles.role(role_name, self.state_machine.language, self.lineno, self.state.reporter) if role is None: error = self.state.reporter.error( 'Unknown interpreted text role "%s".' % role_name, nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return messages + [error] roles._roles[''] = role # @@@ should this be local to the document, not the parser? return messages
def paragraph(self, lines, lineno): """ Return a list (paragraph & messages) & a boolean: literal_block next? """ data = '\n'.join(lines).rstrip() if re.search(r'(?<!\\)(\\\\)*::$', data): if len(data) == 2: return [], 1 elif data[-3] in ' \n': text = data[:-3].rstrip() else: text = data[:-1] literalnext = 1 else: text = data literalnext = 0 textnodes, messages = self.inline_text(text, lineno) p = nodes.paragraph(data, '', *textnodes) p.source, p.line = self.state_machine.get_source_and_line(lineno) return [p] + messages, literalnext
def line(self, match, context, next_state): """Section title overline or transition marker.""" if self.state_machine.match_titles: return [match.string], 'Line', [] elif match.string.strip() == '::': raise statemachine.TransitionCorrection('text') elif len(match.string.strip()) < 4: msg = self.reporter.info( 'Unexpected possible title overline or transition.\n' "Treating it as ordinary text because it's so short.", line=self.state_machine.abs_line_number()) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = self.state_machine.line msg = self.reporter.severe( 'Unexpected section title or transition.', nodes.literal_block(blocktext, blocktext), line=self.state_machine.abs_line_number()) self.parent += msg return [], next_state, []
def text(self, match, context, next_state): """Paragraph.""" startline = self.state_machine.abs_line_number() - 1 msg = None try: block = self.state_machine.get_text_block(flush_left=True) except statemachine.UnexpectedIndentationError, err: block, src, srcline = err.args msg = self.reporter.error('Unexpected indentation.', source=src, line=srcline) lines = context + list(block) paragraph, literalnext = self.paragraph(lines, startline) self.parent += paragraph self.parent += msg if literalnext: try: self.state_machine.next_line() except EOFError: pass self.parent += self.literal_block() return [], next_state, []
def eof(self, context): if context: src, srcline = self.state_machine.get_source_and_line( self.initial_lineno) text = '\n'.join(context) literal_block = nodes.literal_block(text, text) literal_block.source = src literal_block.line = srcline self.parent += literal_block else: self.parent += self.reporter.warning( 'Literal block expected; none found.', line=self.state_machine.abs_line_number()) # src not available, because statemachine.input_lines is empty self.state_machine.previous_line() self.parent += self.messages return []
def get_column_widths(self, max_cols): if type(self.widths) == list: if len(self.widths) != max_cols: error = self.state_machine.reporter.error( '"%s" widths do not match the number of columns in table ' '(%s).' % (self.name, max_cols), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) col_widths = self.widths elif max_cols: col_widths = [100 // max_cols] * max_cols else: error = self.state_machine.reporter.error( 'No table data detected in CSV file.', nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) return col_widths
def process_lean_nodes(app, doctree, fromdocname): for node in doctree.traverse(nodes.literal_block): if node['language'] != 'lean': continue new_node = lean_code_goodies() new_node['full_code'] = node.rawsource node.replace_self([new_node]) code = node.rawsource m = re.search(r'--[^\n]*BEGIN[^\n]*\n(.*)--[^\n]*END', code, re.DOTALL) if m: node = nodes.literal_block(m.group(1), m.group(1)) node['language'] = 'lean' new_node += node if app.builder.name.startswith('epub'): new_node.replace_self([node])
def get_column_widths(self, max_cols): if 'widths' in self.options: col_widths = self.options['widths'] if len(col_widths) != max_cols: error = self.state_machine.reporter.error( '"%s" widths do not match the number of columns in table ' '(%s).' % (self.name, max_cols), nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) elif max_cols: col_widths = [100 // max_cols] * max_cols else: error = self.state_machine.reporter.error( 'No table data detected in CSV file.', nodes.literal_block( self.block_text, self.block_text), line=self.lineno) raise SystemMessagePropagation(error) return col_widths
def run(self): if not self.arguments: if '' in roles._roles: # restore the "default" default role del roles._roles[''] return [] role_name = self.arguments[0] role, messages = roles.role(role_name, self.state_machine.language, self.lineno, self.state.reporter) if role is None: error = self.state.reporter.error( 'Unknown interpreted text role "%s".' % role_name, nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return messages + [error] roles._roles[''] = role self.state.document.settings.env.temp_data['default_role'] = role_name return messages
def apply(self): def has_child(node, cls): return any(isinstance(child, cls) for child in node) for node in self.document.traverse(nodes.Element): if isinstance(node, nodes.figure): if has_child(node, nodes.caption): self.document.note_implicit_target(node) elif isinstance(node, nodes.image): if node.parent and has_child(node.parent, nodes.caption): self.document.note_implicit_target(node.parent) elif isinstance(node, nodes.table): if has_child(node, nodes.title): self.document.note_implicit_target(node) elif isinstance(node, nodes.literal_block): if node.parent and has_child(node.parent, nodes.caption): self.document.note_implicit_target(node.parent)
def get_figtype(node): """Return figtype for given node.""" def has_child(node, cls): return any(isinstance(child, cls) for child in node) from docutils import nodes if isinstance(node, nodes.figure): return 'figure' elif isinstance(node, nodes.image) and isinstance(node.parent, nodes.figure): # bare image node is not supported because it doesn't have caption and # no-caption-target isn't a numbered figure. return 'figure' elif isinstance(node, nodes.table): return 'table' elif isinstance(node, nodes.container): if has_child(node, nodes.literal_block): return 'code-block' return None
def simplify_source_code_blocks_for_latex(app, doctree, fromdocname): # pylint: disable=unused-argument """Simplify coqdoc and coqtop blocks. In HTML mode, this does nothing; in other formats, such as LaTeX, it replaces coqdoc and coqtop blocks by plain text sources, which will use pygments if available. This prevents the LaTeX builder from getting confused. """ is_html = app.builder.tags.has("html") for node in doctree.traverse(is_coqtop_or_coqdoc_block): if is_html: node.rawsource = '' # Prevent pygments from kicking in else: if 'coqtop-hidden' in node['classes']: node.parent.remove(node) else: node.replace_self(nodes.literal_block(node.rawsource, node.rawsource, language="Coq"))
def text(self, match, context, next_state): """Paragraph.""" startline = self.state_machine.abs_line_number() - 1 msg = None try: block = self.state_machine.get_text_block(flush_left=True) except statemachine.UnexpectedIndentationError as err: block, src, srcline = err.args msg = self.reporter.error('Unexpected indentation.', source=src, line=srcline) lines = context + list(block) paragraph, literalnext = self.paragraph(lines, startline) self.parent += paragraph self.parent += msg if literalnext: try: self.state_machine.next_line() except EOFError: pass self.parent += self.literal_block() return [], next_state, []
def run(self): # create a list of document nodes to return doc_nodes = [] for arg in self.arguments: # grabbing a list of the code segments that contain the # title, source, and output of a test segment. codelist = get_test_source_code_for_feature(arg) for code in codelist: (title, src, output) = code # the title can be contained in a special title node title_node = nodes.line(title, title) # we want the body of test code to be formatted and code highlighted body = nodes.literal_block(src, src) body['language'] = 'python' # we want the output block to also be formatted similarly output_node = nodes.literal_block(output, output) # put the nodes we've created in the list, and return them doc_nodes.append(title_node) doc_nodes.append(body) doc_nodes.append(output_node) return doc_nodes
def run(self): # create a list of document nodes to return doc_nodes = [] for arg in self.arguments: # grabbing a list of the code segments that contain the # title, source, and output of a test segment. code = get_source_code_of_class_or_method(arg) # we want the body of test code to be formatted and code highlighted body = nodes.literal_block(code, code) body['language'] = 'python' # put the nodes we've created in the list, and return them doc_nodes.append(body) return doc_nodes
def visit_productionlist(self, node): replacement=nodes.literal_block(classes=["code"]) names = [] for production in node: names.append(production['tokenname']) maxlen = max(len(name) for name in names) for production in node: if production['tokenname']: lastname = production['tokenname'].ljust(maxlen) n=nodes.strong() n+=nodes.Text(lastname) replacement+=n replacement+=nodes.Text(' ::= ') else: replacement+=nodes.Text('%s ' % (' '*len(lastname))) production.walkabout(self) replacement.children.extend(production.children) replacement+=nodes.Text('\n') node.parent.replace(node,replacement) raise nodes.SkipNode
def visit_subscript(self, node): if isinstance(node.parent, nodes.literal_block): self.body.append(self.starttag(node, 'span', '', CLASS='subscript')) else: self.body.append(self.starttag(node, 'sub', ''))
def depart_subscript(self, node): if isinstance(node.parent, nodes.literal_block): self.body.append('</span>') else: self.body.append('</sub>') # Use <h*> for subtitles (deprecated in HTML 5)
def visit_superscript(self, node): if isinstance(node.parent, nodes.literal_block): self.body.append(self.starttag(node, 'span', '', CLASS='superscript')) else: self.body.append(self.starttag(node, 'sup', ''))
def depart_superscript(self, node): if isinstance(node.parent, nodes.literal_block): self.body.append('</span>') else: self.body.append('</sup>') # <tt> element deprecated in HTML 5