我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用docutils.nodes.list_item()。
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 bullet(self, match, context, next_state): """Bullet list item.""" bulletlist = nodes.bullet_list() (bulletlist.source, bulletlist.line) = self.state_machine.get_source_and_line() self.parent += bulletlist bulletlist['bullet'] = match.string[0] i, blank_finish = self.list_item(match.end()) bulletlist += i offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=bulletlist, initial_state='BulletList', blank_finish=blank_finish) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.unindent_warning('Bullet list') return [], next_state, []
def enumerator(self, match, context, next_state): """Enumerated list item.""" format, sequence, text, ordinal = self.parse_enumerator( match, self.parent['enumtype']) if ( format != self.format or (sequence != '#' and (sequence != self.parent['enumtype'] or self.auto or ordinal != (self.lastordinal + 1))) or not self.is_enumerated_list_item(ordinal, sequence, format)): # different enumeration: new list self.invalid_input() if sequence == '#': self.auto = 1 listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish self.lastordinal = ordinal return [], next_state, []
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 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 bullet(self, match, context, next_state): """Bullet list item.""" bulletlist = nodes.bullet_list() self.parent += bulletlist bulletlist['bullet'] = match.string[0] i, blank_finish = self.list_item(match.end()) bulletlist += i offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=bulletlist, initial_state='BulletList', blank_finish=blank_finish) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.unindent_warning('Bullet list') return [], next_state, []
def _toctree_prune(self, node, depth, maxdepth, collapse=False): """Utility: Cut a TOC at a specified depth.""" for subnode in node.children[:]: if isinstance(subnode, (addnodes.compact_paragraph, nodes.list_item)): # for <p> and <li>, just recurse self._toctree_prune(subnode, depth, maxdepth, collapse) elif isinstance(subnode, nodes.bullet_list): # for <ul>, determine if the depth is too large or if the # entry is to be collapsed if maxdepth > 0 and depth > maxdepth: subnode.parent.replace(subnode, []) else: # cull sub-entries whose parents aren't 'current' if (collapse and depth > 1 and 'iscurrent' not in subnode.parent): subnode.parent.remove(subnode) else: # recurse on visible children self._toctree_prune(subnode, depth+1, maxdepth, collapse)
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: code (' ' reason)? # 1: ' -- ' # 2+: description visitor = ParagraphVisitor(self.document) node[0].walkabout(visitor) tokens = visitor.get_paragraph().split() if tokens[0].startswith('['): # have a link, protect it code = tokens[0][1:] tokens[1] = '[' + tokens[1] else: code = tokens[0] idx = _find_param_separator(tokens) reason = ' '.join(tokens[1:idx]) description = ' '.join(tokens[idx+1:]) self.status_info[code] = {'reason': reason, 'description': description} raise nodes.SkipChildren
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 _build_notes(self, content): """Constructs a list of notes content for the support matrix. This is generated as a bullet list. """ notestitle = nodes.subtitle(text="Notes") notes = nodes.bullet_list() content.append(notestitle) content.append(notes) NOTES = [] for note in NOTES: item = nodes.list_item() item.append(nodes.strong(text=note)) notes.append(item)
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 _build_notes(self, content): """Constructs a list of notes content for the support matrix. This is generated as a bullet list. """ notestitle = nodes.subtitle(text="Notes") notes = nodes.bullet_list() content.append(notestitle) content.append(notes) NOTES = [ "Virtuozzo was formerly named Parallels in this document" ] for note in NOTES: item = nodes.list_item() item.append(nodes.strong(text=note)) notes.append(item)
def get_parameter_names(parameters_node): parameter_names = [] for list_item_node in find_by_path(parameters_node, [list_item]): title_ref_nodes = find_by_path( list_item_node, [paragraph, (title_reference, pending_xref)]) parameter_names.append(title_ref_nodes[0].astext()) return parameter_names
def depart_compact_paragraph(self, node): if isinstance(node.parent, nodes.list_item): self.add_text(self.nl)
def visit_paragraph(self, node): if not isinstance(node.parent, ( nodes.Admonition, nodes.citation, nodes.entry, nodes.footnote, nodes.list_item, addnodes.seealso, )): self.new_state(0)
def depart_paragraph(self, node): if isinstance(node.parent, nodes.list_item): self.add_text(self.nl) elif not isinstance(node.parent, ( nodes.Admonition, nodes.citation, nodes.entry, nodes.footnote, addnodes.seealso, )): self.end_state()
def patched_make_field(self, types, domain, items, **kw): # `kw` catches `env=None` needed for newer sphinx while maintaining # backwards compatibility when passed along further down! # type: (List, unicode, Tuple) -> nodes.field def handle_item(fieldarg, content): par = nodes.paragraph() par += addnodes.literal_strong('', fieldarg) # Patch: this line added # par.extend(self.make_xrefs(self.rolename, domain, fieldarg, # addnodes.literal_strong)) if fieldarg in types: par += nodes.Text(' (') # NOTE: using .pop() here to prevent a single type node to be # inserted twice into the doctree, which leads to # inconsistencies later when references are resolved fieldtype = types.pop(fieldarg) if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text): typename = u''.join(n.astext() for n in fieldtype) typename = typename.replace('int', 'python:int') typename = typename.replace('long', 'python:long') typename = typename.replace('float', 'python:float') typename = typename.replace('type', 'python:type') par.extend(self.make_xrefs(self.typerolename, domain, typename, addnodes.literal_emphasis, **kw)) else: par += fieldtype par += nodes.Text(')') par += nodes.Text(' -- ') par += content return par fieldname = nodes.field_name('', self.label) if len(items) == 1 and self.can_collapse: fieldarg, content = items[0] bodynode = handle_item(fieldarg, content) else: bodynode = self.list_type() for fieldarg, content in items: bodynode += nodes.list_item('', handle_item(fieldarg, content)) fieldbody = nodes.field_body('', bodynode) return nodes.field('', fieldname, fieldbody)
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 []
def depart_paragraph(self, node): self.body.append('</p>') if not (isinstance(node.parent, (nodes.list_item, nodes.entry)) and (len(node.parent) == 1)): self.body.append('\n')
def list_item(self, indent): if self.state_machine.line[indent:]: indented, line_offset, blank_finish = ( self.state_machine.get_known_indented(indent)) else: indented, indent, line_offset, blank_finish = ( self.state_machine.get_first_known_indented(indent)) listitem = nodes.list_item('\n'.join(indented)) if indented: self.nested_parse(indented, input_offset=line_offset, node=listitem) return listitem, blank_finish
def bullet(self, match, context, next_state): """Bullet list item.""" if match.string[0] != self.parent['bullet']: # different bullet: new list self.invalid_input() listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish return [], next_state, []
def _append_dbapi_bullet(self, dialect_name, dbapi_name, name, idname): env = self.state.document.settings.env dialect_directive = self._dialects[dialect_name] try: relative_uri = env.app.builder.get_relative_uri( dialect_directive.docname, self.docname) except: relative_uri = "" list_node = nodes.list_item( '', nodes.paragraph( '', '', nodes.reference( '', '', nodes.Text(name, name), refdocname=self.docname, refuri=relative_uri + "#" + idname ), #nodes.Text(" ", " "), #nodes.reference('', '', # nodes.Text("(connectstring)", "(connectstring)"), # refdocname=self.docname, # refuri=env.app.builder.get_relative_uri( # dialect_directive.docname, self.docname) + ## "#" + ("dialect-%s-%s-connect" % # (dialect_name, dbapi_name)) # ) ) ) dialect_directive.bullets.append(list_node)
def run(self): content = _parse_content(self.content) env = self.state.document.settings.env self.docname = env.docname sourcefile = self.state.document.current_source.split(os.pathsep)[0] dir_ = os.path.dirname(sourcefile) files = [ f for f in os.listdir(dir_) if f.endswith(".py") and f != "__init__.py" ] if "files" in content: # ordered listing of files to include files = [ fname for fname in _comma_list(content["files"]) if fname in set(files)] node = nodes.paragraph( '', '', nodes.Text("Listing of files:", "Listing of files:") ) bullets = nodes.bullet_list() for fname in files: modname, ext = os.path.splitext(fname) # relative lookup modname = "." + modname link = _view_source_node(env, modname, self.state) if link is not None: list_node = nodes.list_item( '', link ) bullets += list_node node += bullets return [node]
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 patched_make_field(self, types, domain, items, **kw): # `kw` catches `env=None` needed for newer sphinx while maingaining # backwards compatibility when passed along further down! # type: (List, unicode, Tuple) -> nodes.field def handle_item(fieldarg, content): par = nodes.paragraph() par += addnodes.literal_strong('', fieldarg) # Patch: this line added # par.extend(self.make_xrefs(self.rolename, domain, fieldarg, # addnodes.literal_strong)) if fieldarg in types: par += nodes.Text(' (') # NOTE: using .pop() here to prevent a single type node to be # inserted twice into the doctree, which leads to # inconsistencies later when references are resolved fieldtype = types.pop(fieldarg) if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text): typename = u''.join(n.astext() for n in fieldtype) typename = typename.replace('int', 'python:int') typename = typename.replace('long', 'python:long') typename = typename.replace('float', 'python:float') typename = typename.replace('type', 'python:type') par.extend(self.make_xrefs(self.typerolename, domain, typename, addnodes.literal_emphasis, **kw)) else: par += fieldtype par += nodes.Text(')') par += nodes.Text(' -- ') par += content return par fieldname = nodes.field_name('', self.label) if len(items) == 1 and self.can_collapse: fieldarg, content = items[0] bodynode = handle_item(fieldarg, content) else: bodynode = self.list_type() for fieldarg, content in items: bodynode += nodes.list_item('', handle_item(fieldarg, content)) fieldbody = nodes.field_body('', bodynode) return nodes.field('', fieldname, fieldbody)
def enumerator(self, match, context, next_state): """Enumerated List Item""" format, sequence, text, ordinal = self.parse_enumerator(match) if not self.is_enumerated_list_item(ordinal, sequence, format): raise statemachine.TransitionCorrection('text') enumlist = nodes.enumerated_list() self.parent += enumlist if sequence == '#': enumlist['enumtype'] = 'arabic' else: enumlist['enumtype'] = sequence enumlist['prefix'] = self.enum.formatinfo[format].prefix enumlist['suffix'] = self.enum.formatinfo[format].suffix if ordinal != 1: enumlist['start'] = ordinal msg = self.reporter.info( 'Enumerated list start value not ordinal-1: "%s" (ordinal %s)' % (text, ordinal)) self.parent += msg listitem, blank_finish = self.list_item(match.end()) enumlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=enumlist, initial_state='EnumeratedList', blank_finish=blank_finish, extra_settings={'lastordinal': ordinal, 'format': format, 'auto': sequence == '#'}) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Enumerated list') return [], next_state, []
def isdocnode(self, node): if not isinstance(node, nodes.list_item): return False if len(node.children) != 2: return False if not isinstance(node.children[0], addnodes.compact_paragraph): return False if not isinstance(node.children[0][0], nodes.reference): return False if not isinstance(node.children[1], nodes.bullet_list): return False return True
def write_toc(self, node, indentlevel=4): # XXX this should return a Unicode string, not a bytestring parts = [] if self.isdocnode(node): refnode = node.children[0][0] link = refnode['refuri'] title = htmlescape(refnode.astext()).replace('"', '"') item = '<section title="%(title)s" ref="%(ref)s">' % \ {'title': title, 'ref': link} parts.append(' '*4*indentlevel + item) for subnode in node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append(' '*4*indentlevel + '</section>') elif isinstance(node, nodes.list_item): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, nodes.reference): link = node['refuri'] title = htmlescape(node.astext()).replace('"', '"') item = section_template % {'title': title, 'ref': link} item = u' ' * 4 * indentlevel + item parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif isinstance(node, nodes.bullet_list): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, addnodes.compact_paragraph): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) return parts