Python docutils.nodes.section() Examples
The following are 30
code examples of docutils.nodes.section().
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: parts.py From faces with GNU General Public License v2.0 | 6 votes |
def update_section_numbers(self, node, prefix=(), depth=0): depth += 1 if prefix: sectnum = 1 else: sectnum = self.startvalue for child in node: if isinstance(child, nodes.section): numbers = prefix + (str(sectnum),) title = child[0] # Use for spacing: generated = nodes.generated( '', (self.prefix + '.'.join(numbers) + self.suffix + u'\u00a0' * 3), classes=['sectnum']) title.insert(0, generated) title['auto'] = 1 if depth < self.maxdepth: self.update_section_numbers(child, numbers, depth) sectnum += 1
Example #2
Source File: ext_argparse.py From streamlink with BSD 2-Clause "Simplified" License | 6 votes |
def run(self): module = self.options.get("module") attr = self.options.get("attr") parser = get_parser(module, attr) self._available_options = [] for group in parser.groups: for arg in group.arguments: self._available_options += arg.args node = nodes.section() node.document = self.state.document result = ViewList() for line in self.generate_parser_rst(parser): result.append(line, "argparse") nested_parse_with_titles(self.state, result, node) return node.children
Example #3
Source File: states.py From faces with GNU General Public License v2.0 | 6 votes |
def new_subsection(self, title, lineno, messages): """Append new subsection to document tree. On return, check level.""" memo = self.memo mylevel = memo.section_level memo.section_level += 1 section_node = nodes.section() self.parent += section_node textnodes, title_messages = self.inline_text(title, lineno) titlenode = nodes.title(title, '', *textnodes) name = normalize_name(titlenode.astext()) section_node['names'].append(name) section_node += titlenode section_node += messages section_node += title_messages self.document.note_implicit_target(section_node, section_node) offset = self.state_machine.line_offset + 1 absoffset = self.state_machine.abs_line_offset() + 1 newabsoffset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=absoffset, node=section_node, match_titles=True) self.goto_line(newabsoffset) if memo.section_level <= mylevel: # can't handle next section? raise EOFError # bubble up to supersection # reset section_level; next pass will detect it properly memo.section_level = mylevel
Example #4
Source File: states.py From faces with GNU General Public License v2.0 | 6 votes |
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, []
Example #5
Source File: writers.py From sphinx-revealjs with Apache License 2.0 | 6 votes |
def visit_section(self, node: section): """Begin ``section`` node. - Find first ``revealjs_section`` node and build attributes string. - When enter next section, nest level. """ self.section_level += 1 meta = find_child_section(node, "revealjs_section") if meta is not None: attrs = meta.attributes_str() else: attrs = "" if self.section_level == 1: self.builder.revealjs_slide = find_child_section(node, "revealjs_slide") self._proc_first_on_section = True self.body.append("<section>\n") return if self._proc_first_on_section: self._proc_first_on_section = False self.body.append("</section>\n") self.body.append(f"<section {attrs}>\n") if has_child_sections(node, "section"): self._proc_first_on_section = True self.body.append("<section>\n")
Example #6
Source File: misc.py From faces with GNU General Public License v2.0 | 6 votes |
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)
Example #7
Source File: ext.py From rucio with Apache License 2.0 | 6 votes |
def ensureUniqueIDs(items): """ If action groups are repeated, then links in the table of contents will just go to the first of the repeats. This may not be desirable, particularly in the case of subcommands where the option groups have different members. This function updates the title IDs by adding _repeatX, where X is a number so that the links are then unique. """ s = set() for item in items: for n in item.traverse(descend=True, siblings=True, ascend=False): if isinstance(n, nodes.section): ids = n['ids'] for idx, id in enumerate(ids): if id not in s: s.add(id) else: i = 1 while "{}_repeat{}".format(id, i) in s: i += 1 ids[idx] = "{}_repeat{}".format(id, i) s.add(ids[idx]) n['ids'] = ids
Example #8
Source File: states.py From faces with GNU General Public License v2.0 | 6 votes |
def new_subsection(self, title, lineno, messages): """Append new subsection to document tree. On return, check level.""" memo = self.memo mylevel = memo.section_level memo.section_level += 1 section_node = nodes.section() self.parent += section_node textnodes, title_messages = self.inline_text(title, lineno) titlenode = nodes.title(title, '', *textnodes) name = normalize_name(titlenode.astext()) section_node['names'].append(name) section_node += titlenode section_node += messages section_node += title_messages self.document.note_implicit_target(section_node, section_node) offset = self.state_machine.line_offset + 1 absoffset = self.state_machine.abs_line_offset() + 1 newabsoffset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=absoffset, node=section_node, match_titles=True) self.goto_line(newabsoffset) if memo.section_level <= mylevel: # can't handle next section? raise EOFError # bubble up to supersection # reset section_level; next pass will detect it properly memo.section_level = mylevel
Example #9
Source File: pluginopts.py From Computable with MIT License | 5 votes |
def autohelp_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """produces rst from nose help""" config = Config(parserClass=OptBucket, plugins=BuiltinPluginManager()) parser = config.getParser(TestProgram.usage()) rst = ViewList() for line in parser.format_help().split('\n'): rst.append(line, '<autodoc>') rst.append('Options', '<autodoc>') rst.append('-------', '<autodoc>') rst.append('', '<autodoc>') for opt in parser: rst.append(opt.options(), '<autodoc>') rst.append(' \n', '<autodoc>') rst.append(' ' + opt.help + '\n', '<autodoc>') rst.append('\n', '<autodoc>') node = nodes.section() node.document = state.document surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children
Example #10
Source File: parts.py From faces with GNU General Public License v2.0 | 5 votes |
def apply(self): try: # let the writer (or output software) build the contents list? toc_by_writer = self.document.settings.use_latex_toc except AttributeError: toc_by_writer = False details = self.startnode.details if 'local' in details: startnode = self.startnode.parent.parent while not (isinstance(startnode, nodes.section) or isinstance(startnode, nodes.document)): # find the ToC root: a direct ancestor of startnode startnode = startnode.parent else: startnode = self.document self.toc_id = self.startnode.parent['ids'][0] if 'backlinks' in details: self.backlinks = details['backlinks'] else: self.backlinks = self.document.settings.toc_backlinks if toc_by_writer: # move customization settings to the parent node self.startnode.parent.attributes.update(details) self.startnode.parent.remove(self.startnode) else: contents = self.build_contents(startnode) if len(contents): self.startnode.replace_self(contents) else: self.startnode.parent.parent.remove(self.startnode.parent)
Example #11
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 []
Example #12
Source File: writers.py From sphinx-revealjs with Apache License 2.0 | 5 votes |
def depart_section(self, node: section): """End ``section``. Dedent section level """ self.section_level -= 1 if self.section_level >= 1: self.body.append("</section>\n")
Example #13
Source File: frontmatter.py From faces with GNU General Public License v2.0 | 5 votes |
def apply(self): if not getattr(self.document.settings, 'sectsubtitle_xform', 1): return for section in self.document.traverse(nodes.section): # On our way through the node tree, we are deleting # sections, but we call self.promote_subtitle for those # sections nonetheless. To do: Write a test case which # shows the problem and discuss on Docutils-develop. self.promote_subtitle(section)
Example #14
Source File: writers.py From sphinx-revealjs with Apache License 2.0 | 5 votes |
def has_child_sections(node: Element, name: str): """Search has specified section in children.""" nodes = set([n.tagname for n in node.children]) return name in nodes
Example #15
Source File: writers.py From sphinx-revealjs with Apache License 2.0 | 5 votes |
def find_child_section(node: Element, name: str): """Search and return first specified section in children.""" for n in node.children: if n.tagname == name: return n return None
Example #16
Source File: textwriter.py From deepWordBug with Apache License 2.0 | 5 votes |
def depart_title(self, node): if isinstance(node.parent, nodes.section): char = self._title_char else: char = '^' text = ''.join(x[1] for x in self.states.pop() if x[0] == -1) self.stateindent.pop() self.states[-1].append((0, ['', text, '%s' % (char * len(text)), '']))
Example #17
Source File: peps.py From deepWordBug with Apache License 2.0 | 5 votes |
def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1)
Example #18
Source File: rst.py From restbuilder with BSD 2-Clause "Simplified" License | 5 votes |
def depart_title(self, node): if isinstance(node.parent, nodes.section): char = self._title_char else: char = '^' text = ''.join(x[1] for x in self.states.pop() if x[0] == -1) self.stateindent.pop() self.states[-1].append((0, ['', text, '%s' % (char * len(text)), '']))
Example #19
Source File: parts.py From faces with GNU General Public License v2.0 | 5 votes |
def apply(self): self.maxdepth = self.startnode.details.get('depth', None) self.startvalue = self.startnode.details.get('start', 1) self.prefix = self.startnode.details.get('prefix', '') self.suffix = self.startnode.details.get('suffix', '') self.startnode.parent.remove(self.startnode) if self.document.settings.sectnum_xform: if self.maxdepth is None: self.maxdepth = sys.maxint self.update_section_numbers(self.document) else: # store details for eventual section numbering by the writer self.document.settings.sectnum_depth = self.maxdepth self.document.settings.sectnum_start = self.startvalue self.document.settings.sectnum_prefix = self.prefix self.document.settings.sectnum_suffix = self.suffix
Example #20
Source File: states.py From faces with GNU General Public License v2.0 | 5 votes |
def underline(self, match, context, next_state): """Section title.""" lineno = self.state_machine.abs_line_number() title = context[0].rstrip() underline = match.string.rstrip() source = title + '\n' + underline messages = [] if column_width(title) > len(underline): if len(underline) < 4: if self.state_machine.match_titles: msg = self.reporter.info( 'Possible title underline, too short for the title.\n' "Treating it as ordinary text because it's so short.", line=lineno) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.warning('Title underline too short.', nodes.literal_block(blocktext, blocktext), line=lineno) messages.append(msg) if not self.state_machine.match_titles: blocktext = context[0] + '\n' + self.state_machine.line # We need get_source_and_line() here to report correctly src, srcline = self.state_machine.get_source_and_line() # TODO: why is abs_line_number() == srcline+1 # if the error is in a table (try with test_tables.py)? # print "get_source_and_line", srcline # print "abs_line_number", self.state_machine.abs_line_number() msg = self.reporter.severe('Unexpected section title.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline) self.parent += messages self.parent += msg return [], next_state, [] style = underline[0] context[:] = [] self.section(title, source, style, lineno - 1, messages) return [], next_state, []
Example #21
Source File: frontmatter.py From faces with GNU General Public License v2.0 | 5 votes |
def candidate_index(self, node): """ Find and return the promotion candidate and its index. Return (None, None) if no valid candidate was found. """ index = node.first_child_not_matching_class( nodes.PreBibliographic) if index is None or len(node) > (index + 1) or \ not isinstance(node[index], nodes.section): return None, None else: return node[index], index
Example #22
Source File: peps.py From faces with GNU General Public License v2.0 | 5 votes |
def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent)
Example #23
Source File: peps.py From faces with GNU General Public License v2.0 | 5 votes |
def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1)
Example #24
Source File: textwriter.py From faces with GNU General Public License v2.0 | 5 votes |
def depart_title(self, node): if isinstance(node.parent, nodes.section): char = self._title_char else: char = '^' text = ''.join(x[1] for x in self.states.pop() if x[0] == -1) self.stateindent.pop() self.states[-1].append((0, ['', text, '%s' % (char * len(text)), '']))
Example #25
Source File: __init__.py From faces with GNU General Public License v2.0 | 5 votes |
def minitoc(self, node, title, depth): """Generate a local table of contents with LaTeX package minitoc""" section_name = self.d_class.section(self.section_level) # name-prefix for current section level minitoc_names = {'part': 'part', 'chapter': 'mini'} if 'chapter' not in self.d_class.sections: minitoc_names['section'] = 'sect' try: minitoc_name = minitoc_names[section_name] except KeyError: # minitoc only supports part- and toplevel self.warn('Skipping local ToC at %s level.\n' % section_name + ' Feature not supported with option "use-latex-toc"', base_node=node) return # Requirements/Setup self.requirements['minitoc'] = PreambleCmds.minitoc self.requirements['minitoc-'+minitoc_name] = (r'\do%stoc' % minitoc_name) # depth: (Docutils defaults to unlimited depth) maxdepth = len(self.d_class.sections) self.requirements['minitoc-%s-depth' % minitoc_name] = ( r'\mtcsetdepth{%stoc}{%d}' % (minitoc_name, maxdepth)) # Process 'depth' argument (!Docutils stores a relative depth while # minitoc expects an absolute depth!): offset = {'sect': 1, 'mini': 0, 'part': 0} if 'chapter' in self.d_class.sections: offset['part'] = -1 if depth: self.out.append('\\setcounter{%stocdepth}{%d}' % (minitoc_name, depth + offset[minitoc_name])) # title: self.out.append('\\mtcsettitle{%stoc}{%s}\n' % (minitoc_name, title)) # the toc-generating command: self.out.append('\\%stoc\n' % minitoc_name)
Example #26
Source File: __init__.py From faces with GNU General Public License v2.0 | 5 votes |
def visit_subtitle(self, node): if isinstance(node.parent, nodes.document): self.push_output_collector(self.subtitle) self.fallbacks['documentsubtitle'] = PreambleCmds.documentsubtitle self.subtitle_labels += self.ids_to_labels(node, set_anchor=False) # section subtitle: "starred" (no number, not in ToC) elif isinstance(node.parent, nodes.section): self.out.append(r'\%s*{' % self.d_class.section(self.section_level + 1)) else: self.fallbacks['subtitle'] = PreambleCmds.subtitle self.out.append('\n\\DUsubtitle[%s]{' % node.parent.tagname)
Example #27
Source File: __init__.py From faces with GNU General Public License v2.0 | 5 votes |
def visit_section(self, node): self.section_level += 1 # Initialize counter for potential subsections: self._section_number.append(0) # Counter for this section's level (initialized by parent section): self._section_number[self.section_level - 1] += 1
Example #28
Source File: __init__.py From faces with GNU General Public License v2.0 | 5 votes |
def depart_label(self, node): self.label_delim(node, ']', '}') # elements generated by the framework e.g. section numbers.
Example #29
Source File: __init__.py From faces with GNU General Public License v2.0 | 5 votes |
def section(self, level): """Return the LaTeX section name for section `level`. The name depends on the specific document class. Level is 1,2,3..., as level 0 is the title. """ if level <= len(self.sections): return self.sections[level-1] else: # unsupported levels return 'DUtitle[section%s]' % roman.toRoman(level)
Example #30
Source File: autosummary__init__.py From pyGSTi with Apache License 2.0 | 5 votes |
def process_autosummary_toc(app, doctree): """Insert items described in autosummary:: to the TOC tree, but do not generate the toctree:: list. """ #print "DEBUG: process_autosummary_toc" env = app.builder.env crawled = {} def crawl_toc(node, depth=1): crawled[node] = True for j, subnode in enumerate(node): #print "DEBUG: processing ",(j,subnode) try: if (isinstance(subnode, autosummary_toc) and isinstance(subnode[0], addnodes.toctree)): env.note_toctree(env.docname, subnode[0]) #print "DEBUG: ADDIND DOC!" continue except IndexError: #print "DEBUG: indexerror" continue if not isinstance(subnode, nodes.section): #print "DEBUG: not instance" continue if subnode not in crawled: crawl_toc(subnode, depth+1) crawl_toc(doctree)