我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用docutils.nodes.paragraph()。
def run(self): oldStdout, sys.stdout = sys.stdout, StringIO() tab_width = self.options.get('tab-width', self.state.document.settings.tab_width) source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1) try: exec('\n'.join(self.content)) text = sys.stdout.getvalue() lines = statemachine.string2lines(text, tab_width, convert_whitespace=True) self.state_machine.insert_input(lines, source) return [] except Exception: return [nodes.error(None, nodes.paragraph(text = "Unable to execute python code at %s:%d:" % (basename(source), self.lineno)), nodes.paragraph(text = str(sys.exc_info()[1])))] finally: sys.stdout = oldStdout
def visit_list_item(self, node): children = [] for child in node.children: if not isinstance(child, nodes.Invisible): children.append(child) if (children and isinstance(children[0], nodes.paragraph) and (isinstance(children[-1], nodes.bullet_list) or isinstance(children[-1], nodes.enumerated_list))): children.pop() if len(children) <= 1: return else: raise nodes.NodeFound # def visit_bullet_list(self, node): # pass # def visit_enumerated_list(self, node): # pass # def visit_paragraph(self, node): # raise nodes.SkipNode
def depart_organization(self, node): self.depart_docinfo_item() # Do not omit <p> tags # -------------------- # # The HTML4CSS1 writer does this to "produce # visually compact lists (less vertical whitespace)". This writer # relies on CSS rules for"visual compactness". # # * In XHTML 1.1, e.g. a <blockquote> element may not contain # character data, so you cannot drop the <p> tags. # * Keeping simple paragraphs in the field_body enables a CSS # rule to start the field-body on a new line if the label is too long # * it makes the code simpler. # # TODO: omit paragraph tags in simple table cells?
def visit_list_item(self, node): # print "visiting list item", node.__class__ children = [child for child in node.children if not isinstance(child, nodes.Invisible)] # print "has %s visible children" % len(children) if (children and isinstance(children[0], nodes.paragraph) and (isinstance(children[-1], nodes.bullet_list) or isinstance(children[-1], nodes.enumerated_list) or isinstance(children[-1], nodes.field_list))): children.pop() # print "%s children remain" % len(children) if len(children) <= 1: return else: # print "found", child.__class__, "in", node.__class__ raise nodes.NodeFound
def visit_footnote(self, node): try: backref = node['backrefs'][0] except IndexError: backref = node['ids'][0] # no backref, use self-ref instead if self.docutils_footnotes: self.fallbacks['footnotes'] = PreambleCmds.footnotes num = node[0].astext() if self.settings.footnote_references == 'brackets': num = '[%s]' % num self.out.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{' % (node['ids'][0], backref, self.encode(num))) if node['ids'] == node['names']: self.out += self.ids_to_labels(node) # mask newline to prevent spurious whitespace if paragraph follows: if node[1:] and isinstance(node[1], nodes.paragraph): self.out.append('%') ## else: # TODO: "real" LaTeX \footnote{}s
def visit_table(self, node): self.requirements['table'] = PreambleCmds.table if self.active_table.is_open(): self.table_stack.append(self.active_table) # nesting longtable does not work (e.g. 2007-04-18) self.active_table = Table(self,'tabular') # A longtable moves before \paragraph and \subparagraph # section titles if it immediately follows them: if (self.active_table._latex_type == 'longtable' and isinstance(node.parent, nodes.section) and node.parent.index(node) == 1 and self.d_class.section(self.section_level).find('paragraph') != -1): self.out.append('\\leavevmode') self.active_table.open() self.active_table.set_table_style(self.settings.table_style, node['classes']) if 'align' in node: self.active_table.set('align', node['align']) if self.active_table.borders == 'booktabs': self.requirements['booktabs'] = r'\usepackage{booktabs}' self.push_output_collector([])
def extract_extension_options(field_list, options_spec): """ Return a dictionary mapping extension option names to converted values. :Parameters: - `field_list`: A flat field list without field arguments, where each field body consists of a single paragraph only. - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `ValueError` for invalid option values (raised by the conversion function). - `TypeError` for invalid option value types (raised by conversion function). - `DuplicateOptionError` for duplicate options. - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.). """ option_list = extract_options(field_list) option_dict = assemble_option_dict(option_list, options_spec) return option_dict
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 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 run(self): pnode = nodes.compound(classes=['impl-detail']) content = self.content add_text = nodes.strong('CPython implementation detail:', 'CPython implementation detail:') if self.arguments: n, m = self.state.inline_text(self.arguments[0], self.lineno) pnode.append(nodes.paragraph('', '', *(n + m))) self.state.nested_parse(content, self.content_offset, pnode) if pnode.children and isinstance(pnode[0], nodes.paragraph): pnode[0].insert(0, add_text) pnode[0].insert(1, nodes.Text(' ')) else: pnode.insert(0, nodes.paragraph('', '', add_text)) return [pnode] # Support for documenting decorators
def format_parser_error(name, error, filename, state, lineno, do_unicode_warning): warning = '%s: Unable to parse xml file "%s". ' % (name, filename) explanation = 'Reported error: %s. ' % error unicode_explanation_text = "" unicode_explanation = [] if do_unicode_warning: unicode_explanation_text = textwrap.dedent(""" Parsing errors are often due to unicode errors associated with the encoding of the original source files. Doxygen propagates invalid characters from the input source files to the output xml.""").strip().replace("\n", " ") unicode_explanation = [nodes.paragraph("", "", nodes.Text(unicode_explanation_text))] return [nodes.warning("", nodes.paragraph("", "", nodes.Text(warning)), nodes.paragraph("", "", nodes.Text(explanation)), *unicode_explanation ), state.document.reporter.warning(warning + explanation + unicode_explanation_text, line=lineno) ]
def visit_paragraph(self, node): # insert blank line, if the paragraph is not first in a list item # nor follows a non-paragraph node in a compound index = node.parent.index(node) if (index == 0 and (isinstance(node.parent, nodes.list_item) or isinstance(node.parent, nodes.description))): pass elif (index > 0 and isinstance(node.parent, nodes.compound) and not isinstance(node.parent[index - 1], nodes.paragraph) and not isinstance(node.parent[index - 1], nodes.compound)): pass else: self.out.append('\n') if node.get('ids'): self.out += self.ids_to_labels(node) + ['\n'] if node['classes']: self.visit_inline(node)
def visit_table(self, node): self.requirements['table'] = PreambleCmds.table if self.active_table.is_open(): self.table_stack.append(self.active_table) # nesting longtable does not work (e.g. 2007-04-18) self.active_table = Table(self,'tabular',self.settings.table_style) # A longtable moves before \paragraph and \subparagraph # section titles if it immediately follows them: if (self.active_table._latex_type == 'longtable' and isinstance(node.parent, nodes.section) and node.parent.index(node) == 1 and self.d_class.section(self.section_level).find('paragraph') != -1): self.out.append('\\leavevmode') self.active_table.open() for cls in node['classes']: self.active_table.set_table_style(cls) if self.active_table._table_style == 'booktabs': self.requirements['booktabs'] = r'\usepackage{booktabs}' self.push_output_collector([])
def run(self): env = self.state.document.settings.env if not env.config.show_authors: return [] para = nodes.paragraph(translatable=False) emph = nodes.emphasis() para += emph if self.name == 'sectionauthor': text = _('Section author: ') elif self.name == 'moduleauthor': text = _('Module author: ') elif self.name == 'codeauthor': text = _('Code author: ') else: text = _('Author: ') emph += nodes.Text(text, text) inodes, messages = self.state.inline_text(self.arguments[0], self.lineno) emph.extend(inodes) return [para] + messages
def run(self): ncolumns = self.options.get('columns', 2) node = nodes.paragraph() node.document = self.state.document self.state.nested_parse(self.content, self.content_offset, node) if len(node.children) != 1 or not isinstance(node.children[0], nodes.bullet_list): return [self.state.document.reporter.warning( '.. hlist content is not a list', line=self.lineno)] fulllist = node.children[0] # create a hlist node where the items are distributed npercol, nmore = divmod(len(fulllist), ncolumns) index = 0 newnode = addnodes.hlist() for column in range(ncolumns): endindex = index + (column < nmore and (npercol+1) or npercol) col = addnodes.hlistcol() col += nodes.bullet_list() col[0] += fulllist.children[index:endindex] index = endindex newnode += col return [newnode]
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 visit_list_item(self, node): """ :param docutils.nodes.list_item node: """ # 0: name # 1: ' -- ' # 2: description content = node[0] # paragraph node # normalize the header name so that words are upper-cased normalized = ' '.join('-'.join(elm.title() for elm in word.split('-')) for word in content[0].astext().split()) if len(content) > 2: first_para = content[2].astext() words = first_para.split() words[0] = words[0].title() paragraphs = [' '.join(words)] paragraphs.extend(t.astext().replace('\n', ' ').strip() for t in content[3:]) description = ' '.join(paragraphs) else: description = '' self.headers[normalized] = description
def print_arg_list(data, nested_content): definitions = map_nested_definitions(nested_content) items = [] if 'args' in data: for arg in data['args']: my_def = [nodes.paragraph(text=arg['help'])] if arg['help'] else [] name = arg['name'] my_def = apply_definition(definitions, my_def, name) if len(my_def) == 0: my_def.append(nodes.paragraph(text='Undocumented')) if 'choices' in arg: my_def.append(nodes.paragraph( text=('Possible choices: %s' % ', '.join([str(c) for c in arg['choices']])))) items.append( nodes.option_list_item( '', nodes.option_group('', nodes.option_string(text=name)), nodes.description('', *my_def))) return nodes.option_list('', *items) if items else None
def print_opt_list(data, nested_content): definitions = map_nested_definitions(nested_content) items = [] if 'options' in data: for opt in data['options']: names = [] my_def = [nodes.paragraph(text=opt['help'])] if opt['help'] else [] for name in opt['name']: option_declaration = [nodes.option_string(text=name)] if opt['default'] is not None \ and opt['default'] != '==SUPPRESS==': option_declaration += nodes.option_argument( '', text='=' + str(opt['default'])) names.append(nodes.option('', *option_declaration)) my_def = apply_definition(definitions, my_def, name) if len(my_def) == 0: my_def.append(nodes.paragraph(text='Undocumented')) if 'choices' in opt: my_def.append(nodes.paragraph( text=('Possible choices: %s' % ', '.join([str(c) for c in opt['choices']])))) items.append( nodes.option_list_item( '', nodes.option_group('', *names), nodes.description('', *my_def))) return nodes.option_list('', *items) if items else None
def _format_positional_arguments(self, parser_info): assert 'args' in parser_info items = [] for arg in parser_info['args']: arg_items = [] if arg['help']: arg_items.append(nodes.paragraph(text=arg['help'])) else: arg_items.append(nodes.paragraph(text='Undocumented')) if 'choices' in arg: arg_items.append( nodes.paragraph( text='Possible choices: ' + ', '.join(arg['choices']))) items.append( nodes.option_list_item( '', nodes.option_group( '', nodes.option( '', nodes.option_string(text=arg['metavar']) ) ), nodes.description('', *arg_items))) return nodes.option_list('', *items)
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 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 _parse(self, rst_text, annotation): result = ViewList() for line in rst_text.split("\n"): result.append(line, annotation) node = nodes.paragraph() node.document = self.state.document nested_parse_with_titles(self.state, result, node) return node.children