示例#1
0
    def run(self):
        l = nodes.bullet_list('ul-name')
        for line in self.content:
            #print line

            path, rest = line.split(' ', 1)
            line_text = rest

            text_nodes, messages = self.state.inline_text(line_text,
                                                          self.lineno)
            line = nodes.line(line_text, '', *text_nodes)
            item = nodes.list_item(line_text, line)
            l.append(item)

            # Make the sub-list
            l2 = nodes.bullet_list('ul-name')
            for ext, title in [('.html', 'Normal text'),
                               ('-big.html', 'Presentation mode'),
                               #('-s5.html', 'Slide Show'),
                               ]:
                line_text = '`%s <%s%s>`__'%(title.strip(), path, ext)
                #print line_text

                text_nodes, messages = self.state.inline_text(line_text,
                                                              self.lineno)
                line = nodes.line(line_text, '', *text_nodes)
                #print type(line)
                item2 = nodes.list_item(line_text, line)

                l2.append(item2)

            item.append(l2)


        return [l, nodes.paragraph('hi')]
示例#2
0
    def _build_details(self, matrix, content):
        """Constructs the docutils content for the details of
        the support matrix.

        This is generated as a bullet list of features.
        Against each feature we provide the description of
        the feature and then the details of the hypervisor
        impls, with any driver specific notes that exist
        """

        detailstitle = nodes.subtitle(text="Details")
        details = nodes.bullet_list()

        content.append(detailstitle)
        content.append(details)

        # One list entry for each feature we're reporting on
        for feature in matrix.features:
            item = nodes.list_item()

            status = feature.status
            if feature.group is not None:
                status += "(" + feature.group + ")"

            # The hypervisor target name linked from summary table
            id = re.sub("[^a-zA-Z0-9_]", "_",
                        feature.key)

            # Highlight the feature title name
            item.append(nodes.strong(text=feature.title,
                                     ids=[id]))

            para = nodes.paragraph()
            para.append(nodes.strong(text="Status: " + status + ". "))
            if feature.notes is not None:
                para.append(nodes.inline(text=feature.notes))
            item.append(para)

            # A sub-list giving details of each hypervisor target
            impls = nodes.bullet_list()
            for key in feature.implementations:
                target = matrix.targets[key]
                impl = feature.implementations[key]
                subitem = nodes.list_item()

                id = re.sub("[^a-zA-Z0-9_]", "_",
                            feature.key + "_" + key)
                subitem += [
                    nodes.strong(text=target.title + ": "),
                    nodes.literal(text=impl.status,
                                  classes=["sp_impl_" + impl.status],
                                  ids=[id]),
                ]
                if impl.notes is not None:
                    subitem.append(nodes.paragraph(text=impl.notes))
                impls.append(subitem)

            item.append(impls)
            details.append(item)
示例#3
0
 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.maxsize)
     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 []
示例#4
0
    def make_content(self, all_members):
        ret = nodes.section()
        doc = self.item
        if doc.doc:
            self.directive.state.nested_parse(to_list(doc.doc), 0, ret)

        check_parameters(self, doc)

        params, subtypes = extract_subtypes(self.item.name, self.item)
        rdoc = doc.return_val.doc
        rtype = doc.return_val.type
        if params or rtype or rdoc:
            with addto(ret, nodes.field_list()) as fields:
                if params:
                    with addto(fields, nodes.field()) as field:
                        field += nodes.field_name('Parameters', 'Parameters')
                        with addto(field, nodes.field_body()) as body,\
                             addto(body, nodes.bullet_list()) as holder:
                            holder.extend(make_parameters(params, mod=doc['sourcemodule'].name))
                if rdoc:
                    with addto(fields, nodes.field()) as field:
                        field += nodes.field_name("Returns", "Returns")
                        with addto(field, nodes.field_body()) as body,\
                             addto(body, nodes.paragraph()) as p:
                            p += nodes.inline(rdoc, rdoc)
                if rtype:
                    with addto(fields, nodes.field()) as field:
                        field += nodes.field_name("Return Type", "Return Type")
                        with addto(field, nodes.field_body()) as body, \
                             addto(body, nodes.paragraph()) as p:
                            p += make_types(rtype, mod=doc['sourcemodule'].name)

        ret += self.document_subtypes(subtypes)

        return ret.children
示例#5
0
 def build_contents(self, node, level=0):
     level += 1
     sections = []
     i = len(node) - 1
     while i >= 0 and isinstance(node[i], nodes.section):
         sections.append(node[i])
         i -= 1
     sections.reverse()
     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['id'],
                                     *entrytext)
         ref_id = self.document.set_id(reference)
         entry = nodes.paragraph('', '', reference)
         item = nodes.list_item('', entry)
         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.set_class('auto-toc')
         return contents
     else:
         return []
示例#6
0
    def _add_feature_info(self, item, feature):
        para_info = nodes.paragraph()
        para_info.append(nodes.strong(text="info:"))
        info_list = nodes.bullet_list()

        maturity_literal = nodes.literal(text=feature.maturity,
                classes=["fm_maturity_" + feature.maturity])
        self._append_info_list_item(info_list,
                "Maturity", items=[maturity_literal])
        self._append_info_list_item(info_list,
                "API Docs", link=feature.api_doc_link)
        self._append_info_list_item(info_list,
                "Admin Docs", link=feature.admin_doc_link)

        tempest_items = []
        if feature.tempest_test_uuids:
            for uuid in feature.tempest_test_uuids.split(";"):
                base = "https://github.com/openstack/tempest/search?q=%s"
                link = base % uuid
                inline_ref = self._get_uri_ref(link, text=uuid)
                tempest_items.append(inline_ref)
                tempest_items.append(nodes.inline(text=", "))
            # removing trailing punctuation
            tempest_items = tempest_items[:-1]
        self._append_info_list_item(info_list,
                "Tempest tests", items=tempest_items)

        para_info.append(info_list)
        item.append(para_info)
示例#7
0
文件: rst_sphinx.py 项目: pv/pydocweb
def toctree_directive(dirname, arguments, options, content, lineno,
                      content_offset, block_text, state, state_machine):

    node = nodes.admonition()
    node['classes'] += ['admonition-toctree']
    node += nodes.title('', 'Toctree')

    para = nodes.paragraph('')
    node += para
    
    ul = nodes.bullet_list()
    para += ul
    
    for line in content:
        line = line.strip()
        if not line or line.startswith(':'): continue

        try:
            uri, name = resolve_name(line, state.inliner)
            title = name
            try:
                doc = models.Docstring.on_site.get(name=name)
                if doc.title:
                    title = doc.title
            except models.Docstring.DoesNotExist:
                pass
            entry = nodes.reference('', title, refuri=uri)
        except ValueError:
            entry = nodes.reference('', line, name=line,
                                    refname=':ref:`%s`' % line)

        ul += nodes.list_item('', nodes.paragraph('', '', entry))

    return [node]
示例#8
0
文件: wiki.py 项目: tkf/neorg
def gene_link_list(uri_list, bullet="*"):
    """
    Generate bullet list of uri from the list of uri

    >>> print gene_link_list(['a', 'b']).pformat()
    <bullet_list bullet="*">
        <list_item>
            <paragraph>
                <reference name="a" refuri="a">
                    a
                <target ids="a" names="a" refuri="a">
        <list_item>
            <paragraph>
                <reference name="b" refuri="b">
                    b
                <target ids="b" names="b" refuri="b">
    <BLANKLINE>

    """
    bullet_list = nodes.bullet_list(bullet=bullet)
    bullet_list += [
        nodes.list_item(
            '', with_children(nodes.paragraph, gene_link(l)))
        for l in uri_list]
    return bullet_list
示例#9
0
    def run(self):
        env = self.state.document.settings.env

        node = nodes.Element()
        node.document = self.state.document
        self.state.nested_parse(self.content, self.content_offset, node)

        entries = []
        for i, child in enumerate(node):
            if isinstance(child, nodes.literal_block):
                # add a title (the language name) before each block
                #targetid = "configuration-block-%d" % env.new_serialno('configuration-block')
                #targetnode = nodes.target('', '', ids=[targetid])
                #targetnode.append(child)
                if 'language' in child:
                    language = child['language']
                else:
                    language = env.app.config.highlight_language

                innernode = nodes.emphasis(self.formats[language], self.formats[language])

                para = nodes.paragraph()
                para += [innernode, child]

                entry = nodes.list_item('')
                entry.append(para)
                entries.append(entry)

        resultnode = configurationblock()
        resultnode.append(nodes.bullet_list('', *entries))

        return [resultnode]
示例#10
0
def process_latest_toc(app, doctree, fromdocname):
    """We traverse the doctree looking for publication dates to build the
    date-based ToC here. Since the ordering is ill-defined, from our
    perspective, we parse all of them each time, but cache them in the
    environment"""

    env = app.builder.env
    cache_article_dates(env)
        
    feed_pub_dates = getattr(env, 'feed_pub_dates', {})

    def is_blacklisted(docname):
        for blacklist_entry in app.config.feed_blacklist:
            if blacklist_entry in docname:
                return True
        return False
    
    for node in doctree.traverse(latest):
        entries = node['entries']
        includefiles = node['includefiles']
        
        decorated_entries = [
          (feed_pub_dates.get(doc), title, doc)
          for title, doc in entries
          if doc in feed_pub_dates]
        decorated_entries.sort(reverse=True)
        
        latest_list = nodes.bullet_list('')
        
        for date, title, docname in decorated_entries:
            if is_blacklisted(docname):
                continue
            para = nodes.paragraph()
            list_item = nodes.list_item('', para)
            
            if title is None:
                title = env.titles.get(docname)
                if title:
                    title = title[0] #.astext()

            # Create a reference
            newnode = nodes.reference('', '')

            # date
            stringdate = date.strftime('%Y-%m-%d') + ':'
            para += nodes.Text(stringdate, stringdate)
            para += nodes.Text(' ', ' ')

            # title and link
            innernode = title #nodes.emphasis(title, title)
            newnode['refdocname'] = docname
            newnode['refuri'] = app.builder.get_relative_uri(
                fromdocname, docname)
            newnode.append(innernode)
            para += newnode

            # Insert into the latestlist
            latest_list.append(list_item)

        node.replace_self(latest_list)
示例#11
0
    def run(self):
        env = self.state.document.settings.env
        config = env.config
        repodir = env.srcdir + '/' + config["git_repository_root"]

        doc_path = env.srcdir + '/' + env.docname + config["source_suffix"]

        if self.options.get('dir', False) == None:
            doc_path = '/'.join(doc_path.split('/')[:-1])

        repo = Repo(repodir)
        commits = repo.iter_commits(paths=doc_path)
        l = nodes.bullet_list()
        revisions_to_display = self.options.get('revisions', 10)

        for commit in list(commits)[:revisions_to_display]:
            date_str = datetime.fromtimestamp(commit.authored_date)
            if '\n' in commit.message:
                message, detailed_message = commit.message.split('\n', 1)
            else:
                message = commit.message
                detailed_message = None

            item = nodes.list_item()
            item += [
                nodes.strong(text=message),
                nodes.inline(text=" by "),
                nodes.emphasis(text=str(commit.author)),
                nodes.inline(text=" at "),
                nodes.emphasis(text=str(date_str))
            ]
            if detailed_message:
                item.append(nodes.caption(text=detailed_message.strip()))
            l.append(item)
        return [l]
    def test_assert_having_only(self):
        node = addnodes.Section()
        node.assert_having_only(addnodes.Action)
        node.assert_having_only((addnodes.Action, addnodes.Parameters))

        # standard nodes are ignored
        node += nodes.section()
        node += nodes.paragraph()
        node += nodes.bullet_list()
        node.assert_having_only(addnodes.Action)

        # success
        node += addnodes.Action()
        node.assert_having_only(addnodes.Action)

        node += addnodes.Parameters()
        node.assert_having_only((addnodes.Action, addnodes.Parameters))

        # failed
        with self.assertRaises(AssertionError):
            node.assert_having_only(addnodes.Action)

        # descendants are ignored
        node[0] += addnodes.Body()
        node.assert_having_only((addnodes.Action, addnodes.Parameters))
示例#13
0
    def render(self, app, doctree):
        rootnode = nodes.bullet_list()
        rootnode = nodes.paragraph()
        rootnode = nodes.definition_list()
        prepend = ""
        append = ""
        if self.scope == "global":
            prepend = "Global "
        if self.scope == "class":
            append = " (class %s)" % self.refname
        elif self.scope == "namespace":
            append = " (namespace %s)" % self.refname

        n = self.render_sub(app, doctree, self.namespaces,
                            prepend + "Namespaces" + append,
                            "namespace ")
        if n : rootnode.append(n)
        n = self.render_sub(app, doctree, self.classes,
                            prepend + "Classes" + append,
                            "class ")
        if n : rootnode.append(n)
        n = self.render_simple(app, doctree, self.functions,
                               prepend + "Functions"  + append,
                               "functions")
        if n : rootnode.append(n)
        n = self.render_simple(app, doctree, self.members,
                               prepend + "Members"  + append,
                               "members")
        if n : rootnode.append(n)
        n = self.render_simple(app, doctree, self.types,
                               prepend + "Types"  + append,
                               "types")
        if n : rootnode.append(n)
        return rootnode
    def test_assert_having_any(self):
        node = addnodes.Section()

        # standard nodes are ignored
        node += nodes.section()
        node += nodes.paragraph()
        node += nodes.bullet_list()
        node.assert_having_any(addnodes.Action)

        # success
        node.assert_having_any(addnodes.Action)  # no items

        node += addnodes.Action()
        node.assert_having_any(addnodes.Action)  # one item

        node += addnodes.Action()
        node.assert_having_any(addnodes.Action)  # two items

        # descendants are ignored
        node.pop()
        node[0] += addnodes.Action()
        node.assert_having_any(addnodes.Action)

        # other sections are ignored
        node[0] += addnodes.Parameters()
        node[0] += addnodes.Body()
        node.assert_having_any(addnodes.Action)
示例#15
0
def resolve_required_by_xrefs(app, env, node, contnode):
    """Now that all recipes and packages have been parsed, we are called here
    for each ``pending_xref`` node that sphinx has not been able to resolve.

    We handle specifically the ``requiredby`` reftype created by the
    `RequiredByField` fieldtype allowed in ``conda:package::``
    directives, where we replace the ``pending_ref`` node with a bullet
    list of reference nodes pointing to the package pages that
    "depended" on the package.
    """
    if node['reftype'] == 'requiredby' and node['refdomain'] == 'conda':
        target = node['reftarget']
        docname = node['refdoc']
        backrefs = env.domains['conda'].data['backrefs'].get(target, set())
        listnode = nodes.bullet_list()
        for back_docname, back_target in backrefs:
            par = nodes.paragraph()
            name_node = addnodes.literal_strong(back_target, back_target,
                                      classes=['xref', 'backref'])
            refnode = make_refnode(app.builder, docname,
                                   back_docname, back_target, name_node)
            refnode.set_class('conda-package')
            par += refnode
            listnode += nodes.list_item('', par)
        return listnode
示例#16
0
    def _build_markup(self, commits):
        list_node = nodes.bullet_list()
        for commit in commits:
            date_str = datetime.fromtimestamp(commit.authored_date)
            if '\n' in commit.message:
                message, detailed_message = commit.message.split('\n', 1)
            else:
                message = commit.message
                detailed_message = None

            item = nodes.list_item()
            item += [
                nodes.strong(text=message),
                nodes.inline(text=" by "),
                nodes.emphasis(text=six.text_type(commit.author)),
                nodes.inline(text=" at "),
                nodes.emphasis(text=str(date_str))
            ]
            if detailed_message:
                detailed_message = detailed_message.strip()
                if self.options.get('detailed-message-pre', False):
                    item.append(
                        nodes.literal_block(text=detailed_message))
                else:
                    item.append(nodes.paragraph(text=detailed_message))
            list_node.append(item)
        return [list_node]
示例#17
0
    def _output_resource(self, resource, parent, is_list):
        item = nodes.list_item()
        parent += item

        paragraph = nodes.paragraph()
        item += paragraph

        paragraph += parse_text(
            self,
            ':ref:`%s <%s>`' %
            (get_resource_title(resource, is_list, False),
             'webapi2.0-%s-resource' % get_resource_docname(resource, is_list)))

        bullet_list = nodes.bullet_list()
        item += bullet_list

        if is_list:
            if resource.uri_object_key:
                self._output_resource(resource, bullet_list, False)

            for child in resource.list_child_resources:
                self._output_resource(child, bullet_list, True)
        else:
            for child in resource.item_child_resources:
                self._output_resource(child, bullet_list, True)
示例#18
0
    def run(self):
        env = self.state.document.settings.env
        repo = Repo(env.srcdir)
        commits = repo.iter_commits()
        l = nodes.bullet_list()
        for commit in list(commits)[:10]:
            date_str = datetime.fromtimestamp(commit.authored_date)
            if '\n' in commit.message:
                message, detailed_message = commit.message.split('\n', 1)
            else:
                message = commit.message
                detailed_message = None

            item = nodes.list_item()
            item += [
                nodes.strong(text=message),
                nodes.inline(text=" by "),
                nodes.emphasis(text=str(commit.author)),
                nodes.inline(text=" at "),
                nodes.emphasis(text=str(date_str))
            ]
            if detailed_message:
                item.append(nodes.caption(text=detailed_message.strip()))
            l.append(item)
        return [l]
示例#19
0
    def _render_service(self, path, service, methods):
        env = self.state.document.settings.env
        service_id = "service-%d" % env.new_serialno('service')
        service_node = nodes.section(ids=[service_id])
        service_node += nodes.title(text='Service at %s' %
                                    service.route_name)

        if service.description is not None:
            service_node += rst2node(_dedent(service.description))

        for method, info in methods.items():
            method_id = '%s-%s' % (service_id, method)
            method_node = nodes.section(ids=[method_id])
            method_node += nodes.title(text=method)

            docstring = info['func'].__doc__ or ""

            if 'validator' in info:
                validators = to_list(info['validator'])
                for validator in validators:
                    if validator.__doc__ is not None:
                        if docstring is not None:
                            docstring += '\n' + validator.__doc__.strip()

            if 'accept' in info:
                accept = info['accept']

                if callable(accept):
                    if accept.__doc__ is not None:
                        docstring += accept.__doc__.strip()
                else:
                    accept = to_list(accept)

                    accept_node = nodes.strong(text='Accepted content types:')
                    node_accept_list = nodes.bullet_list()
                    accept_node += node_accept_list

                    for item in accept:
                        temp = nodes.list_item()
                        temp += nodes.inline(text=item)
                        node_accept_list += temp

                    method_node += accept_node

            node = rst2node(docstring)
            if node is not None:
                method_node += node

            renderer = info['renderer']
            if renderer == 'simplejson':
                renderer = 'json'

            response = nodes.paragraph()

            response += nodes.strong(text='Response: %s' % renderer)
            method_node += response

            service_node += method_node

        return service_node
示例#20
0
    def _dialect_node(self):
        self._dialects[self.dialect_name] = self

        content = self._parse_content()
        self.database_name = content['name']

        self.bullets = nodes.bullet_list()
        text = "The following dialect/DBAPI options are available.  "\
                "Please refer to individual DBAPI sections for connect information."
        sec = nodes.section('',
                nodes.paragraph('', '',
                    nodes.Text(
                        "Support for the %s database." % content['name'],
                        "Support for the %s database." % content['name']
                    ),
                ),
                nodes.title("DBAPI Support", "DBAPI Support"),
                nodes.paragraph('', '',
                    nodes.Text(text, text),
                    self.bullets
                ),
                ids=["dialect-%s" % self.dialect_name]
            )

        return [sec]
示例#21
0
文件: get-options.py 项目: ampl/mp
 def run(self):
   if ValueTableDirective.values[0].description is None:
     list = nodes.bullet_list()
     for v in ValueTableDirective.values:
       item = nodes.list_item()
       item += nodes.literal(v.value, v.value)
       list += item
     return [list]
   table = nodes.table()
   tgroup = nodes.tgroup()
   tbody = nodes.tbody()
   for v in ValueTableDirective.values:
     row = nodes.row()
     entry = nodes.entry()
     entry += nodes.literal(v.value, v.value)
     row += entry
     entry = nodes.entry()
     entry += nodes.paragraph(text=v.description)
     row += entry
     tbody += row
   tgroup += nodes.colspec(colwidth=10)
   tgroup += nodes.colspec(colwidth=90)
   tgroup += tbody
   table += tgroup
   return [table]
示例#22
0
 def run(self):
     ncolumns = self.options.get('columns', 2)
     node = nodes.Element()
     node.document = self.state.document
     self.state.nested_parse(self.content, self.content_offset, node)
     if len(node.children) != 1 or not isinstance(node.children[0],
                                                  nodes.bullet_list):
         return [self.state.document.reporter.warning(
             '.. hlist content is not a list', line=self.lineno)]
     fulllist = node.children[0]
     # create a hlist node where the items are distributed
     npercol, nmore = divmod(len(fulllist), ncolumns)
     index = 0
     table = nodes.table()
     tg = nodes.tgroup()
     table += tg
     row = nodes.row()
     tbody = nodes.tbody()
     for column in range(ncolumns):
         endindex = index + (column < nmore and (npercol + 1) or npercol)
         colspec = nodes.colspec()
         colspec.attributes['stub'] = 0
         colspec.attributes['colwidth'] = 100. / ncolumns
         col = nodes.entry()
         col += nodes.bullet_list()
         col[0] += fulllist.children[index:endindex]
         index = endindex
         tg += colspec
         row += col
     tbody += row
     tg += tbody
     table['classes'].append('hlist')
     return [table]
示例#23
0
def filebrief_replace_node(app, doctree, itemtype, items):
    """ where does the scene take place?
        here sir, here!!! I saw chaisaw, acid, and the like.
        what? this is just python code idiot!
    """
    env = app.builder.env
    nodefuncmap = dict()

    if itemtype == "functions":
        nodefuncmap = filebrief_nodefuncmap(doctree)

    listnode = nodes.bullet_list()
    for refname, (docname, type, theid) in sorted(items.iteritems()):
        pnode   = nodes.paragraph()
        if itemtype == "classes":
            pnode   = nodes.paragraph("class ", "class ")
        refnode = nodes.reference(refname, refname, refdocname=docname, refid=theid)

        retnode = refnode
        cnode = nodefuncmap.get(theid)
        if cnode:
            (_, fname) = split_func_name(refname)
            refnode = nodes.reference(fname, fname, refdocname=docname, refid=theid)
            i = cnode[0].first_child_matching_class(addnodes.desc_name)
            cnode[0][i] = refnode
            cnode.children = cnode[0].children
            retnode = cnode
        pnode.append(retnode)
        listnode.append(pnode)
    return listnode
示例#24
0
    def run(self):
        """Create a type list."""
        config = self.state.document.settings.env.config

        # Group processes by category
        processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)
        processes.sort(key=itemgetter('type'))
        processes_by_types = {k: list(g) for k, g in groupby(processes, itemgetter('type'))}

        listnode = nodes.bullet_list()

        for typ in sorted(processes_by_types.keys()):
            par = nodes.paragraph()
            par += nodes.literal(typ, typ)
            par += nodes.Text(' - ')

            processes = sorted(processes_by_types[typ], key=itemgetter('name'))
            last_process = processes[-1]
            for process in processes:
                node = nodes.reference('', process['name'], internal=True)
                node['refuri'] = config.autoprocess_definitions_uri + '#process-' + process['slug']
                node['reftitle'] = process['name']
                par += node
                if process != last_process:
                    par += nodes.Text(', ')

            listnode += nodes.list_item('', par)

        return [listnode]
示例#25
0
 def build_contents(self, node, level=0):
     level += 1
     sections = []
     i = len(node) - 1
     while i >= 0 and isinstance(node[i], nodes.section):
         sections.append(node[i])
         i -= 1
     sections.reverse()
     entries = []
     autonum = 0
     depth = 4   # XXX FIXME
     for section in sections:
         title = section[0]
         entrytext = title
         try:
             reference = nodes.reference('', '', refid=section['ids'][0], *entrytext)
         except IndexError:
             continue
         ref_id = self.document.set_id(reference)
         entry = nodes.paragraph('', '', reference)
         item = nodes.list_item('', entry)
         if level < depth:
             subsects = self.build_contents(section, level)
             item += subsects
         entries.append(item)
     if entries:
         contents = nodes.bullet_list('', *entries)
         return contents
     else:
         return []
    def test_assert_at_least_one(self):
        node = addnodes.Section()

        # failed
        with self.assertRaises(AssertionError):
            node.assert_having_at_least_one(addnodes.Action)

        # success
        node += addnodes.Action()
        node.assert_having_at_least_one(addnodes.Action)  # one item

        node += addnodes.Action()
        node.assert_having_at_least_one(addnodes.Action)  # two items

        # standard nodes are ignored
        node += nodes.section()
        node += nodes.paragraph()
        node += nodes.bullet_list()
        node.assert_having_at_least_one(addnodes.Action)

        # descendants are ignored
        node.pop()
        node[0] += addnodes.Action()
        node.assert_having_at_least_one(addnodes.Action)

        # other sections are ignored
        node[0] += addnodes.Parameters()
        node[0] += addnodes.Body()
        node.assert_having_at_least_one(addnodes.Action)
示例#27
0
def process_motor_nodes(app, doctree):
    # Search doctree for Motor's methods and attributes whose docstrings were
    # copied from PyMongo, and fix them up for Motor:
    #   1. Add a 'callback' param (sometimes optional, sometimes required) to
    #      all async methods. If the PyMongo method took no params, we create
    #      a parameter-list from scratch, otherwise we edit PyMongo's list.
    #   2. Remove all version annotations like "New in version 2.0" since
    #      PyMongo's version numbers are meaningless in Motor's docs.
    #   3. Remove "seealso" directives that reference PyMongo's docs.
    #
    # We do this here, rather than by registering a callback to Sphinx's
    # 'autodoc-process-signature' event, because it's way easier to handle the
    # parsed doctree before it's turned into HTML than it is to update the RST.
    for objnode in doctree.traverse(desc):
        if objnode["objtype"] in ("method", "attribute"):
            signature_node = find_by_path(objnode, [desc_signature])[0]
            name = ".".join([signature_node["module"], signature_node["fullname"]])

            assert name.startswith("motor.")
            obj_motor_info = motor_info.get(name)
            if obj_motor_info:
                desc_content_node = find_by_path(objnode, [desc_content])[0]
                if obj_motor_info.get("is_async_method"):
                    try:
                        # Find the parameter list, a bullet_list instance
                        parameters_node = find_by_path(desc_content_node, [field_list, field, field_body, bullet_list])[
                            0
                        ]
                    except IndexError:
                        # PyMongo method has no parameters, create an empty
                        # params list
                        parameters_node = bullet_list()
                        parameters_field_list_node = field_list(
                            "", field("", field_name("", "Parameters "), field_body("", parameters_node))
                        )

                        desc_content_node.append(parameters_field_list_node)

                    insert_callback(parameters_node)

                    callback_future_text = "If a callback is passed, returns None, else returns a" " Future."

                    desc_content_node.append(paragraph("", Text(callback_future_text)))

                if obj_motor_info["is_pymongo_docstring"]:
                    # Remove all "versionadded", "versionchanged" and
                    # "deprecated" directives from the docs we imported from
                    # PyMongo
                    version_nodes = find_by_path(desc_content_node, [versionmodified])

                    for version_node in version_nodes:
                        version_node.parent.remove(version_node)

                    # Remove all "seealso" directives that contain :doc:
                    # references from PyMongo's docs
                    seealso_nodes = find_by_path(desc_content_node, [seealso])

                    for seealso_node in seealso_nodes:
                        if 'reftype="doc"' in str(seealso_node):
                            seealso_node.parent.remove(seealso_node)
示例#28
0
 def build(self):
     """Build contributors repo details."""
     node_list = nodes.bullet_list()
     for contributor in self.contributors:
         node_contributor = nodes.list_item()
         node_contributor += contributor.build()
         node_list += node_contributor
     return node_list
 def render_bullet_list(self, token: SyntaxTreeNode) -> None:
     list_node = nodes.bullet_list()
     if token.attrs.get("class"):
         # this is used e.g. by tasklist
         list_node["classes"] = str(token.attrs["class"]).split()
     self.add_line_and_source_path(list_node, token)
     with self.current_node_context(list_node, append=True):
         self.render_children(token)
示例#30
0
    def make_properties_list(self, field):
        """Fill the ``field`` into a properties list and return it.

        :param dict field: the content of the property list to make
        :return: field_list instance filled with given field
        :rtype: nodes.field_list

        """
        properties_list = nodes.field_list()

        # changing the order of elements in this list affects
        # the order in which they are displayed
        property_names = [
            "label",
            "type",
            "description",
            "required",
            "disabled",
            "hidden",
            "default",
            "placeholder",
            "validate_regex",
            "choices",
            "collapse",
            "group",
        ]

        for name in property_names:
            if name not in field:
                continue

            value = field[name]

            # Value should be formatted in code-style (=literal) mode
            if name in ["type", "default", "placeholder", "validate_regex"]:
                literal_node = nodes.literal(str(value), str(value))
                properties_list += self.make_field(name, literal_node)

            # Special formating of ``value`` is needed if name == 'choices'
            elif name == "choices":
                bullet_list = nodes.bullet_list()
                for choice in value:
                    label = nodes.Text(choice["label"] + ": ")
                    val = nodes.literal(choice["value"], choice["value"])

                    paragraph = nodes.paragraph()
                    paragraph += label
                    paragraph += val
                    list_item = nodes.list_item()
                    list_item += paragraph
                    bullet_list += list_item

                properties_list += self.make_field(name, bullet_list)

            else:
                properties_list += self.make_field(name, str(value))

        return properties_list
示例#31
0
文件: __init__.py 项目: wertziop/lab
def process_authorlists(app, doctree, fromdocname):
    """Build list of authors sorted by contribution count."""
    env = app.builder.env
    authors = set(
        itertools.chain(*[authors for authors in env.author_list.values()]))
    guides_by_author = {
        a: set(g for g, guide_authors in env.author_list.items()
               if a in guide_authors)
        for a in authors
    }
    count_by_author = {a: len(guides_by_author[a]) for a in authors}

    for node in doctree.traverse(allauthors):
        author_list = nodes.enumerated_list(classes=["hof__list"])

        for author, count in sorted(count_by_author.items(),
                                    key=lambda x: (-x[1], x[0].lower())):
            # list entry
            author_entry = nodes.list_item(classes=["hof__entry"])
            author_list += author_entry

            # counter
            counter_div = nodes.container(classes=["hof__counter"])
            counter_div += addnodes.compact_paragraph(text=count)
            author_entry += counter_div

            # author
            author_div = nodes.container(classes=["hof__author"])
            author_div += addnodes.compact_paragraph(text=author)
            author_entry += author_div

            # guide list
            guides_div = nodes.container(classes=["hof__guides"])
            author_entry += guides_div

            # linklist
            guides_list = nodes.bullet_list(classes=["hof__guide_list"])
            guides_div += guides_list

            for guide in sorted(guides_by_author[author]):
                # guide
                link_entry = nodes.list_item(classes=["hof__guide"])
                guides_list += link_entry

                # I can't figure out a way to get the link and title from a page name..
                link = '/' + guide + '.html'
                title = guide.partition("_")[2].title()

                link_wrapper = addnodes.compact_paragraph()
                link_wrapper += nodes.reference("",
                                                "",
                                                nodes.Text(title),
                                                internal=True,
                                                refuri=link,
                                                anchorname="")
                link_entry += link_wrapper

        node.replace_self([author_list])
示例#32
0
    def make_params(self, params):
        if not params:
            return []

        ret = nodes.field('', nodes.field_name('Parameters', 'Parameters'))
        with addto(ret, nodes.field_body()) as body,\
             addto(body, nodes.bullet_list()) as holder:
            holder += make_parameters(params, mod=self.modname)
        return ret
示例#33
0
def handle_doc_fields(node):
    # don't traverse, only handle field lists that are immediate children
    for child in node.children:
        if not isinstance(child, nodes.field_list):
            continue
        params = None
        param_nodes = {}
        param_types = {}
        new_list = nodes.field_list()
        for field in child:
            fname, fbody = field
            try:
                typ, obj = fname.astext().split(None, 1)
                typ = doc_fields_with_arg[typ]
                if len(fbody.children) == 1 and \
                   isinstance(fbody.children[0], nodes.paragraph):
                    children = fbody.children[0].children
                else:
                    children = fbody.children
                if typ == 'param':
                    if not params:
                        pfield = nodes.field()
                        pfield += nodes.field_name('Parameters', 'Parameters')
                        pfield += nodes.field_body()
                        params = nodes.bullet_list()
                        pfield[1] += params
                        new_list += pfield
                    dlitem = nodes.list_item()
                    dlpar = nodes.paragraph()
                    dlpar += nodes.emphasis(obj, obj)
                    dlpar += nodes.Text(' -- ', ' -- ')
                    dlpar += children
                    param_nodes[obj] = dlpar
                    dlitem += dlpar
                    params += dlitem
                elif typ == 'type':
                    param_types[obj] = fbody.astext()
                else:
                    fieldname = typ + ' ' + obj
                    nfield = nodes.field()
                    nfield += nodes.field_name(fieldname, fieldname)
                    nfield += nodes.field_body()
                    nfield[1] += fbody.children
                    new_list += nfield
            except (KeyError, ValueError):
                fnametext = fname.astext()
                try:
                    typ = doc_fields_without_arg[fnametext]
                except KeyError:
                    # at least capitalize the field name
                    typ = fnametext.capitalize()
                fname[0] = nodes.Text(typ)
                new_list += field
        for param, type in param_types.iteritems():
            if param in param_nodes:
                param_nodes[param].insert(1, nodes.Text(' (%s)' % type))
        child.replace_self(new_list)
示例#34
0
    def _parse(self, tree):
        if isinstance(tree, minidom.Document):
            return self._parse(tree.childNodes[0])
        if isinstance(tree, minidom.Text):
            return nodes.Text(tree.data)

        # Get children.
        children = [self._parse(c) for c in tree.childNodes]

        if tree.tagName == 'epytext':
            return children
        if tree.tagName == 'para':
            return nodes.paragraph('','', *children)
        if tree.tagName == 'section':
            return nodes.section('', *children)
        if tree.tagName == 'heading':
            return nodes.title('','', *children)
        if tree.tagName == 'fieldlist':
            return nodes.field_list('', *children)
        if tree.tagName == 'field':
            return nodes.field('', *self._parse_field(tree, children))
        if tree.tagName == 'literalblock':
            return nodes.literal_block('','', *children)
        if tree.tagName == 'doctestblock':
            return nodes.doctest_block('','', *children)
        if tree.tagName == 'ulist':
            return nodes.bullet_list('', *children)
        if tree.tagName == 'olist':
            return nodes.enumerated_list('', *children)
        if tree.tagName == 'li':
            return nodes.list_item('', *children)
        if tree.tagName == 'link':
            # [XX] discards link target.
            name, target = children
            return nodes.title_reference('','', name)
        if tree.tagName == 'uri':
            name, target = children
            return nodes.reference('','', name, refuid=target.astext())
        if tree.tagName == 'code':
            return nodes.literal('','', *children)
        if tree.tagName == 'math':
            return nodes.emphasis('','', *children)
        if tree.tagName == 'italic':
            return nodes.emphasis('','', *children)
        if tree.tagName == 'bold':
            return nodes.strong('','', *children)
        if tree.tagName == 'indexed': 
            # [XX] doesn't mark the fact that it's indexedd
            return nodes.emphasis('','', *children)
        if tree.tagName == 'symbol':
            # use substitutions.  
            # [XX] this needs to be fixed!
            return nodes.Text(children[0])
        elif tree.tagName in ('tag', 'arg', 'name', 'target'):
            return children[0]
        else:
            raise ValueError, ('unknown %s' % tree.tagName)
示例#35
0
 def handle_nested_parse(lines, offset, node):
     from docutils import nodes
     node.append(nodes.paragraph(text='additional information'))
     bullet_list = nodes.bullet_list()
     p = nodes.paragraph('', 'item1: ', nodes.strong(text='strong'))
     bullet_list.append(nodes.list_item('', p))
     p = nodes.paragraph('', 'item2: ', nodes.emphasis(text='emphasis'))
     bullet_list.append(nodes.list_item('', p))
     node.append(bullet_list)
示例#36
0
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]
示例#37
0
    def _parse(self, tree):
        if isinstance(tree, minidom.Document):
            return self._parse(tree.childNodes[0])
        if isinstance(tree, minidom.Text):
            return nodes.Text(tree.data)

        # Get children.
        children = [self._parse(c) for c in tree.childNodes]

        if tree.tagName == 'epytext':
            return children
        if tree.tagName == 'para':
            return nodes.paragraph('', '', *children)
        if tree.tagName == 'section':
            return nodes.section('', *children)
        if tree.tagName == 'heading':
            return nodes.title('', '', *children)
        if tree.tagName == 'fieldlist':
            return nodes.field_list('', *children)
        if tree.tagName == 'field':
            return nodes.field('', *self._parse_field(tree, children))
        if tree.tagName == 'literalblock':
            return nodes.literal_block('', '', *children)
        if tree.tagName == 'doctestblock':
            return nodes.doctest_block('', '', *children)
        if tree.tagName == 'ulist':
            return nodes.bullet_list('', *children)
        if tree.tagName == 'olist':
            return nodes.enumerated_list('', *children)
        if tree.tagName == 'li':
            return nodes.list_item('', *children)
        if tree.tagName == 'link':
            # [XX] discards link target.
            name, target = children
            return nodes.title_reference('', '', name)
        if tree.tagName == 'uri':
            name, target = children
            return nodes.reference('', '', name, refuid=target.astext())
        if tree.tagName == 'code':
            return nodes.literal('', '', *children)
        if tree.tagName == 'math':
            return nodes.emphasis('', '', *children)
        if tree.tagName == 'italic':
            return nodes.emphasis('', '', *children)
        if tree.tagName == 'bold':
            return nodes.strong('', '', *children)
        if tree.tagName == 'indexed':
            # [XX] doesn't mark the fact that it's indexedd
            return nodes.emphasis('', '', *children)
        if tree.tagName == 'symbol':
            # use substitutions.
            # [XX] this needs to be fixed!
            return nodes.Text(children[0])
        elif tree.tagName in ('tag', 'arg', 'name', 'target'):
            return children[0]
        else:
            raise ValueError, ('unknown %s' % tree.tagName)
示例#38
0
 def run(self):
     models = skl2onnx.supported_converters(True)
     bullets = nodes.bullet_list()
     ns = [bullets]
     for mod in models:
         par = nodes.paragraph()
         par += nodes.Text(mod)
         bullets += nodes.list_item('', par)
     return ns
示例#39
0
    def make_params(self, params):
        if not params:
            return []

        ret = nodes.field('', nodes.field_name('Parameters', 'Parameters'))
        with addto(ret, nodes.field_body()) as body,\
             addto(body, nodes.bullet_list()) as holder:
            holder += make_parameters(params, mod=self.modname)
        return ret
 def visit_ul(self, node):
     ul = nodes.bullet_list()
     ids = node.attrib.get("id", "")
     if ids:
         ul['ids'] = [node.attrib.pop("id")]
     classes = node.attrib.get("classes", "")
     if classes:
         ul["classes"] = [node.attrib.pop("class")]
     return ul
示例#41
0
 def toInterfaceList(self, interfaceList):
     InterfaceList = nodes.bullet_list()
     for Interface in interfaceList:
         listItem = nodes.list_item()
         para = nodes.paragraph()
         para += InterfaceInlineRefNode(name=Interface['name'])
         listItem += para
         InterfaceList.append(listItem)
     return InterfaceList
示例#42
0
def handle_doc_fields(node):
    # don't traverse, only handle field lists that are immediate children
    for child in node.children:
        if not isinstance(child, nodes.field_list):
            continue
        params = None
        param_nodes = {}
        param_types = {}
        new_list = nodes.field_list()
        for field in child:
            fname, fbody = field
            try:
                typ, obj = fname.astext().split(None, 1)
                typ = doc_fields_with_arg[typ]
                if len(fbody.children) == 1 and \
                   isinstance(fbody.children[0], nodes.paragraph):
                    children = fbody.children[0].children
                else:
                    children = fbody.children
                if typ == 'param':
                    if not params:
                        pfield = nodes.field()
                        pfield += nodes.field_name('Parameters', 'Parameters')
                        pfield += nodes.field_body()
                        params = nodes.bullet_list()
                        pfield[1] += params
                        new_list += pfield
                    dlitem = nodes.list_item()
                    dlpar = nodes.paragraph()
                    dlpar += nodes.emphasis(obj, obj)
                    dlpar += nodes.Text(' -- ', ' -- ')
                    dlpar += children
                    param_nodes[obj] = dlpar
                    dlitem += dlpar
                    params += dlitem
                elif typ == 'type':
                    param_types[obj] = fbody.astext()
                else:
                    fieldname = typ + ' ' + obj
                    nfield = nodes.field()
                    nfield += nodes.field_name(fieldname, fieldname)
                    nfield += nodes.field_body()
                    nfield[1] += fbody.children
                    new_list += nfield
            except (KeyError, ValueError):
                fnametext = fname.astext()
                try:
                    typ = doc_fields_without_arg[fnametext]
                except KeyError:
                    # at least capitalize the field name
                    typ = fnametext.capitalize()
                fname[0] = nodes.Text(typ)
                new_list += field
        for param, type in param_types.iteritems():
            if param in param_nodes:
                param_nodes[param].insert(1, nodes.Text(' (%s)' % type))
        child.replace_self(new_list)
示例#43
0
    def _entries_from_toctree(toctreenode, parents, subtree=False):
        refs = [(e[0], e[1]) for e in toctreenode['entries']]
        entries = []
        for (title, ref) in refs:
            refdoc = None
            if url_re.match(ref):
                raise NotImplementedError('Not going to implement this (url)')
            elif ref == 'env':
                raise NotImplementedError('Not going to implement this (env)')
            else:
                if ref in parents:
                    env.warn(
                        ref, 'circular toctree references '
                        'detected, ignoring: %s <- %s' %
                        (ref, ' <- '.join(parents)))
                    continue
                refdoc = ref
                toc = env.tocs[ref].deepcopy()
                env.process_only_nodes(toc, builder, ref)
                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
                env.warn_node(
                    'toctree contains reference to document %r that '
                    'doesn\'t have a title: no link will be generated' % ref,
                    toctreenode)

            # 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 subtocnode in toc.traverse(addnodes.toctree):
                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)

            entries.extend(toc.children)
        if not subtree:
            ret = nodes.bullet_list()
            ret += entries
            return [ret]
        return entries
示例#44
0
 def toInvolingList(self, involingList):
     ComponentList = nodes.bullet_list()
     for component in involingList:
         listItem = nodes.list_item('')
         para = nodes.paragraph('', '')
         para += ComponentInlineRefNode(
             componentCodeName=component['codeName'])
         listItem += para
         ComponentList.append(listItem)
     return ComponentList
 def create_items(self, key, values):
     item = nodes.list_item()
     p = nodes.paragraph()
     bullet_list = nodes.bullet_list()
     for value in values:
         bullet_list += self.create_item('', value)
     p += nodes.strong('', key)
     item += p
     item += bullet_list
     return item
示例#46
0
 def _render_contributors(self, people):
     ul = nodes.bullet_list(classes=["changelog-list", "simple"])
     for username in people.keys():
         fullname = users.get_full_name(username)
         url = "https://github.com/" + username
         link = nodes.reference("", fullname, refuri=url, internal=False)
         li = nodes.list_item(classes=["changelog-list-item", "gh"])
         li += nodes.inline("", "", link)
         ul += li
     return ul
示例#47
0
    def make_node(self, lang='en'):
        if lang not in texts.keys():
            lang = 'en'

        arg_map = texts[lang]["arg_map"]
        task_title = texts[lang]["task_title"]
        module_title = texts[lang]["module_title"]

        module = ""
        module_args = []
        # first, search module
        for arg, m in self.args.items():
            if arg not in arg_map.keys():
                module = arg
                module_args.append(m)

        item = nodes.admonition()
        title = nodes.title(text=self.name)
        item.append(title)

        for m in module_args:
            if isinstance(m, str):
                item.append(nodes.paragraph(text=m))
            else:
                mlist = []
                for k, v in m.items():
                    mlist.append("%s=%s" % (k, v))
                item.append(nodes.paragraph(text=" ".join(mlist)))

        field_list = nodes.field_list()
        field_list.append(self.make_arg(module_title, module))
        # second, create node tree
        for arg, txt in arg_map.items():
            if not txt:  # skip name etc...
                continue
            if arg not in self.args:
                continue
            value = self.args[arg]  # value of that task arg
            if isinstance(value, list):
                bl = nodes.bullet_list()
                for v in value:
                    body = nodes.emphasis(text=v)
                    bl.append(nodes.list_item('', body))
                name = nodes.field_name(text=txt)
                body = nodes.field_body()
                body.append(bl)
                field = nodes.field()
                field += [name, body]
                field_list.append(field)
            else:
                field_list.append(self.make_arg(txt, value))

        item.append(field_list)

        return item
示例#48
0
    def run(self) -> List[nodes.Node]:
        bullets = nodes.bullet_list()

        for unit_set_name, unit_set in UNIT_SYSTEM.unit_sets.items():
            top_item = nodes.list_item()
            bullets += top_item

            top_paragraph = nodes.paragraph(text=unit_set_name.title() + ":")
            top_item += top_paragraph

            sub_bullets = nodes.bullet_list()
            top_paragraph += sub_bullets

            for unit in unit_set.units:
                item = nodes.list_item()
                paragraph = nodes.paragraph(text=", ".join(unit.names))
                item += paragraph
                sub_bullets += item

        return [bullets]
 def make_list_representation(self, value):
     bl = nodes.bullet_list()
     if isinstance(value, list):
         for v in value:
             body = nodes.literal(text=v)
             bl.append(nodes.list_item('', body))
     elif isinstance(value, dict):
         for k, v in value.items():
             body = nodes.literal(text="%s=%s" % (k, v))
             bl.append(nodes.list_item('', body))
     return bl
示例#50
0
    def create_bullet_list(self, lines: typing.Iterable[str]):
        bullet_list = nodes.bullet_list()
        parse_msgs = []
        for line in lines:
            text_nodes, messages = self.state.inline_text(line, self.lineno + self.content_offset)
            parse_msgs += messages
            par_node = nodes.paragraph('', '', *text_nodes)
            list_item = nodes.list_item('', par_node)
            bullet_list += list_item

        return bullet_list, parse_msgs
示例#51
0
    def build_node_authors(self) -> nodes.Node:
        authors_node = nodes.paragraph(text='Authors',
                                       classes=self.classes['authors'])

        authors_bullet_list = nodes.bullet_list(bullet='-')
        for a in self.authors:
            author_list_item = nodes.list_item()
            author_list_item += a.build_node(domain=self.domain)
            authors_bullet_list += author_list_item

        authors_node += authors_bullet_list
        return authors_node
示例#52
0
def visit_language_specific_pages_node_html(self, node):
    node['classes'] = ['tabbable']

    ul = nodes.bullet_list()
    ul['classes'] = ['nav', 'nav-tabs']
    # set_source_info(self, ul)

    href = tab('', 'Language-specific info:')
    href['classes'] = ['disabled']
    paragraph = nodes.paragraph('', '')
    li = nodes.list_item('')
    li['classes'] = ['disabled']

    paragraph.append(href)
    li.append(paragraph)
    ul.append(li)

    first = True
    for part in node.parts:
        href = tab(part.language, part.language)
        href['refuri'] = '#' + make_id(node, part.language)
        paragraph = nodes.paragraph('')
        li = nodes.list_item('')
        if first:
            li['classes'].append('active')

        paragraph.append(href)
        li.append(paragraph)
        ul.append(li)

        first = False

    node.append(ul)

    pages = section()
    pages['classes'] = ['tab-content']

    first = True
    for part in node.parts:
        page = section()
        page['classes'] = ['tab-pane']
        if first:
            page['classes'].append('active')
        page['ids'] = [make_id(node, part.language)]

        page.append(part.paragraph)
        pages.append(page)

        first = False

    node.append(pages)

    self.body.append(self.starttag(node, 'div'))
示例#53
0
def replace_settingslist_nodes(app, doctree, fromdocname):
    env = app.builder.env

    for node in doctree.traverse(settingslist_node):
        settings_list = nodes.bullet_list()
        settings_list.extend([
            make_setting_element(d, app, fromdocname)
            for d in sorted(env.scrapy_all_settings,
                            key=itemgetter('setting_name'))
            if fromdocname != d['docname']
        ])
        node.replace_self(settings_list)
示例#54
0
def construct_property_description_list(name):
    """
    Construct a skeleton for sphinx member description block
    """
    description_group_list = nodes.field_list()
    obj_desc = nodes.field()
    obj_desc += nodes.field_name(_(name), _(name))
    description_group_list += obj_desc

    obj_list = nodes.bullet_list()
    description_group_list += nodes.field_body('', obj_list)
    return description_group_list, obj_list
示例#55
0
    def list_block(self, block):
        list_node = None
        if (block.list_data['type'] == "Bullet"):
            list_node = nodes.bullet_list()
        else:
            list_node = nodes.enumerated_list()
        list_node.line = block.start_line

        with self._temp_current_node(list_node):
            self.convert_blocks(block.children)

        self.current_node.append(list_node)
示例#56
0
def process_postlist(app, doctree, docname):
    """Replace `PostList` nodes with lists of posts. Also, register all posts
    if they have not been registered yet."""

    blog = Blog()
    if not blog:
        register_posts(app)

    for node in doctree.traverse(PostList):
        colls = []
        for cat in ['tags', 'author', 'category', 'location', 'language']:
            for coll in node[cat]:
                if coll in blog.catalogs[cat].collections:
                    colls.append(blog.catalogs[cat].collections[coll])
        if colls:
            posts = set(blog.posts)
            for coll in colls:
                posts = posts & set(coll)
            posts = list(posts)
            posts.sort(reverse=True)
        else:
            posts = list(
                blog.recent(node.attributes['length'], docname,
                            **node.attributes))
        if node.attributes['sort']:
            posts.sort()  # in reverse chronological order, so no reverse=True
        bl = nodes.bullet_list()
        for post in posts:
            bli = nodes.list_item()
            bl.append(bli)
            par = nodes.paragraph()

            if True:
                par.append(
                    nodes.Text(
                        post.date.strftime(_(blog.post_date_format)) + ' - '))

            bli.append(par)
            ref = nodes.reference()
            ref['refuri'] = app.builder.get_relative_uri(docname, post.docname)
            ref['ids'] = []
            ref['backrefs'] = []
            ref['dupnames'] = []
            ref['classes'] = []
            ref['names'] = []
            ref['internal'] = True
            par.append(ref)

            emp = nodes.emphasis()
            ref.append(emp)
            emp.append(nodes.Text(post.title))

        node.replace_self(bl)
示例#57
0
文件: directives.py 项目: rlfss/sc
 def make_dependencies(self, field, doc):
     field += nodes.field_name("Depends On", "Depends On")
     with addto(field, nodes.field_body()) as body:
         with addto(body, nodes.bullet_list()) as deps:
             for dep in sorted(doc.dependencies):
                 ref = addnodes.pending_xref(
                     dep, nodes.paragraph(dep, dep),
                     refdomain='js',
                     reftype='module',
                     reftarget=dep,
                 )
                 deps += nodes.list_item(dep, ref)
示例#58
0
    def run(self):
        base = 'drivers_{}.yml'.format(self.arguments[0])
        filename = resource_filename('spatialist', base)
        drivers = yaml.safe_load(open(filename))

        lst = nodes.bullet_list()
        for extension, name in drivers.items():
            item = nodes.list_item()
            lst += item
            item += nodes.paragraph(text='.{} ({})'.format(extension, name))

        return [lst]
示例#59
0
    def citation_list(self, citable):
        bullet_list = nodes.bullet_list()
        for citation in citable.citations:
            list_item = nodes.list_item()

            para = nodes.paragraph(text=f"{citation.author}, {citation.year}. ")
            para += nodes.reference(
                internal=False, refuri=citation.doi, text=citation.doi
            )
            list_item += para
            bullet_list += list_item
        return bullet_list
示例#60
0
def process_latest_toc(app, doctree, fromdocname):
    """We traverse the doctree looking for publication dates to build the
    date-based ToC here. Since the order in whicih documents are processed is
    ill-defined, from our perspective, we parse all of them each time, but
    cache them in the environment"""

    env = app.builder.env
    cache_article_dates(env)
        
    feed_pub_dates = getattr(env, 'feed_pub_dates', {})
    
    for node in doctree.traverse(latest):
        entries = node['entries']
        includefiles = node['includefiles']
        
        decorated_entries = [
          (feed_pub_dates.get(doc), title, doc)
          for title, doc in entries
          if doc in feed_pub_dates]
        decorated_entries.sort(reverse=True)
        
        latest_list = nodes.bullet_list('',
          classes=['feed-latest-articles'])
        
        for date, title, docname in decorated_entries:
            para = nodes.paragraph()
            list_item = nodes.list_item('', para,
              classes=['feed-dated-article'])
            
            if title is None:
                title = env.titles.get(docname)
                if title:
                    title = title[0] #.astext()

            # Create a reference
            newnode = nodes.reference('', '')
            innernode = title #nodes.emphasis(title, title)
            newnode['refdocname'] = docname
            newnode['refuri'] = app.builder.get_relative_uri(
                fromdocname, docname)
            newnode.append(innernode)
            para += newnode
            para += nodes.Text(' ', ' ')
            stringdate = date.strftime('%Y/%m/%d')
            date_wrapper = nodes.container(classes=['feed-article-date'])
            date_wrapper += nodes.Text(stringdate, stringdate)
            para += date_wrapper

            # Insert into the latestlist
            latest_list.append(list_item)

        node.replace_self(latest_list)