我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用docutils.nodes.table()。
def build_table(self, tabledata, tableline, stub_columns=0, widths=None): colwidths, headrows, bodyrows = tabledata table = nodes.table() if widths == 'auto': table['classes'] += ['colwidths-auto'] elif widths: # "grid" or list of integers table['classes'] += ['colwidths-given'] tgroup = nodes.tgroup(cols=len(colwidths)) table += tgroup for colwidth in colwidths: colspec = nodes.colspec(colwidth=colwidth) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec if headrows: thead = nodes.thead() tgroup += thead for row in headrows: thead += self.build_table_row(row, tableline) tbody = nodes.tbody() tgroup += tbody for row in bodyrows: tbody += self.build_table_row(row, tableline) return table
def depart_row(self, node): self.body.append('\\\\') if any(self.remember_multirow.values()): linestart = 1 col = self.table.colcount for col in range(1, self.table.col + 1): if self.remember_multirow.get(col): if linestart != col: linerange = str(linestart) + '-' + str(col - 1) self.body.append('\\cline{' + linerange + '}') linestart = col + 1 if self.remember_multirowcol.get(col, 0): linestart += self.remember_multirowcol[col] if linestart <= col: linerange = str(linestart) + '-' + str(col) self.body.append('\\cline{' + linerange + '}') else: self.body.append('\\hline\n') self.table.rowcount += 1
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 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_paragraph(self, node): # insert blank line, unless # * the paragraph is first in a list item, # * follows a non-paragraph node in a compound, # * is in a table with auto-width columns 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 elif self.active_table.colwidths_auto: if index == 1: # second paragraph self.warn('LaTeX merges paragraphs in tables ' 'with auto-sized columns!', base_node=node) if index > 0: self.out.append('\n') 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 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 table(self, isolate_function, parser_class): """Parse a table.""" block, messages, blank_finish = isolate_function() if block: try: parser = parser_class() tabledata = parser.parse(block) tableline = (self.state_machine.abs_line_number() - len(block) + 1) table = self.build_table(tabledata, tableline) nodelist = [table] + messages except tableparser.TableMarkupError, err: nodelist = self.malformed_table(block, ' '.join(err.args), offset=err.offset) + messages else: nodelist = messages return nodelist, blank_finish
def build_table(self, tabledata, tableline, stub_columns=0, widths=None): colwidths, headrows, bodyrows = tabledata table = nodes.table() if widths: table['classes'] += ['colwidths-%s' % widths] tgroup = nodes.tgroup(cols=len(colwidths)) table += tgroup for colwidth in colwidths: colspec = nodes.colspec(colwidth=colwidth) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec if headrows: thead = nodes.thead() tgroup += thead for row in headrows: thead += self.build_table_row(row, tableline) tbody = nodes.tbody() tgroup += tbody for row in bodyrows: tbody += self.build_table_row(row, tableline) return table
def visit_paragraph(self, node): # insert blank line, unless # * the paragraph is first in a list item or compound, # * follows a non-paragraph node in a compound, # * is in a table with auto-width columns index = node.parent.index(node) if index == 0 and isinstance(node.parent, (nodes.list_item, nodes.description, nodes.compound)): 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 elif self.active_table.colwidths_auto: if index == 1: # second paragraph self.warn('LaTeX merges paragraphs in tables ' 'with auto-sized columns!', base_node=node) if index > 0: self.out.append('\n') 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 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 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 depart_table(self, node): # wrap content in the right environment: content = self.out self.pop_output_collector() self.out.append('\n' + self.active_table.get_opening()) self.out += content self.out.append(self.active_table.get_closing() + '\n') self.active_table.close() if len(self.table_stack)>0: self.active_table = self.table_stack.pop() else: self.active_table.set_table_style(self.settings.table_style) # Insert hyperlabel after (long)table, as # other places (beginning, caption) result in LaTeX errors. if node.get('ids'): self.out += self.ids_to_labels(node, set_anchor=False) + ['\n']
def run(self): if not self.content: warning = self.state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [warning] title, messages = self.make_title() node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) if len(node) != 1 or not isinstance(node[0], nodes.table): error = self.state_machine.reporter.error( 'Error parsing content block for the "%s" directive: exactly ' 'one table expected.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [error] table_node = node[0] table_node['classes'] += self.options.get('class', []) self.add_name(table_node) if title: table_node.insert(0, title) return [table_node] + messages
def build_table(self, tabledata, tableline, stub_columns=0): colwidths, headrows, bodyrows = tabledata table = nodes.table() tgroup = nodes.tgroup(cols=len(colwidths)) table += tgroup for colwidth in colwidths: colspec = nodes.colspec(colwidth=colwidth) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec if headrows: thead = nodes.thead() tgroup += thead for row in headrows: thead += self.build_table_row(row, tableline) tbody = nodes.tbody() tgroup += tbody for row in bodyrows: tbody += self.build_table_row(row, tableline) return table
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 autosummary_table_visit_html(self, node): """Make the first column of the table non-breaking.""" try: tbody = node[0][0][-1] for row in tbody: col1_entry = row[0] par = col1_entry[0] for j, subnode in enumerate(list(par)): if isinstance(subnode, nodes.Text): new_text = text_type(subnode.astext()) new_text = new_text.replace(u" ", u"\u00a0") par[j] = nodes.Text(new_text) except IndexError: pass # -- autodoc integration -------------------------------------------------------
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 visit_title(self, node): if not self.seen_title: self.seen_title = 1 raise nodes.SkipNode parent = node.parent if isinstance(parent, nodes.table): return if isinstance(parent, (nodes.Admonition, nodes.sidebar, nodes.topic)): raise nodes.SkipNode elif not isinstance(parent, nodes.section): self.builder.warn( 'encountered title node not in section, topic, table, ' 'admonition or sidebar', (self.curfilestack[-1], node.line)) self.visit_rubric(node) else: try: heading = self.headings[self.section_level] except IndexError: heading = self.headings[-1] self.body.append('\n%s ' % heading)
def depart_row(self, node): self.body.append('\\\\\n') if any(self.remember_multirow.values()): linestart = 1 col = self.table.colcount for col in range(1, self.table.col + 1): if self.remember_multirow.get(col): if linestart != col: linerange = str(linestart) + '-' + str(col - 1) self.body.append('\\cline{' + linerange + '}') linestart = col + 1 if self.remember_multirowcol.get(col, 0): linestart += self.remember_multirowcol[col] if linestart <= col: linerange = str(linestart) + '-' + str(col) self.body.append('\\cline{' + linerange + '}') else: self.body.append('\\hline') self.table.rowcount += 1
def depart_title(self, node): close_tag = self.context[-1] if (self.permalink_text and self.builder.add_permalinks and node.parent.hasattr('ids') and node.parent['ids']): # add permalink anchor if close_tag.startswith('</h'): self.add_permalink_ref(node.parent, _('Permalink to this headline')) elif close_tag.startswith('</a></h'): self.body.append(u'</a><a class="headerlink" href="#%s" ' % node.parent['ids'][0] + u'title="%s">%s' % ( _('Permalink to this headline'), self.permalink_text)) elif isinstance(node.parent, nodes.table): self.body.append('</span>') self.add_permalink_ref(node.parent, _('Permalink to this table')) BaseTranslator.depart_title(self, node) # overwritten to add even/odd classes
def table(self, isolate_function, parser_class): """Parse a table.""" block, messages, blank_finish = isolate_function() if block: try: parser = parser_class() tabledata = parser.parse(block) tableline = (self.state_machine.abs_line_number() - len(block) + 1) table = self.build_table(tabledata, tableline) nodelist = [table] + messages except tableparser.TableMarkupError as err: nodelist = self.malformed_table(block, ' '.join(err.args), offset=err.offset) + messages else: nodelist = messages return nodelist, blank_finish
def depart_title(self, node): self.in_title = 0 if isinstance(node.parent, nodes.table): self.table.caption = self.popbody() else: self.body.append(self.context.pop()) self.unrestrict_footnote(node)
def visit_desc(self, node): self.body.append('\n\n\\begin{fulllineitems}\n') if self.table: self.table.has_problematic = True
def visit_table(self, node): if self.table: raise UnsupportedError( '%s:%s: nested tables are not yet implemented.' % (self.curfilestack[-1], node.line or '')) self.table = Table() self.table.longtable = 'longtable' in node['classes'] self.tablebody = [] self.tableheaders = [] # Redirect body output until table is finished. self.pushbody(self.tablebody) self.restrict_footnote(node)
def visit_colspec(self, node): self.table.colcount += 1
def visit_thead(self, node): self.table.had_head = True if self.next_table_colspec: self.table.colspec = '{%s}\n' % self.next_table_colspec self.next_table_colspec = None # Redirect head output until header is finished. see visit_tbody. self.body = self.tableheaders
def visit_tbody(self, node): if not self.table.had_head: self.visit_thead(node) self.body = self.tablebody
def visit_row(self, node): self.table.col = 0 for key, value in self.remember_multirow.items(): if not value and key in self.remember_multirowcol: del self.remember_multirowcol[key]
def visit_bullet_list(self, node): if not self.compact_list: self.body.append('\\begin{itemize}\n') if self.table: self.table.has_problematic = True
def visit_enumerated_list(self, node): self.body.append('\\begin{enumerate}\n') if 'start' in node: self.body.append('\\setcounter{enumi}{%d}\n' % (node['start'] - 1)) if self.table: self.table.has_problematic = True
def visit_definition_list(self, node): self.body.append('\\begin{description}\n') if self.table: self.table.has_problematic = True
def visit_field_list(self, node): self.body.append('\\begin{quote}\\begin{description}\n') if self.table: self.table.has_problematic = True
def visit_centered(self, node): self.body.append('\n\\begin{center}') if self.table: self.table.has_problematic = True
def visit_caption(self, node): self.in_caption += 1 if self.in_container_literal_block: # Track the caption body separately self.literal_block_caption = [] self.pushbody(self.literal_block_caption) elif self.in_minipage and isinstance(node.parent, nodes.figure): self.body.append('\\captionof{figure}{') elif self.table and node.parent.tagname == 'figure': self.body.append('\\sphinxfigcaption{') else: self.body.append('\\caption{')
def visit_line_block(self, node): if isinstance(node.parent, nodes.line_block): self.body.append('\\item[]\n' '\\begin{DUlineblock}{\\DUlineblockindent}\n') else: self.body.append('\n\\begin{DUlineblock}{0em}\n') if self.table: self.table.has_problematic = True
def visit_block_quote(self, node): # If the block quote contains a single object and that object # is a list, then generate a list not a block quote. # This lets us indent lists. done = 0 if len(node.children) == 1: child = node.children[0] if isinstance(child, nodes.bullet_list) or \ isinstance(child, nodes.enumerated_list): done = 1 if not done: self.body.append('\\begin{quote}\n') if self.table: self.table.has_problematic = True