• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python addnodes.compact_paragraph函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sphinx.addnodes.compact_paragraph函数的典型用法代码示例。如果您正苦于以下问题:Python compact_paragraph函数的具体用法?Python compact_paragraph怎么用?Python compact_paragraph使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了compact_paragraph函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: extract_toc

def extract_toc(fulltoc, selectors):
    entries = []

    def matches(ref, selector):
        if selector.endswith('/*'):
            return ref.rsplit('/', 1)[0] == selector[:-2]
        return ref == selector

    for refnode in fulltoc.traverse(nodes.reference):
        container = refnode.parent.parent
        if any(
            cls[:4] == 'ref-' and any(
                matches(cls[4:], s) for s in selectors
            )
            for cls in container['classes']
        ):
            parent = container.parent

            new_parent = parent.deepcopy()
            del new_parent.children[:]
            new_parent += container
            entries.append(new_parent)

            parent.remove(container)
            if not parent.children:
                parent.parent.remove(parent)

    newnode = addnodes.compact_paragraph('', '')
    newnode.extend(entries)
    newnode['toctree'] = True

    return newnode
开发者ID:getsentry,项目名称:sentry-doc-support,代码行数:32,代码来源:sentryext.py


示例2: handle_signature

	def handle_signature(self, sig, signode):
		#synopsis = unicodedata.normalize('NFD', self.options.get('synopsis'))
		synopsis = self.options.get('synopsis')
		module = self.env.temp_data.get('nscp:module')
		fullname = 'TODO'
		if self.objtype == 'query':
			fullname = '%s.%s'%(module, sig)
			signode['fullname'] = fullname
			signode += addnodes.desc_addname(module, module)
			signode += addnodes.desc_name(sig, sig)
			signode += addnodes.desc_content('')
			signode += addnodes.compact_paragraph(synopsis, synopsis)
		elif self.objtype == 'option':
			command = self.env.temp_data.get('nscp:command')
			fullname = '%s.%s:%s'%(module, command, sig)
			signode['fullname'] = fullname
			ann = ' (%s, %s)'%(module, command)
			signode += addnodes.desc_name(sig, sig)
			signode += addnodes.desc_annotation(ann, ann)
		elif self.objtype == 'confpath':
			fullname = '%s:%s'%(module, sig)
			signode['fullname'] = fullname
			ann = ' (%s)'%(module)
			signode += addnodes.desc_name(sig, sig)
			signode += addnodes.desc_annotation(ann, ann)
		elif self.objtype == 'confkey':
			confpath = self.env.temp_data.get('nscp:confpath', '')
			fullname = '%s:%s:%s'%(module, confpath, sig)
			signode['fullname'] = fullname
			ann = ' (%s, %s)'%(module, confpath)
			signode += addnodes.desc_name(sig, sig)
			signode += addnodes.desc_annotation(ann, ann)
		#print 'handle_signature(%s, %s) => %s'%(sig, signode, fullname)
		return fullname, sig
开发者ID:Vilse1202,项目名称:nscp,代码行数:34,代码来源:nscp.py


示例3: run

    def run(self):
        self.assert_has_content()

        content = ''.join(self.content).strip()

        icon_classes = self.options.get('icon-classes', '')
        icon_classes = icon_classes.split(' ')

        container_classes = self.options.get('box-classes', '')
        container_classes = container_classes.split(' ')

        icons = span(classes=icon_classes)

        node = nodes.container(classes=container_classes)
        node.children.append(icons)

        parsed, _messages = self.state.inline_text(
            content, self.content_offset
        )
        parsed_ = parsed[0]
        for p in parsed[1:]:
            parsed_.children.append(p)

        cp = compact_paragraph('', '', parsed_)
        node.children.append(cp)

        return [node]
开发者ID:kyungmin,项目名称:balanced-docs,代码行数:27,代码来源:customizations.py


示例4: getArgsContent

def getArgsContent(Args):
  Container = desc('', desc_signature(text='Args'), objtype="Args")

  for name, Arg in Args.items():
    Content = desc_content()
    Content.append(desc_name(text='%s: ' % name))
    Content.append(compact_paragraph(text=getArgDesc(Arg)))
    Container.append(Content)

  return Container
开发者ID:Laufire,项目名称:eccontrib-sphinxdoc,代码行数:10,代码来源:sphinxdoc.py


示例5: build_toc

 def build_toc(node, depth=1):
     # type: (nodes.Element, int) -> nodes.bullet_list
     entries = []  # type: List[nodes.Element]
     for sectionnode in node:
         # find all toctree nodes in this section and add them
         # to the toc (just copying the toctree node which is then
         # resolved in self.get_and_resolve_doctree)
         if isinstance(sectionnode, nodes.section):
             title = sectionnode[0]
             # copy the contents of the section title, but without references
             # and unnecessary stuff
             visitor = SphinxContentsFilter(doctree)
             title.walkabout(visitor)
             nodetext = visitor.get_entry_text()
             if not numentries[0]:
                 # for the very first toc entry, don't add an anchor
                 # as it is the file's title anyway
                 anchorname = ''
             else:
                 anchorname = '#' + sectionnode['ids'][0]
             numentries[0] += 1
             # make these nodes:
             # list_item -> compact_paragraph -> reference
             reference = nodes.reference(
                 '', '', internal=True, refuri=docname,
                 anchorname=anchorname, *nodetext)
             para = addnodes.compact_paragraph('', '', reference)
             item = nodes.list_item('', para)  # type: nodes.Element
             sub_item = build_toc(sectionnode, depth + 1)
             if sub_item:
                 item += sub_item
             entries.append(item)
         elif isinstance(sectionnode, addnodes.only):
             onlynode = addnodes.only(expr=sectionnode['expr'])
             blist = build_toc(sectionnode, depth)
             if blist:
                 onlynode += blist.children
                 entries.append(onlynode)
         elif isinstance(sectionnode, nodes.Element):
             for toctreenode in traverse_in_section(sectionnode,
                                                    addnodes.toctree):
                 item = toctreenode.copy()
                 entries.append(item)
                 # important: do the inventory stuff
                 TocTree(app.env).note(docname, toctreenode)
     if entries:
         return nodes.bullet_list('', *entries)
     return None
开发者ID:olivier-heurtier,项目名称:sphinx,代码行数:48,代码来源:toctree.py


示例6: build_toc

    def build_toc(node, depth=1, main=False, title_visited=False):
      entries = []
      for sectionnode in node:
# EV: added or condition on 'main' and 'title_visited'
        # find all toctree nodes in this section and add them
        # to the toc (just copying the toctree node which is then
        # resolved in self.get_and_resolve_doctree)
        if isinstance(sectionnode, addnodes.only):
          onlynode = addnodes.only(expr=sectionnode['expr'])
          blist = build_toc(sectionnode, depth)
          if blist:
            onlynode += blist.children
            entries.append(onlynode)
        if not isinstance(sectionnode, nodes.section) or (main and title_visited):
          for toctreenode in traverse_in_section(sectionnode,
                                                 addnodes.toctree):
            item = toctreenode.copy()
            entries.append(item)
            # important: do the inventory stuff
            self.note_toctree(docname, toctreenode)
          continue
        title = sectionnode[0]
        # copy the contents of the section title, but without references
        # and unnecessary stuff
        visitor = SphinxContentsFilter(document)
        title.walkabout(visitor)
        nodetext = visitor.get_entry_text()
        if not numentries[0]:
          # for the very first toc entry, don't add an anchor
          # as it is the file's title anyway
          anchorname = ''
        else:
          anchorname = '#' + sectionnode['ids'][0]
        numentries[0] += 1
        reference = nodes.reference(
          '', '', internal=True, refuri=docname,
          anchorname=anchorname, *nodetext)
        para = addnodes.compact_paragraph('', '', reference)
        item = nodes.list_item('', para)
        if maxdepth == 0 or depth < maxdepth:
# EV: set 'main' and 'title_visited' args
          item += build_toc(sectionnode, depth+1, main=main, title_visited=True)
        entries.append(item)
      if entries:
        return nodes.bullet_list('', *entries)
      return []
开发者ID:baohaojun,项目名称:eclim,代码行数:46,代码来源:environment.py


示例7: sub

 def sub(title, lst):
     if not lst:
         return None
     item, res, tmp = nodes.list_item(), addnodes.compact_paragraph(), []
     res += nodes.strong(text=(title + ': '))
     kwargs = {
         'refdomain': 'cpp',
         'refexplicit': False,
         'reftype': 'class',
     }
     for it in lst:
         kwargs['reftarget'] = unicode(it.name)
         node = addnodes.pending_xref('', **kwargs)
         node += nodes.literal(text=it.name)
         tmp.extend([node, nodes.Text(', ')])
     res.extend(tmp[:-1])
     item += res
     return item
开发者ID:aldebaran,项目名称:doc-tools,代码行数:18,代码来源:__init__.py


示例8: _build_toc_node

def _build_toc_node(docname, anchor="anchor", text="test text", bullet=False):
    """
    Create the node structure that Sphinx expects for TOC Tree entries.

    The ``bullet`` argument wraps it in a ``nodes.bullet_list``,
    which is how you nest TOC Tree entries.
    """
    reference = nodes.reference(
        "",
        "",
        internal=True,
        refuri=docname,
        anchorname="#" + anchor,
        *[nodes.Text(text, text)]
    )
    para = addnodes.compact_paragraph("", "", reference)
    ret_list = nodes.list_item("", para)
    return nodes.bullet_list("", ret_list) if bullet else ret_list
开发者ID:rtfd,项目名称:sphinx-autoapi,代码行数:18,代码来源:toctree.py


示例9: run

 def run(self):
     populated = CPPAutoDocObject._populate(self)
     self.name = 'function'
     res, obj = CPPFunctionObject.run(self), self._get_obj()
     if populated:
         fieldlist, _empty = nodes.field_list(), True
         doc_args = [it for it in obj.signature
                     if obj.brief('param_' + str(it.get_name()))]
         if doc_args:
             tmp = []
             for it in doc_args:
                 param_name = 'param_' + str(it.get_name())
                 node = addnodes.compact_paragraph()
                 if obj.param_ways.get(param_name, None) is not None:
                     node += nodes.literal(text='[{}] '.format(
                         obj.param_ways[param_name]
                     ))
                 node += nodes.Text(obj.brief(param_name)[0])
                 tmp.append((it.name, node))
             fieldlist += self.doc_field_types[0].make_field(
                 [], # [it.type for it in doc_args],
                 self._get_domain(),
                 tmp,
             )
             _empty = False
         def _simple_field(fieldlist, name, nb_):
             if obj.brief(name):
                 fieldlist += self.doc_field_types[nb_].make_field(
                     None, self._get_domain(),
                     (None, [nodes.Text(it) for it in obj.brief(name)])
                 )
                 return False
             return True
         _empty =_simple_field(fieldlist, 'return', 1) and _empty
         _empty = _simple_field(fieldlist, 'pre', 3) and _empty
         _empty = _simple_field(fieldlist, 'post', 4) and _empty
         if not _empty:
             res[1][1].insert(0, fieldlist)
         if obj.details() and not _empty:
             para = nodes.paragraph()
             para += nodes.emphasis(text='Brief: ')
             para += nodes.Text(''.join(obj.brief()))
             res[1][1].insert(0, para)
     return res
开发者ID:aldebaran,项目名称:doc-tools,代码行数:44,代码来源:__init__.py


示例10: get_navtree

def get_navtree(app, pagename, collapse=True, **kwargs):

    shift_toc = app.config.navtree_shift
    root_links = app.config.navtree_root_links
    maxdepth = app.config.navtree_maxdepth
    try:
        maxdepth.setdefault('default', kwargs.pop('maxdepth', MAXDEPTH_DEFAULT))
    except AttributeError:
        maxdepth = {'default': maxdepth}

    toctree = app.env.get_toctree_for(pagename, app.builder, collapse=False, **kwargs)
    navtree = addnodes.compact_paragraph()
    navtree['toctree'] = True

    for bullet_list, caption in iter_toctree(toctree):
        process_toctree_list(navtree, bullet_list, caption, app,
                             collapse, maxdepth, shift_toc, root_links)

    if shift_toc:
        update_navtree_classes(navtree)

    return app.builder.render_partial(navtree)['fragment']
开发者ID:bintoro,项目名称:sphinx-navtree,代码行数:22,代码来源:main.py


示例11: extract_toc

def extract_toc(fulltoc, selectors):
    entries = []

    for refnode in fulltoc.traverse(nodes.reference):
        container = refnode.parent.parent
        if any(cls[:4] == 'ref-' and cls[4:] in selectors
               for cls in container['classes']):
            parent = container.parent

            new_parent = parent.deepcopy()
            del new_parent.children[:]
            new_parent += container
            entries.append(new_parent)

            parent.remove(container)
            if not parent.children:
                parent.parent.remove(parent)

    newnode = addnodes.compact_paragraph('', '')
    newnode.extend(entries)
    newnode['toctree'] = True

    return newnode
开发者ID:SLusenti,项目名称:origin,代码行数:23,代码来源:sentryext.py


示例12: apply

    def apply(self):
        env = self.document.settings.env
        if env.config.html_compact_lists:
            return

        def check_refonly_list(node):
            """Check for list with only references in it."""
            visitor = RefOnlyListChecker(self.document)
            try:
                node.walk(visitor)
            except nodes.NodeFound:
                return False
            else:
                return True

        for node in self.document.traverse(nodes.bullet_list):
            if check_refonly_list(node):
                for item in node.traverse(nodes.list_item):
                    para = item[0]
                    ref = para[0]
                    compact_para = addnodes.compact_paragraph()
                    compact_para += ref
                    item.replace(para, compact_para)
开发者ID:TimKam,项目名称:sphinx,代码行数:23,代码来源:compact_bullet_list.py


示例13: build_toc

 def build_toc(node):
     entries = []
     for subnode in node:
         if isinstance(subnode, addnodes.toctree):
             # just copy the toctree node which is then resolved
             # in self.get_and_resolve_doctree
             item = subnode.copy()
             entries.append(item)
             # do the inventory stuff
             self.note_toctree(docname, subnode)
             continue
         if not isinstance(subnode, nodes.section):
             continue
         title = subnode[0]
         # copy the contents of the section title, but without references
         # and unnecessary stuff
         visitor = SphinxContentsFilter(document)
         title.walkabout(visitor)
         nodetext = visitor.get_entry_text()
         if not numentries[0]:
             # for the very first toc entry, don't add an anchor
             # as it is the file's title anyway
             anchorname = ''
         else:
             anchorname = '#' + subnode['ids'][0]
         numentries[0] += 1
         reference = nodes.reference('', '', refuri=docname,
                                     anchorname=anchorname,
                                     *nodetext)
         para = addnodes.compact_paragraph('', '', reference)
         item = nodes.list_item('', para)
         item += build_toc(subnode)
         entries.append(item)
     if entries:
         return nodes.bullet_list('', *entries)
     return []
开发者ID:lshmenor,项目名称:IMTAphy,代码行数:36,代码来源:environment.py


示例14: apply

    def apply(self, **kwargs):
        # type: (Any) -> None
        if self.config.html_compact_lists:
            return

        def check_refonly_list(node):
            # type: (nodes.Node) -> bool
            """Check for list with only references in it."""
            visitor = RefOnlyListChecker(self.document)
            try:
                node.walk(visitor)
            except nodes.NodeFound:
                return False
            else:
                return True

        for node in self.document.traverse(nodes.bullet_list):
            if check_refonly_list(node):
                for item in node.traverse(nodes.list_item):
                    para = cast(nodes.paragraph, item[0])
                    ref = cast(nodes.reference, para[0])
                    compact_para = addnodes.compact_paragraph()
                    compact_para += ref
                    item.replace(para, compact_para)
开发者ID:olivier-heurtier,项目名称:sphinx,代码行数:24,代码来源:compact_bullet_list.py


示例15: __init__

 def __init__(self, *args, **kwargs):
   StandaloneHTMLBuilder.__init__(self, *args, **kwargs)
   self.toctrees = {}
   self.index_node = nodes.list_item('', addnodes.compact_paragraph(''))
开发者ID:DamienCassou,项目名称:eclim,代码行数:4,代码来源:builder.py


示例16: _entries_from_toctree

 def _entries_from_toctree(toctreenode, parents,
                           separate=False, subtree=False):
     """Return TOC entries for a toctree node."""
     refs = [(e[0], e[1]) for e in toctreenode['entries']]
     entries = []
     for (title, ref) in refs:
         try:
             refdoc = None
             if url_re.match(ref):
                 if title is None:
                     title = ref
                 reference = nodes.reference('', '', internal=False,
                                             refuri=ref, anchorname='',
                                             *[nodes.Text(title)])
                 para = addnodes.compact_paragraph('', '', reference)
                 item = nodes.list_item('', para)
                 toc = nodes.bullet_list('', item)
             elif ref == 'self':
                 # 'self' refers to the document from which this
                 # toctree originates
                 ref = toctreenode['parent']
                 if not title:
                     title = clean_astext(self.titles[ref])
                 reference = nodes.reference('', '', internal=True,
                                             refuri=ref,
                                             anchorname='',
                                             *[nodes.Text(title)])
                 para = addnodes.compact_paragraph('', '', reference)
                 item = nodes.list_item('', para)
                 # don't show subitems
                 toc = nodes.bullet_list('', item)
             else:
                 if ref in parents:
                     self.env.warn(ref, 'circular toctree references '
                                   'detected, ignoring: %s <- %s' %
                                   (ref, ' <- '.join(parents)))
                     continue
                 refdoc = ref
                 toc = self.tocs[ref].deepcopy()
                 maxdepth = self.env.metadata[ref].get('tocdepth', 0)
                 if ref not in toctree_ancestors or (prune and maxdepth > 0):
                     self._toctree_prune(toc, 2, maxdepth, collapse)
                 process_only_nodes(toc, builder.tags, warn_node=self.env.warn_node)
                 if title and toc.children and len(toc.children) == 1:
                     child = toc.children[0]
                     for refnode in child.traverse(nodes.reference):
                         if refnode['refuri'] == ref and \
                            not refnode['anchorname']:
                             refnode.children = [nodes.Text(title)]
             if not toc.children:
                 # empty toc means: no titles will show up in the toctree
                 self.env.warn_node(
                     'toctree contains reference to document %r that '
                     'doesn\'t have a title: no link will be generated'
                     % ref, toctreenode)
         except KeyError:
             # this is raised if the included file does not exist
             self.env.warn_node(
                 'toctree contains reference to nonexisting document %r'
                 % ref, toctreenode)
         else:
             # if titles_only is given, only keep the main title and
             # sub-toctrees
             if titles_only:
                 # delete everything but the toplevel title(s)
                 # and toctrees
                 for toplevel in toc:
                     # nodes with length 1 don't have any children anyway
                     if len(toplevel) > 1:
                         subtrees = toplevel.traverse(addnodes.toctree)
                         if subtrees:
                             toplevel[1][:] = subtrees
                         else:
                             toplevel.pop(1)
             # resolve all sub-toctrees
             for subtocnode in toc.traverse(addnodes.toctree):
                 if not (subtocnode.get('hidden', False) and
                         not includehidden):
                     i = subtocnode.parent.index(subtocnode) + 1
                     for item in _entries_from_toctree(
                             subtocnode, [refdoc] + parents,
                             subtree=True):
                         subtocnode.parent.insert(i, item)
                         i += 1
                     subtocnode.parent.remove(subtocnode)
             if separate:
                 entries.append(toc)
             else:
                 entries.extend(toc.children)
     if not subtree and not separate:
         ret = nodes.bullet_list()
         ret += entries
         return [ret]
     return entries
开发者ID:JelteF,项目名称:sphinx,代码行数:94,代码来源:toctree.py


示例17: resolve_toctree

    def resolve_toctree(self, docname, builder, toctree, prune=True, maxdepth=0,
                        titles_only=False, collapse=False, includehidden=False):
        # type: (unicode, Builder, addnodes.toctree, bool, int, bool, bool, bool) -> nodes.Node
        """Resolve a *toctree* node into individual bullet lists with titles
        as items, returning None (if no containing titles are found) or
        a new node.

        If *prune* is True, the tree is pruned to *maxdepth*, or if that is 0,
        to the value of the *maxdepth* option on the *toctree* node.
        If *titles_only* is True, only toplevel document titles will be in the
        resulting tree.
        If *collapse* is True, all branches not containing docname will
        be collapsed.
        """
        if toctree.get('hidden', False) and not includehidden:
            return None

        # For reading the following two helper function, it is useful to keep
        # in mind the node structure of a toctree (using HTML-like node names
        # for brevity):
        #
        # <ul>
        #   <li>
        #     <p><a></p>
        #     <p><a></p>
        #     ...
        #     <ul>
        #       ...
        #     </ul>
        #   </li>
        # </ul>
        #
        # The transformation is made in two passes in order to avoid
        # interactions between marking and pruning the tree (see bug #1046).

        toctree_ancestors = self.get_toctree_ancestors(docname)

        def _toctree_add_classes(node, depth):
            """Add 'toctree-l%d' and 'current' classes to the toctree."""
            for subnode in node.children:
                if isinstance(subnode, (addnodes.compact_paragraph,
                                        nodes.list_item)):
                    # for <p> and <li>, indicate the depth level and recurse
                    subnode['classes'].append('toctree-l%d' % (depth-1))
                    _toctree_add_classes(subnode, depth)
                elif isinstance(subnode, nodes.bullet_list):
                    # for <ul>, just recurse
                    _toctree_add_classes(subnode, depth+1)
                elif isinstance(subnode, nodes.reference):
                    # for <a>, identify which entries point to the current
                    # document and therefore may not be collapsed
                    if subnode['refuri'] == docname:
                        if not subnode['anchorname']:
                            # give the whole branch a 'current' class
                            # (useful for styling it differently)
                            branchnode = subnode
                            while branchnode:
                                branchnode['classes'].append('current')
                                branchnode = branchnode.parent
                        # mark the list_item as "on current page"
                        if subnode.parent.parent.get('iscurrent'):
                            # but only if it's not already done
                            return
                        while subnode:
                            subnode['iscurrent'] = True
                            subnode = subnode.parent

        def _entries_from_toctree(toctreenode, parents,
                                  separate=False, subtree=False):
            """Return TOC entries for a toctree node."""
            refs = [(e[0], e[1]) for e in toctreenode['entries']]
            entries = []
            for (title, ref) in refs:
                try:
                    refdoc = None
                    if url_re.match(ref):
                        if title is None:
                            title = ref
                        reference = nodes.reference('', '', internal=False,
                                                    refuri=ref, anchorname='',
                                                    *[nodes.Text(title)])
                        para = addnodes.compact_paragraph('', '', reference)
                        item = nodes.list_item('', para)
                        toc = nodes.bullet_list('', item)
                    elif ref == 'self':
                        # 'self' refers to the document from which this
                        # toctree originates
                        ref = toctreenode['parent']
                        if not title:
                            title = clean_astext(self.titles[ref])
                        reference = nodes.reference('', '', internal=True,
                                                    refuri=ref,
                                                    anchorname='',
                                                    *[nodes.Text(title)])
                        para = addnodes.compact_paragraph('', '', reference)
                        item = nodes.list_item('', para)
                        # don't show subitems
                        toc = nodes.bullet_list('', item)
                    else:
                        if ref in parents:
#.........这里部分代码省略.........
开发者ID:JelteF,项目名称:sphinx,代码行数:101,代码来源:toctree.py


示例18: my_resolve_toctree

def my_resolve_toctree(self, docname, builder, toctree, prune=True, maxdepth=0,
                       titles_only=False, collapse=False, includehidden=False):
    """alter 'sphinx.environment.BuildEnvironment.resolve_toctree'.

    Very long copied function but only to replace one str() with unicode() :-(

    Note: Difference of this function between 1.0.7 and 1.1pre is only 1 line.
          search to see "added 1.1".

    Original description is following:
    Resolve a *toctree* node into individual bullet lists with titles
    as items, returning None (if no containing titles are found) or
    a new node.

    If *prune* is True, the tree is pruned to *maxdepth*, or if that is 0,
    to the value of the *maxdepth* option on the *toctree* node.
    If *titles_only* is True, only toplevel document titles will be in the
    resulting tree.
    If *collapse* is True, all branches not containing docname will
    be collapsed.
    """
    if toctree.get('hidden', False) and not includehidden:
        return None

    def _walk_depth(node, depth, maxdepth):
        """Utility: Cut a TOC at a specified depth."""

        # For reading this function, it is useful to keep in mind the node
        # structure of a toctree (using HTML-like node names for brevity):
        #
        # <ul>
        #   <li>
        #     <p><a></p>
        #     <p><a></p>
        #     ...
        #     <ul>
        #       ...
        #     </ul>
        #   </li>
        # </ul>

        for subnode in node.children[:]:
            if isinstance(subnode, (addnodes.compact_paragraph,
                                    nodes.list_item)):
                # for <p> and <li>, just indicate the depth level and
                # recurse to children
                subnode['classes'].append('toctree-l%d' % (depth-1))
                _walk_depth(subnode, depth, maxdepth)

            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:
                    # to find out what to collapse, *first* walk subitems,
                    # since that determines which children point to the
                    # current page
                    _walk_depth(subnode, depth+1, maxdepth)
                    # cull sub-entries whose parents aren't 'current'
                    if (collapse and depth > 1 and
                        'iscurrent' not in subnode.parent):
                        subnode.parent.remove(subnode)

            elif isinstance(subnode, nodes.reference):
                # for <a>, identify which entries point to the current
                # document and therefore may not be collapsed
                if subnode['refuri'] == docname:
                    if not subnode['anchorname']:
                        # give the whole branch a 'current' class
                        # (useful for styling it differently)
                        branchnode = subnode
                        while branchnode:
                            branchnode['classes'].append('current')
                            branchnode = branchnode.parent
                    # mark the list_item as "on current page"
                    if subnode.parent.parent.get('iscurrent'):
                        # but only if it's not already done
                        return
                    while subnode:
                        subnode['iscurrent'] = True
                        subnode = subnode.parent

    def _entries_from_toctree(toctreenode, separate=False, subtree=False):
        """Return TOC entries for a toctree node."""
        refs = [(e[0], to_unicode(e[1])) for e in toctreenode['entries']]
        entries = []
        for (title, ref) in refs:
            try:
                if url_re.match(ref):
                    reference = nodes.reference('', '', internal=False,
                                                refuri=ref, anchorname='',
                                                *[nodes.Text(title)])
                    para = addnodes.compact_paragraph('', '', reference)
                    item = nodes.list_item('', para)
                    toc = nodes.bullet_list('', item)
                elif ref == 'self':
                    # 'self' refers to the document from which this
                    # toctree originates
                    ref = toctreenode['parent']
#.........这里部分代码省略.........
开发者ID:tkzwtks,项目名称:zaffy,代码行数:101,代码来源:unicode_ids.py


示例19: _entries_from_toctree

 def _entries_from_toctree(toctreenode, separate=False, subtree=False):
     """Return TOC entries for a toctree node."""
     refs = [(e[0], to_unicode(e[1])) for e in toctreenode['entries']]
     entries = []
     for (title, ref) in refs:
         try:
             if url_re.match(ref):
                 reference = nodes.reference('', '', internal=False,
                                             refuri=ref, anchorname='',
                                             *[nodes.Text(title)])
                 para = addnodes.compact_paragraph('', '', reference)
                 item = nodes.list_item('', para)
                 toc = nodes.bullet_list('', item)
             elif ref == 'self':
                 # 'self' refers to the document from which this
                 # toctree originates
                 ref = toctreenode['parent']
                 if not title:
                     title = clean_astext(self.titles[ref])
                 reference = nodes.reference('', '', internal=True,
                                             refuri=ref,
                                             anchorname='',
                                             *[nodes.Text(title)])
                 para = addnodes.compact_paragraph('', '', reference)
                 item = nodes.list_item('', para)
                 # don't show subitems
                 toc = nodes.bullet_list('', item)
             else:
                 toc = self.tocs[ref].deepcopy()
                 self.process_only_nodes(toc, builder, ref) # added 1.1
                 if title and toc.children and len(toc.children) == 1:
                     child = toc.children[0]
                     for refnode in child.traverse(nodes.reference):
                         if refnode['refuri'] == ref and \
                                not refnode['anchorname']:
                             refnode.children = [nodes.Text(title)]
             if not toc.children:
                 # empty toc means: no titles will show up in the toctree
                 self.warn(docname,
                           'toctree contains reference to document '
                           '%r that doesn\'t have a title: no link '
                           'will be generated' % ref, toctreenode.line)
         except KeyError:
             # this is raised if the included file does not exist
             self.warn(docname, 'toctree contains reference to '
                       'nonexisting document %r' % ref,
                       toctreenode.line)
         else:
             # if titles_only is given, only keep the main title and
             # sub-toctrees
             if titles_only:
                 # delete everything but the toplevel title(s)
                 # and toctrees
                 for toplevel in toc:
                     # nodes with length 1 don't have any children anyway
                     if len(toplevel) > 1:
                         subtrees = toplevel.traverse(addnodes.toctree)
                         toplevel[1][:] = subtrees
             # resolve all sub-toctrees
             for toctreenode in toc.traverse(addnodes.toctree):
                 i = toctreenode.parent.index(toctreenode) + 1
                 for item in _entries_from_toctree(toctreenode,
                                                   subtree=True):
                     toctreenode.parent.insert(i, item)
                     i += 1
                 toctreenode.parent.remove(toctreenode)
             if separate:
                 entries.append(toc)
             else:
                 entries.extend(toc.children)
     if not subtree and not separate:
         ret = nodes.bullet_list()
         ret += entries
         return [ret]
     return entries
开发者ID:tkzwtks,项目名称:zaffy,代码行数:75,代码来源:unicode_ids.py


示例20: new_resolve_toctree_v122

    def new_resolve_toctree_v122(self, docname, builder, toctree, prune=True, maxdepth=0,
                                 titles_only=False, collapse=False, includehidden=False):
        """Resolve a *toctree* node into individual bullet lists with titles
        as items, returning None (if no containing titles are found) or
        a new node.

        If *prune* is True, the tree is pruned to *maxdepth*, or if that is 0,
        to the value of the *maxdepth* option on the *toctree* node.
        If *titles_only* is True, only toplevel document titles will be in the
        resulting tree.
        If *collapse* is True, all branches not containing docname will
        be collapsed.
        """

        if toctree.get('hidden', False) and not includehidden:
            return None

        # photron: prepare reverse toctree lookup to avoid expaning the whole
        # tree every time. only expand the path to the current document
        if not hasattr(self, 'monkey_reverse_toctree'):
            self.monkey_reverse_toctree = self.monkey_get_reverse_toctree()
        # photron: end

        # For reading the following two helper function, it is useful to keep
        # in mind the node structure of a toctree (using HTML-like node names
        # for brevity):
        #
        # <ul>
        #   <li>
        #     <p><a></p>
        #     <p><a></p>
        #     ...
        #     <ul>
        #       ...
        #     </ul>
        #   </li>
        # </ul>
        #
        # The transformation is made in two passes in order to avoid
        # interactions between marking and pruning the tree (see bug #1046).

        def _toctree_prune_v122(node, depth, maxdepth):
            """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
                    _toctree_prune_v122(subnode, depth, maxdepth)
                elif isinstance(subnode, nodes.bullet_list):
                    # for <ul>, determine if the depth is too large or if the
                    # entry is to be collapsed
   

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python addnodes.desc函数代码示例发布时间:2022-05-27
下一篇:
Python sphinx.main函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap