示例#1
0
文件: body.py 项目: 89sos98/main
 def run(self):
     self.assert_has_content()
     text = '\n'.join(self.content)
     node = nodes.compound(text)
     node['classes'] += self.options.get('class', [])
     self.state.nested_parse(self.content, self.content_offset, node)
     return [node]
示例#2
0
文件: body.py 项目: srid/debris
 def run(self):
     self.assert_has_content()
     text = "\n".join(self.content)
     node = nodes.compound(text)
     node["classes"] += self.options.get("class", [])
     self.state.nested_parse(self.content, self.content_offset, node)
     return [node]
示例#3
0
 def run(self):
     prefix = raw('', '\\par\\begin{samepage}', format='latex')
     suffix = raw('', '\\end{samepage}\\par', format='latex')
     text = '\n'.join(self.content)
     content_node = compound(rawsource=text)
     self.state.nested_parse(self.content, self.content_offset, content_node)
     return [prefix, content_node, suffix]
示例#4
0
 def run(self):
     latexPrefix = raw('', '{\\centering', format='latex')
     latexSuffix = raw('', '\\par}\\bigskip', format='latex')
     text = '\n'.join(self.content)
     content_node = compound(rawsource=text)
     self.state.nested_parse(self.content, self.content_offset, content_node)
     content_node.attributes['classes'].append('caption')
     return [latexPrefix, content_node, latexSuffix]
示例#5
0
    def run(self):
        self.assert_has_content()

        body = nodes.compound('\n'.join(self.content), classes=['tabs'])
        self.state.nested_parse(self.content, self.content_offset, body)

        titles = []
        for child in body.children:
            if isinstance(child, nodes.literal_block):
                titles.append(get_lexer_by_name(child['language']).name)
            else:
                assert child['names'], ("A switcher case must be either a "\
                                        "code block or a compound with a name")
                titles.append(' '.join(child['names']))
        tabs = nodes.bullet_list('', *[
            nodes.list_item('', nodes.Text(title))
            for title in titles
        ])
        node = nodes.compound('', tabs, body, classes=['content-switcher'])
        return [node]
示例#6
0
文件: body.py 项目: garinh/cs
def compound(name, arguments, options, content, lineno,
             content_offset, block_text, state, state_machine):
    text = '\n'.join(content)
    if not text:
        error = state_machine.reporter.error(
            'The "%s" directive is empty; content required.' % name,
            nodes.literal_block(block_text, block_text), line=lineno)
        return [error]
    node = nodes.compound(text)
    node['classes'] += options.get('class', [])
    state.nested_parse(content, content_offset, node)
    return [node]
示例#7
0
    def run(self):

        node = compound()
        dotted = self.arguments[0].split()[0]

        # Get the workflow for ``dotted``.
        try:
            workflow = Workflow(dotted)
        except WorkflowException as err:
            return [node.document.reporter.warning(
                err.args[0], line=self.lineno)]

        self.rst = []

        for state in workflow.states:
            # section title
            title = u'Role to Permissions mapping for state "{}" ({})'.format(
                state['title'], state['name'])

            # table format
            self.rst.append(u'.. tabularcolumns:: |R|{}|'.format(
                u'|'.join(['C'] * len(workflow.permissions)))
            )
            self.rst.append(u'.. csv-table:: {}'.format(title))
            # table header
            thead = ['Role / Permission', ]
            thead.extend([c for c in workflow.permissions])
            self.rst.append(u'   :header: {}'.format(
                u','.join(u'"{}"'.format(c) for c in thead)
            ))
            self.rst.append('')
            # table body
            for role in workflow.roles:
                trow = [role, ]
                perms = state['data'].get(u'role:{}'.format(role), u'')
                for p in workflow.permissions:
                    if p in perms:
                        trow.append('Y')
                    else:
                        trow.append('N')
                self.rst.append(u'   {}'.format(
                    u','.join(u'"{}"'.format(c) for c in trow)
                ))

        result = ViewList()
        result.append(u'', self.directive)
        for r in self.rst:
            result.append(r, self.directive)
        result.append(u'', self.directive)

        self.state.nested_parse(result, 0, node)
        return node.children
示例#8
0
 def run(self):
     ret = super(Latest, self).run()
     #extract the tocnode. We not want.
     #Could we even expand it to a full hierarchy here?
     tocnode = ret[0][0]
     tocatts = tocnode.non_default_attributes()
     latestnode = latest()
     for key, val in tocatts.iteritems():
         latestnode[key] = val
     wrappernode = nodes.compound(classes=['latest-wrapper'])
     wrappernode.append(latestnode)
     ret.append(wrappernode)
     return ret
 def run(self):
     ret = super(Latest, self).run()
     #extract the tocnode. We not want.
     #Could we even expand it to a full hierarchy here?
     tocnode = ret[0][0]
     tocatts = tocnode.non_default_attributes()
     latestnode = latest()
     for key, val in tocatts.iteritems():
         latestnode[key] = val
     wrappernode = nodes.compound(classes=['latest-wrapper'])
     wrappernode.append(latestnode)
     ret.append(wrappernode)
     return ret
示例#10
0
def compound(name, arguments, options, content, lineno, content_offset,
             block_text, state, state_machine):
    text = '\n'.join(content)
    if not text:
        error = state_machine.reporter.error(
            'The "%s" directive is empty; content required.' % name,
            nodes.literal_block(block_text, block_text),
            line=lineno)
        return [error]
    node = nodes.compound(text)
    node['classes'] += options.get('class', [])
    state.nested_parse(content, content_offset, node)
    return [node]
 def run(self):
     doc = self.state.document
     env = doc.settings.env
     if 'layout' in self.options:
         layout = self.options['layout']
     else:
         layout = env.config.demo_layout
     if not self.layout_re.match(layout):
         return [
             doc.reporter.error("invalid layout specifier: %s" % layout,
                                lineno=self.lineno)
         ]
     order = []
     for block in layout.split(','):
         block = block.strip()
         is_hidden = block[0] == '-'
         block = block.lstrip('+-')
         order.append((block, is_hidden))
     wrapper = nodes.compound(classes=['demo-wrapper'])
     data = "\n".join(self.content)
     for block, is_hidden in order:
         if block == 'demo':
             header = nodes.paragraph(classes=['demo-header'])
             header += nodes.Text("Demo")
             if is_hidden:
                 header['classes'].append('demo-hide')
             demo = nodes.raw(data,
                              data,
                              format='html',
                              classes=['demo-area'])
             html_wrapper = addnodes.only(expr='html')
             html_wrapper += header
             html_wrapper += demo
             wrapper += html_wrapper
         elif block == 'source':
             header = nodes.paragraph(classes=['demo-header'])
             header += nodes.Text("Source")
             if is_hidden:
                 header['classes'].append('demo-hide')
             source = nodes.literal_block(data,
                                          data,
                                          language='html',
                                          classes=['demo-source'])
             html_wrapper = addnodes.only(expr='html')
             html_wrapper += header
             wrapper += html_wrapper
             wrapper += source
         else:
             assert False, block
     return [wrapper]
 def run(self):
     pnode = nodes.compound(classes=["impl-detail"])
     content = self.content
     add_text = nodes.strong("CPython implementation detail:", "CPython implementation detail:")
     if self.arguments:
         n, m = self.state.inline_text(self.arguments[0], self.lineno)
         pnode.append(nodes.paragraph("", "", *(n + m)))
     self.state.nested_parse(content, self.content_offset, pnode)
     if pnode.children and isinstance(pnode[0], nodes.paragraph):
         pnode[0].insert(0, add_text)
         pnode[0].insert(1, nodes.Text(" "))
     else:
         pnode.insert(0, nodes.paragraph("", "", add_text))
     return [pnode]
示例#13
0
 def run(self):
     pnode = nodes.compound(classes=['impl-detail'])
     content = self.content
     add_text = nodes.strong('CPython implementation detail:',
                             'CPython implementation detail:')
     if self.arguments:
         n, m = self.state.inline_text(self.arguments[0], self.lineno)
         pnode.append(nodes.paragraph('', '', *(n + m)))
     self.state.nested_parse(content, self.content_offset, pnode)
     if pnode.children and isinstance(pnode[0], nodes.paragraph):
         pnode[0].insert(0, add_text)
         pnode[0].insert(1, nodes.Text(' '))
     else:
         pnode.insert(0, nodes.paragraph('', '', add_text))
     return [pnode]
示例#14
0
    def run(self):
        doc = self.state.document
        env = doc.settings.env
        output = []
        entries = []
        includefiles = []
        glob_regex = 'glob-regex' in self.options
        glob = glob_regex or 'glob' in self.options

        if glob:
            content_iter = self._glob_content(env, self.content, glob_regex)
        else:
            content_iter = self.content

        for entry in content_iter:
            if not entry:
                continue
            docname = docname_join(env.docname, entry)
            if docname not in env.found_docs:
                output.append(
                    doc.reporter.warning(
                        'feed contains a reference to nonexisting '
                        'document %r' % docname,
                        line=self.lineno))
                env.note_reread()
            else:
                entries.append((None, docname))
                includefiles.append(docname)
        subnode = addnodes.toctree()
        subnode['parent'] = env.docname
        subnode['entries'] = entries
        subnode['includefiles'] = includefiles
        subnode['maxdepth'] = 1
        subnode['glob'] = False
        subnode['hidden'] = True
        subnode['numbered'] = False
        subnode['titlesonly'] = False
        wrappernode = nodes.compound(classes=['toctree-wrapper'])
        wrappernode.append(subnode)
        output.append(wrappernode)
        subnode = feed()
        subnode['entries'] = includefiles
        subnode['rss'] = self.options.get('rss')
        subnode['title'] = self.options.get('title', '')
        subnode['link'] = self.options.get('link', '')
        subnode['description'] = self.options.get('description', '')
        output.append(subnode)
        return output
示例#15
0
 def run(self):
     self.filenames = set()
     if self.arguments[0] == 'lexers':
         out = self.document_lexers()
     elif self.arguments[0] == 'formatters':
         out = self.document_formatters()
     elif self.arguments[0] == 'filters':
         out = self.document_filters()
     else:
         raise Exception('invalid argument for "pygmentsdoc" directive')
     node = nodes.compound()
     vl = ViewList(out.split('\n'), source='')
     nested_parse_with_titles(self.state, vl, node)
     for fn in self.filenames:
         self.state.document.settings.record_dependencies.add(fn)
     return node.children
示例#16
0
 def run(self):
     self.filenames = set()
     if self.arguments[0] == "lexers":
         out = self.document_lexers()
     elif self.arguments[0] == "formatters":
         out = self.document_formatters()
     elif self.arguments[0] == "filters":
         out = self.document_filters()
     else:
         raise Exception('invalid argument for "pygmentsdoc" directive')
     node = nodes.compound()
     vl = ViewList(out.split("\n"), source="")
     nested_parse_with_titles(self.state, vl, node)
     for fn in self.filenames:
         self.state.document.settings.record_dependencies.add(fn)
     return node.children
示例#17
0
    def _create_array_items_node(self, items, path):
        path = self._append_to_path(path, 'items')
        for combiner in ['anyOf', 'allOf']:
            if combiner in items:
                return self._create_combiner(items,
                                             combiner,
                                             array=True,
                                             path=path)

        node_list = nodes.compound()
        node_list.append(
            nodes.line(
                text='Items in the array are restricted to the following types:'
            ))
        node_list.append(self._process_properties(items, top=True, path=path))
        return node_list
示例#18
0
 def run(self):
   try:
     names = self.arguments[0].split()
     rst = '\n'.join([str(_PROD[name]) for name in names])
     self.arguments = [rst]
     p = nodes.compound()
     p['classes'] += ['dparser', 'admonition', 'collapse']
     title = nodes.paragraph()
     title['classes'] += ['first', 'admonition-title']
     title += nodes.Text(' '.join(names))
     body = ProductionList.run(self)[0]
     body['classes'] += ['last']
     p += [title, body]
     return [p]
   except KeyError as e:
     self.state.document.reporter.severe("Unknown nonterminal: " + str(e))
     return []
 def run(self):
     # First argument is the name of the glyph
     alert_name = 'alert-{}'.format(self.custom_class)
     # get the label content
     text = '\n'.join(self.content)
     # Create a new container element (div)
     new_element = nodes.compound(text)
     # Update its content
     self.state.nested_parse(self.content, self.content_offset, new_element)
     # Recurse inside its children and change the hyperlinks classes
     for child in new_element.traverse(include_self=False):
         if isinstance(child, nodes.reference):
             child.set_class('alert-link')
     # Set its custom bootstrap classes
     new_element['classes'] += ['alert ', alert_name]
     # Return one single element
     return [new_element]
 def run(self):
     doc = self.state.document
     env = doc.settings.env
     if 'layout' in self.options:
         layout = self.options['layout']
     else:
         layout = env.config.demo_layout
     if not self.layout_re.match(layout):
         return [doc.reporter.error("invalid layout specifier: %s" % layout,
                                    lineno=self.lineno)]
     order = []
     for block in layout.split(','):
         block = block.strip()
         is_hidden = block[0] == '-'
         block = block.lstrip('+-')
         order.append((block, is_hidden))
     wrapper = nodes.compound(classes=['demo-wrapper'])
     data = "\n".join(self.content)
     for block, is_hidden in order:
         if block == 'demo':
             header = nodes.paragraph(classes=['demo-header'])
             header += nodes.Text("Demo")
             if is_hidden:
                 header['classes'].append('demo-hide')
             demo = nodes.raw(data, data,
                              format='html',
                              classes=['demo-area'])
             html_wrapper = addnodes.only(expr='html')
             html_wrapper += header
             html_wrapper += demo
             wrapper += html_wrapper
         elif block == 'source':
             header = nodes.paragraph(classes=['demo-header'])
             header += nodes.Text("Source")
             if is_hidden:
                 header['classes'].append('demo-hide')
             source = nodes.literal_block(data, data,
                                          language='html',
                                          classes=['demo-source'])
             html_wrapper = addnodes.only(expr='html')
             html_wrapper += header
             wrapper += html_wrapper
             wrapper += source
         else:
             assert False, block
     return [wrapper]
 def run(self):
     # First argument is the name of the glyph
     alert_name = "alert-{}".format(self.custom_class)
     # get the label content
     text = "\n".join(self.content)
     # Create a new container element (div)
     new_element = nodes.compound(text)
     # Update its content
     self.state.nested_parse(self.content, self.content_offset, new_element)
     # Recurse inside its children and change the hyperlinks classes
     for child in new_element.traverse(include_self=False):
         if isinstance(child, nodes.reference):
             child.set_class("alert-link")
     # Set its custom bootstrap classes
     new_element["classes"] += ["alert ", alert_name]
     # Return one single element
     return [new_element]
示例#22
0
    def run(self):
        document = self.state.document
        if not document.settings.file_insertion_enabled:
            return [document.reporter.warning("File insertion disabled", line=self.lineno)]
        # convert options['diff'] to absolute a_path
        if "diff" in self.options:
            _, a_path = self.env.relfn2path(self.options["diff"])
            self.options["diff"] = a_path

        try:
            location = self.state_machine.get_source_and_line(self.lineno)
            rel_filename, filename = self.env.relfn2path(self.arguments[0])
            self.env.note_dependency(rel_filename)

            reader = LiteralIncludeReader(filename, self.options, self.config)
            text, lines = reader.read(location=location)

            retnode = nodes.literal_block(text, text, source=filename)
            set_source_info(self, retnode)
            if self.options.get("diff"):  # if diff is set, set udiff
                retnode["language"] = "udiff"
            elif "language" in self.options:
                retnode["language"] = self.options["language"]
            retnode["linenos"] = (
                "linenos" in self.options or "lineno-start" in self.options or "lineno-match" in self.options
            )
            retnode["classes"] += self.options.get("class", [])
            extra_args = retnode["highlight_args"] = {}
            if "emphasize-lines" in self.options:
                hl_lines = parselinenos(self.options["emphasize-lines"], lines)
                if any(i >= lines for i in hl_lines):
                    logger.warning(
                        "line number spec is out of range(1-%d): %r", lines, self.options["emphasize-lines"]
                    )
                extra_args["hl_lines"] = [x + 1 for x in hl_lines if x < lines]
            extra_args["linenostart"] = reader.lineno_start

            container_node = nodes.compound(classes=["example-block-wrapper"])
            container_node += ExampleHeader(filename=filename)
            container_node += retnode
            retnode = container_node

            return [retnode]
        except Exception as exc:
            return [document.reporter.warning(str(exc), line=self.lineno)]
示例#23
0
 def run(self):
     try:
         names = self.arguments[0].split()
         rst = '\n'.join([str(_PROD[name]) for name in names])
         self.arguments = [rst]
         p = nodes.compound()
         p['classes'] += ['dparser', 'admonition', 'collapse']
         title = nodes.paragraph()
         title['classes'] += ['first', 'admonition-title']
         title += nodes.Text(' '.join(names))
         body = ProductionList.run(self)[0]
         body['classes'] += ['last']
         p += [title, body]
         return [p]
     except KeyError as e:
         self.state.document.reporter.severe("Unknown nonterminal: " +
                                             str(e))
         return []
示例#24
0
    def run(self):
        self.assert_has_content()

        hidden_until = self.arguments[0]
        try:
            hidden_until = parse_date(hidden_until)
        except:
            raise self.error('Unknown date format in the "%s" directive; '
                             '%s' % (self.name, hidden_until))

        force_show = self.state.document.settings.force_show_hidden_until
        translation = _get_inginious_translation()

        after_deadline = hidden_until <= datetime.now()
        if after_deadline or force_show:
            output = []

            # Add a warning for teachers/tutors/...
            if not after_deadline and force_show:
                node = nodes.caution()
                self.add_name(node)
                text = translation.gettext(
                    "The feedback below will be hidden to the students until {}."
                ).format(hidden_until.strftime("%d/%m/%Y %H:%M:%S"))
                self.state.nested_parse(StringList(text.split("\n")), 0, node)
                output.append(node)

            text = '\n'.join(self.content)
            node = nodes.compound(text)
            self.add_name(node)
            self.state.nested_parse(self.content, self.content_offset, node)
            output.append(node)

            return output
        else:
            node = nodes.caution()
            self.add_name(node)
            text = translation.gettext(
                "A part of this feedback is hidden until {}. Please come back later and reload the submission to see the full feedback."
            ).format(hidden_until.strftime("%d/%m/%Y %H:%M:%S"))
            self.state.nested_parse(StringList(text.split("\n")), 0, node)
            return [node]
示例#25
0
    def run(self):
        """ returns an array of nodes for the tableofcontents directive declaration
        """
        ret = []
        wrappernode = nodes.compound(classes=["tableofcontents-wrapper"])
        self.add_name(wrappernode)
        depth = 0

        globaltoc = self._process_toc_dict(copy.deepcopy(
            self.config.globaltoc))

        # remove master_doc from the dict
        if "file" in globaltoc and globaltoc["file"] == self.config.master_doc:
            del globaltoc["file"]

        wncopy = wrappernode.deepcopy()
        self._has_toc_yaml(wncopy, globaltoc, depth)

        ret.append(wncopy)
        return ret
示例#26
0
 def run(self):
     pnode = nodes.compound(classes=['impl-detail'])
     label = translators['sphinx'].gettext(self.label_text)
     content = self.content
     add_text = nodes.strong(label, label)
     if self.arguments:
         n, m = self.state.inline_text(self.arguments[0], self.lineno)
         pnode.append(nodes.paragraph('', '', *(n + m)))
     self.state.nested_parse(content, self.content_offset, pnode)
     if pnode.children and isinstance(pnode[0], nodes.paragraph):
         content = nodes.inline(pnode[0].rawsource, translatable=True)
         content.source = pnode[0].source
         content.line = pnode[0].line
         content += pnode[0].children
         pnode[0].replace_self(
             nodes.paragraph('', '', content, translatable=False))
         pnode[0].insert(0, add_text)
         pnode[0].insert(1, nodes.Text(' '))
     else:
         pnode.insert(0, nodes.paragraph('', '', add_text))
     return [pnode]
示例#27
0
    def run(self):

        node = compound()
        dotted = self.arguments[0].split()[0]

        self.rst = [
            u'.. workflow-diagram::',
            u'   {}'.format(dotted),
            u''
            u'.. workflow-permissionmapping::',
            u'   {}'.format(dotted),
        ]

        result = ViewList()
        result.append(u'', self.directive)
        for r in self.rst:
            result.append(r, self.directive)
        result.append(u'', self.directive)

        self.state.nested_parse(result, 0, node)
        return node.children
示例#28
0
 def run(self):
     pnode = nodes.compound(classes=['impl-detail'])
     label = translators['sphinx'].gettext(self.label_text)
     content = self.content
     add_text = nodes.strong(label, label)
     if self.arguments:
         n, m = self.state.inline_text(self.arguments[0], self.lineno)
         pnode.append(nodes.paragraph('', '', *(n + m)))
     self.state.nested_parse(content, self.content_offset, pnode)
     if pnode.children and isinstance(pnode[0], nodes.paragraph):
         content = nodes.inline(pnode[0].rawsource, translatable=True)
         content.source = pnode[0].source
         content.line = pnode[0].line
         content += pnode[0].children
         pnode[0].replace_self(nodes.paragraph('', '', content,
                                               translatable=False))
         pnode[0].insert(0, add_text)
         pnode[0].insert(1, nodes.Text(' '))
     else:
         pnode.insert(0, nodes.paragraph('', '', add_text))
     return [pnode]
示例#29
0
def generate_sidebar(app, fromdocname):
    env = app.builder.env
    container = nodes.compound(classes=['toctree-wrapper'])#addnodes.compact_paragraph('', '', classes=['toctree-wrapper'])
    py = env.get_domain('py')
    classes = [_ for _ in py.get_objects() if _[2] == 'class']

    classes_per_group = {"modules": ([], 1), "provider": ([], 2), "core": ([], 1)}
    for e in classes:
        if e[0].startswith("src.provider."):
            group = "provider"
        elif e[0].startswith("src.main.") or e[0].startswith("src.utility."):
            group = "core"
        else:
            group = "modules"
        classes_per_group[group][0].append(e)

    generate_examples_sidebar(app, fromdocname, container)
    for key, items in classes_per_group.items():
        generate_collapsible_classlist(app, fromdocname, items[0], container, key.capitalize(), items[1])

    return container
 def run(self):
     env = self.state.document.settings.env
     output = []
     entries = []
     includefiles = []
     for entry in self.content:
         if not entry:
             continue
         docname = docname_join(env.docname, entry)
         if docname not in env.found_docs:
             output.append(
                 self.state.document.reporter.warning(
                     "feed contains a reference to nonexisting " "document %r" % docname, line=self.lineno
                 )
             )
             env.note_reread()
         else:
             output.append(self.state.document.reporter.warning("file exists %r" % docname, line=self.lineno))
             entries.append((None, docname))
             includefiles.append(docname)
     subnode = addnodes.toctree()
     subnode["parent"] = env.docname
     subnode["entries"] = entries
     subnode["includefiles"] = includefiles
     subnode["maxdepth"] = 1
     subnode["glob"] = False
     subnode["hidden"] = True
     subnode["numbered"] = False
     subnode["titlesonly"] = False
     wrappernode = nodes.compound(classes=["toctree-wrapper"])
     wrappernode.append(subnode)
     output.append(wrappernode)
     subnode = feed()
     subnode["entries"] = includefiles
     subnode["rss"] = self.options.get("rss")
     subnode["title"] = self.options.get("title", "")
     subnode["link"] = self.options.get("link", "")
     subnode["description"] = self.options.get("description", "")
     output.append(subnode)
     return output
示例#31
0
 def run(self):
     env = self.state.document.settings.env
     ret = []
     entries = []
     includefiles = []
     for entry in self.content:
         if not entry:
             continue
         docname = docname_join(env.docname, entry)
         if docname not in env.found_docs:
             ret.append(
                 self.state.document.reporter.warning(
                     'toctree contains reference to nonexisting '
                     'document %r' % docname,
                     line=self.lineno))
             env.note_reread()
         else:
             entries.append((None, docname))
             includefiles.append(docname)
     subnode = addnodes.toctree()
     subnode['parent'] = env.docname
     subnode['entries'] = entries
     subnode['includefiles'] = includefiles
     subnode['maxdepth'] = 1
     subnode['glob'] = False
     subnode['hidden'] = True
     subnode['numbered'] = False
     subnode['titlesonly'] = False
     wrappernode = nodes.compound(classes=['toctree-wrapper'])
     wrappernode.append(subnode)
     ret.append(wrappernode)
     subnode = blogtree()
     subnode['entries'] = includefiles
     subnode['output'] = self.options.get('output')
     subnode['title'] = self.options.get('title', '')
     subnode['link'] = self.options.get('link', '')
     subnode['description'] = self.options.get('description', '')
     ret.append(subnode)
     return ret
示例#32
0
    def run(self):
        self.assert_has_content()

        hidden_until = self.arguments[0]
        try:
            hidden_until = parse_date(hidden_until)
        except:
            raise self.error('Unknown date format in the "%s" directive; '
                             '%s' % (self.name, hidden_until))

        force_show = self.state.document.settings.force_show_hidden_until

        after_deadline = hidden_until <= datetime.now()
        if after_deadline or force_show:
            output = []

            # Add a warning for teachers/tutors/...
            if not after_deadline and force_show:
                node = nodes.caution()
                self.add_name(node)
                text = "The feedback below will be hidden to the students until %s." % hidden_until.strftime("%d/%m/%Y %H:%M:%S")
                self.state.nested_parse(StringList(text.split("\n")), 0, node)
                output.append(node)

            text = '\n'.join(self.content)
            node = nodes.compound(text)
            self.add_name(node)
            self.state.nested_parse(self.content, self.content_offset, node)
            output.append(node)

            return output
        else:
            node = nodes.caution()
            self.add_name(node)
            text = "A part of this feedback is hidden until %s. Please come back later and reload the submission to see the full feedback." % \
                   hidden_until.strftime("%d/%m/%Y %H:%M:%S")
            self.state.nested_parse(StringList(text.split("\n")), 0, node)
            return [node]
示例#33
0
    def apply(self):
        # toctrees will have a compound just before them
        toctrees = [
            ii for ii in self.document.traverse(compound)
            if "toctree-wrapper" in ii.attributes["classes"]
        ]

        # replacing all TableOfContentsNode with tocnode
        for index, tocnode in enumerate(
                self.document.traverse(TableOfContentsNode)):
            if len(toctrees) == 0:
                warn = f"Found tableofcontents directive in {self.env.docname}, but this file has no descendents."  # noqa: E501
                logger.warning(warn)

            # Replace the tableofcontents node with the page's toctree
            wrappernode = compound(classes=["tableofcontents-wrapper"])
            for itoc in toctrees:
                toctree = itoc.children[0].deepcopy()
                toctree.attributes["hidden"] = False
                if index == len(self.document.traverse(TableOfContentsNode)):
                    itoc.parent.remove(itoc)
                wrappernode.append(toctree)
            tocnode.replace_self(wrappernode)
示例#34
0
文件: other.py 项目: zwq000/sphinx
    def run(self) -> List[Node]:
        subnode = addnodes.toctree()
        subnode['parent'] = self.env.docname

        # (title, ref) pairs, where ref may be a document, or an external link,
        # and title may be None if the document's title is to be used
        subnode['entries'] = []
        subnode['includefiles'] = []
        subnode['maxdepth'] = self.options.get('maxdepth', -1)
        subnode['caption'] = self.options.get('caption')
        subnode['glob'] = 'glob' in self.options
        subnode['hidden'] = 'hidden' in self.options
        subnode['includehidden'] = 'includehidden' in self.options
        subnode['numbered'] = self.options.get('numbered', 0)
        subnode['titlesonly'] = 'titlesonly' in self.options
        self.set_source_info(subnode)
        wrappernode = nodes.compound(classes=['toctree-wrapper'])
        wrappernode.append(subnode)
        self.add_name(wrappernode)

        ret = self.parse_content(subnode)
        ret.append(wrappernode)
        return ret
示例#35
0
 def run(self):
     env = self.state.document.settings.env
     output = []
     entries = []
     includefiles = []
     for entry in self.content:
         if not entry:
             continue
         docname = docname_join(env.docname, entry)
         if docname not in env.found_docs:
             output.append(self.state.document.reporter.warning(
                 'feed contains a reference to nonexisting '
                 'document %r' % docname, line=self.lineno))
             env.note_reread()
         else:
             entries.append((None, docname))
             includefiles.append(docname)
     subnode = addnodes.toctree()
     subnode['parent'] = env.docname
     subnode['entries'] = entries
     subnode['includefiles'] = includefiles
     subnode['maxdepth'] = 1
     subnode['glob'] = False
     subnode['hidden'] = True
     subnode['numbered'] = False
     subnode['titlesonly'] = False
     wrappernode = nodes.compound(classes=['toctree-wrapper'])
     wrappernode.append(subnode)
     output.append(wrappernode)
     subnode = feed()
     subnode['entries'] = includefiles
     subnode['rss'] = self.options.get('rss')
     subnode['title'] = self.options.get('title', '')
     subnode['link'] = self.options.get('link', '')
     subnode['description'] = self.options.get('description', '')
     output.append(subnode)
     return output
示例#36
0
    def run(self):
        self.assert_has_content()

        hidden_until = self.arguments[0]
        try:
            hidden_until = parse_date(hidden_until)
        except:
            raise self.error('Unknown date format in the "%s" directive; '
                             '%s' % (self.name, hidden_until))

        if hidden_until <= datetime.now():
            text = '\n'.join(self.content)
            node = nodes.compound(text)
            self.add_name(node)

            self.state.nested_parse(self.content, self.content_offset, node)
            return [node]
        else:
            node = nodes.caution()
            self.add_name(node)
            text = "A part of this feedback is hidden until %s. Please come back later and reload the submission to see the full feedback." % \
                   hidden_until.strftime("%d/%m/%Y %H:%M:%S")
            self.state.nested_parse(StringList(text.split("\n")), 0, node)
            return [node]
示例#37
0
    def run(self):
        # type: () -> List[nodes.Node]
        subnode = addnodes.toctree()
        subnode['parent'] = self.env.docname

        # (title, ref) pairs, where ref may be a document, or an external link,
        # and title may be None if the document's title is to be used
        subnode['entries'] = []
        subnode['includefiles'] = []
        subnode['maxdepth'] = self.options.get('maxdepth', -1)
        subnode['caption'] = self.options.get('caption')
        subnode['glob'] = 'glob' in self.options
        subnode['hidden'] = 'hidden' in self.options
        subnode['includehidden'] = 'includehidden' in self.options
        subnode['numbered'] = self.options.get('numbered', 0)
        subnode['titlesonly'] = 'titlesonly' in self.options
        set_source_info(self, subnode)
        wrappernode = nodes.compound(classes=['toctree-wrapper'])
        wrappernode.append(subnode)
        self.add_name(wrappernode)

        ret = self.parse_content(subnode)
        ret.append(wrappernode)
        return ret
示例#38
0
def simple_compound(*items):
    """Return a compound node."""
    compound = nodes.compound()
    for item in items:
        compound.append(item)
    return compound
def process_feed(app, doctree, fromdocname):
    env = app.builder.env
    if env.config.disqus_shortname and doctree.traverse(entrymeta):
        node = disqus(classes=["feed-disqus"])
        node["shortname"] = env.config.disqus_shortname
        node["identifier"] = "/%s" % fromdocname
        node["title"] = env.titles[fromdocname][0]
        node["developer"] = env.config.disqus_developer
        doctree += node
    for node in doctree.traverse(feed):
        rss_filename = node["rss"]
        rss_title = node["title"]
        rss_link = node["link"]
        rss_description = node["description"]
        rss_date = datetime.datetime.utcnow()
        rss_items = []
        replacement = []
        for docname in node["entries"]:
            entry = env.get_doctree(docname)
            for meta in entry.traverse(entrymeta):
                section_node = nodes.section()
                title = env.titles[docname]
                section_node["ids"] = entry[0]["ids"]
                title_node = nodes.title()
                ref_node = nodes.reference(classes=["feed-ref"])
                ref_node["internal"] = True
                ref_node["refdocname"] = docname
                ref_node["refuri"] = app.builder.get_relative_uri(fromdocname, docname)
                ref_node["refuri"] += "#" + section_node["ids"][0]
                ref_node += title[0]
                title_node += ref_node
                section_node += title_node
                rss_item_title = "%s" % title[0]
                rss_item_link = rss_link + app.builder.get_target_uri(docname)
                rss_item_description = nodes.compound()
                for subnode in entry[0]:
                    if isinstance(subnode, (nodes.title, disqus)):
                        continue
                    if isinstance(subnode, entrycut):
                        para_node = nodes.paragraph()
                        ref_node = nodes.reference(classes=["feed-more"])
                        ref_node["internal"] = True
                        ref_node["refdocname"] = docname
                        ref_node["refuri"] = app.builder.get_relative_uri(fromdocname, docname)
                        ref_node["refuri"] += "#" + section_node["ids"][0]
                        ref_node += nodes.Text("Read more\u2026")
                        para_node += ref_node
                        section_node += para_node
                        break
                    section_node += subnode.deepcopy()
                    if isinstance(subnode, entrymeta):
                        continue
                    rss_item_description += subnode.deepcopy()
                env.resolve_references(section_node, fromdocname, app.builder)
                replacement.append(section_node)
                env.resolve_references(rss_item_description, docname, app.builder)
                if app.builder.format == "html":
                    rss_item_description = app.builder.render_partial(rss_item_description)["body"]
                    rss_item_date = meta["date"]
                    rss_item = RSSItem(rss_item_title, rss_item_link, rss_item_description, rss_item_date)
                    rss_items.append(rss_item)
        node.replace_self(replacement)
        if app.builder.format == "html":
            rss_feed = RSSFeed(rss_title, rss_link, rss_description, rss_date, rss_items)
            if rss_filename:
                rss_path = os.path.join(app.builder.outdir, rss_filename)
                rss_stream = open(rss_path, "wb")
                write_rss(rss_feed, rss_stream)
                rss_stream.close()
示例#40
0
    def run(self):
        self.assert_has_content()

        node = nodes.compound('\n'.join(self.content), names=[self.arguments[0]])
        self.state.nested_parse(self.content, self.content_offset, node)
        return [node]
示例#41
0
    def run(self):
        env = self.state.document.settings.env
        stat_example = None
        stat_group, stat_name, stat_type = self.arguments[0:3]
        if (len(self.arguments) > 3):
            stat_example = self.arguments[3]

        # First, make a generic desc() node to be the parent.
        node = sphinx.addnodes.desc()
        node.document = self.state.document
        node['objtype'] = 'stat'

        # Next, make a signature node. This creates a permalink and a
        # highlighted background when the link is selected.
        title = sphinx.addnodes.desc_signature(stat_name, '')
        title['ids'].append(nodes.make_id('stat-' + stat_name))
        title['names'].append(stat_name)
        title['first'] = False
        title['objtype'] = 'stat'
        self.add_name(title)
        title.set_class('ts-stat-title')

        # Finally, add a desc_name() node to display the name of the
        # configuration variable.
        title += sphinx.addnodes.desc_name(stat_name, stat_name)

        node.append(title)

        # This has to be a distinct node before the title. if nested then
        # the browser will scroll forward to just past the title.
        anchor = nodes.target('', '', names=[stat_name])
        # Second (optional) arg is 'msgNode' - no idea what I should pass for that
        # or if it even matters, although I now think it should not be used.
        self.state.document.note_explicit_target(title)
        env.domaindata['ts']['stat'][stat_name] = env.docname

        fl = nodes.field_list()
        fl.append(self.make_field('Collection', stat_group))
        if ('type' in self.options):
            fl.append(self.make_field('Type', self.options['type']))
        if ('unit' in self.options):
            fl.append(self.make_field('Units', self.options['unit']))
        fl.append(self.make_field('Datatype', stat_type))
        if ('introduced' in self.options
                and len(self.options['introduced']) > 0):
            fl.append(self.make_field('Introduced',
                                      self.options['introduced']))
        if ('deprecated' in self.options):
            if (len(self.options['deprecated']) > 0):
                fl.append(
                    self.make_field('Deprecated', self.options['deprecated']))
            else:
                fl.append(self.make_field('Deprecated', 'Yes'))
        if ('ungathered' in self.options):
            fl.append(self.make_field('Gathered', 'No'))
        if (stat_example):
            fl.append(self.make_field('Example', stat_example))

        # Get any contained content
        nn = nodes.compound()
        self.state.nested_parse(self.content, self.content_offset, nn)

        # Create an index node so that Sphinx adds this statistic to the
        # index. nodes.make_id() specifies the link anchor name that is
        # implicitly generated by the anchor node above.
        indexnode = sphinx.addnodes.index(entries=[])

        if sphinx.version_info >= (1, 4):
            indexnode['entries'].append(('single', _('%s') % stat_name,
                                         nodes.make_id(stat_name), '', ''))
        else:
            indexnode['entries'].append(
                ('single', _('%s') % stat_name, nodes.make_id(stat_name), ''))

        return [indexnode, node, fl, nn]
示例#42
0
文件: other.py 项目: nwf/sphinx
    def run(self):
        # type: () -> List[nodes.Node]
        env = self.state.document.settings.env
        suffixes = env.config.source_suffix
        glob = 'glob' in self.options

        ret = []
        # Children of the internal toctree node; these will be rewritten by
        # traversals (and so having other references into these will also
        # get rewritten) but, nicely, are not rendered directly due to the
        # way that the environment code deals with toctrees.
        others = []
        # (title, ref) pairs, where ref may be a document, or an external link,
        # or a node.  title may be None if the document's title is to be used
        # and must be None if a node is given as a ref.
        entries = []  # type: List[Tuple[unicode, Union[unicode,nodes.Node]]]
        includefiles = []
        all_docnames = env.found_docs.copy()
        # don't add the currently visited file in catch-all patterns
        all_docnames.remove(env.docname)
        for entry in self.content:
            if not entry:
                continue
            if entry.startswith("_ "):
                node = nodes.paragraph()
                self.state.nested_parse(ViewList([entry[2:]]), 0, node)
                others.append(node)
                entries.append((None, node))
            elif glob and ('*' in entry or '?' in entry or '[' in entry):
                patname = docname_join(env.docname, entry)
                docnames = sorted(patfilter(all_docnames, patname))
                for docname in docnames:
                    all_docnames.remove(docname)  # don't include it again
                    entries.append((None, docname))
                    includefiles.append(docname)
                if not docnames:
                    ret.append(
                        self.state.document.reporter.warning(
                            'toctree glob pattern %r didn\'t match any documents'
                            % entry,
                            line=self.lineno))
            else:
                # look for explicit titles ("Some Title <document>")
                m = explicit_title_re.match(entry)
                if m:
                    ref = m.group(2)
                    title = m.group(1)
                    docname = ref
                else:
                    ref = docname = entry
                    title = None
                # remove suffixes (backwards compatibility)
                for suffix in suffixes:
                    if docname.endswith(suffix):
                        docname = docname[:-len(suffix)]
                        break
                # absolutize filenames
                docname = docname_join(env.docname, docname)
                if url_re.match(ref) or ref == 'self':
                    entries.append((title, ref))
                elif docname not in env.found_docs:
                    ret.append(
                        self.state.document.reporter.warning(
                            'toctree contains reference to nonexisting '
                            'document %r' % docname,
                            line=self.lineno))
                    env.note_reread()
                else:
                    all_docnames.discard(docname)
                    entries.append((title, docname))
                    includefiles.append(docname)
        subnode = addnodes.toctree()
        subnode['parent'] = env.docname
        # entries contains all entries (self references, external links etc.)
        if 'reversed' in self.options:
            entries.reverse()
        subnode['entries'] = entries
        # includefiles only entries that are documents
        subnode['includefiles'] = includefiles
        subnode['maxdepth'] = self.options.get('maxdepth', -1)
        subnode['caption'] = self.options.get('caption')
        subnode['glob'] = glob
        subnode['hidden'] = 'hidden' in self.options
        subnode['includehidden'] = 'includehidden' in self.options
        subnode['numbered'] = self.options.get('numbered', 0)
        subnode['titlesonly'] = 'titlesonly' in self.options
        subnode.children = others
        set_source_info(self, subnode)
        wrappernode = nodes.compound(classes=['toctree-wrapper'])
        wrappernode.append(subnode)
        self.add_name(wrappernode)
        ret.append(wrappernode)
        return ret
示例#43
0
def my_toctree_run(self):
    """Show non existing entries of toctree

    Used to replace the function -> sphinx.directives.other.TocTree.run

    Only %r following are replaced %s to avoid unreadable string.
    """
    env = self.state.document.settings.env
    suffix = env.config.source_suffix
    glob = 'glob' in self.options

    ret = []
    # (title, ref) pairs, where ref may be a document, or an external link,
    # and title may be None if the document's title is to be used
    entries = []
    includefiles = []
    all_docnames = env.found_docs.copy()
    # don't add the currently visited file in catch-all patterns
    all_docnames.remove(env.docname)
    for entry in self.content:
        if not entry:
            continue
        if not glob:
            # look for explicit titles ("Some Title <document>")
            m = explicit_title_re.match(entry)
            if m:
                ref = m.group(2)
                title = m.group(1)
                docname = ref
            else:
                ref = docname = entry
                title = None
            # remove suffixes (backwards compatibility)
            if docname.endswith(suffix):
                docname = docname[:-len(suffix)]
            # absolutize filenames
            docname = docname_join(env.docname, docname)
            if url_re.match(ref) or ref == 'self':
                entries.append((title, ref))
            elif docname not in env.found_docs:
                ret.append(self.state.document.reporter.warning(
                    u'toctree contains reference to nonexisting '
                    u'document %s' % docname, line=self.lineno))
                env.note_reread()
            else:
                entries.append((title, docname))
                includefiles.append(docname)
        else:
            patname = docname_join(env.docname, entry)
            docnames = sorted(patfilter(all_docnames, patname))
            for docname in docnames:
                all_docnames.remove(docname) # don't include it again
                entries.append((None, docname))
                includefiles.append(docname)
            if not docnames:
                ret.append(self.state.document.reporter.warning(
                    'toctree glob pattern %s didn\'t match any documents'
                    % entry, line=self.lineno))
    subnode = addnodes.toctree()
    subnode['parent'] = env.docname
    # entries contains all entries (self references, external links etc.)
    subnode['entries'] = entries
    # includefiles only entries that are documents
    subnode['includefiles'] = includefiles
    subnode['maxdepth'] = self.options.get('maxdepth', -1)
    subnode['glob'] = glob
    subnode['hidden'] = 'hidden' in self.options
    subnode['numbered'] = 'numbered' in self.options
    subnode['titlesonly'] = 'titlesonly' in self.options
    wrappernode = nodes.compound(classes=['toctree-wrapper'])
    wrappernode.append(subnode)
    ret.append(wrappernode)
    return ret
示例#44
0
def process_feed(app, doctree, fromdocname):
    env = app.builder.env
    if env.config.disqus_shortname and doctree.traverse(entrymeta):
        node = disqus(classes=['feed-disqus'])
        node['shortname'] = env.config.disqus_shortname
        node['identifier'] = "/%s" % fromdocname
        node['title'] = env.titles[fromdocname][0]
        node['developer'] = env.config.disqus_developer
        doctree += node
    for node in doctree.traverse(feed):
        rss_filename = node['rss']
        rss_title = node['title']
        rss_link = node['link']
        rss_description = node['description']
        rss_date = datetime.datetime.utcnow()
        rss_items = []
        replacement = []
        for docname in node['entries']:
            entry = env.get_doctree(docname)
            for meta in entry.traverse(entrymeta):
                section_node = nodes.section()
                title = env.titles[docname]
                section_node['ids'] = entry[0]['ids']
                title_node = nodes.title()
                ref_node = nodes.reference(classes=['feed-ref'])
                ref_node['internal'] = True
                ref_node['refdocname'] = docname
                ref_node['refuri'] = \
                        app.builder.get_relative_uri(fromdocname, docname)
                ref_node['refuri'] += '#' + section_node['ids'][0]
                ref_node += title[0]
                title_node += ref_node
                section_node += title_node
                rss_item_title = "%s" % title[0]
                rss_item_link = rss_link+app.builder.get_target_uri(docname)
                rss_item_description = nodes.compound()
                for subnode in entry[0]:
                    if isinstance(subnode, (nodes.title, disqus)):
                        continue
                    if isinstance(subnode, entrycut):
                        para_node = nodes.paragraph()
                        ref_node = nodes.reference(classes=['feed-more'])
                        ref_node['internal'] = True
                        ref_node['refdocname'] = docname
                        ref_node['refuri'] = \
                                app.builder.get_relative_uri(fromdocname, docname)
                        ref_node['refuri'] += '#' + section_node['ids'][0]
                        ref_node += nodes.Text('Read more\u2026')
                        para_node += ref_node
                        section_node += para_node
                        break
                    section_node += subnode.deepcopy()
                    if isinstance(subnode, entrymeta):
                        continue
                    rss_item_description += subnode.deepcopy()
                env.resolve_references(section_node, fromdocname, app.builder)
                replacement.append(section_node)
                env.resolve_references(rss_item_description, docname, app.builder)
                rss_item_description = app.builder.render_partial(
                                                rss_item_description)['body']
                rss_item_date = meta['date']
                rss_item = RSSItem(rss_item_title, rss_item_link,
                                   rss_item_description, rss_item_date)
                rss_items.append(rss_item)
        node.replace_self(replacement)
        rss_feed = RSSFeed(rss_title, rss_link, rss_description,
                           rss_date, rss_items)
        if rss_filename:
            rss_path = os.path.join(app.builder.outdir, rss_filename)
            rss_stream = open(rss_path, 'wb')
            write_rss(rss_feed, rss_stream)
            rss_stream.close()
示例#45
0
    def run(self):
        env = self.state.document.settings.env
        suffix = env.config.source_suffix
        glob = 'glob' in self.options

        ret = []
        # (title, ref) pairs, where ref may be a document, or an external link,
        # and title may be None if the document's title is to be used
        entries = []
        includefiles = []
        all_docnames = env.found_docs.copy()
        # don't add the currently visited file in catch-all patterns
        all_docnames.remove(env.docname)
        for entry in self.content:
            if not entry:
                continue
            if not glob:
                # look for explicit titles ("Some Title <document>")
                m = explicit_title_re.match(entry)
                if m:
                    ref = m.group(2)
                    title = m.group(1)
                    docname = ref
                else:
                    ref = docname = entry
                    title = None
                # remove suffixes (backwards compatibility)
                if docname.endswith(suffix):
                    docname = docname[:-len(suffix)]
                # absolutize filenames
                docname = docname_join(env.docname, docname)
                if url_re.match(ref) or ref == 'self':
                    entries.append((title, ref))
                elif docname not in env.found_docs:
                    ret.append(
                        self.state.document.reporter.warning(
                            'toctree contains reference to nonexisting '
                            'document %r' % docname,
                            line=self.lineno))
                    env.note_reread()
                else:
                    entries.append((title, docname))
                    includefiles.append(docname)
            else:
                patname = docname_join(env.docname, entry)
                docnames = sorted(patfilter(all_docnames, patname))
                for docname in docnames:
                    all_docnames.remove(docname)  # don't include it again
                    entries.append((None, docname))
                    includefiles.append(docname)
                if not docnames:
                    ret.append(
                        self.state.document.reporter.warning(
                            'toctree glob pattern %r didn\'t match any documents'
                            % entry,
                            line=self.lineno))
        subnode = addnodes.toctree()
        subnode['parent'] = env.docname
        # entries contains all entries (self references, external links etc.)
        subnode['entries'] = entries
        # includefiles only entries that are documents
        subnode['includefiles'] = includefiles
        subnode['maxdepth'] = self.options.get('maxdepth', -1)
        subnode['glob'] = glob
        subnode['hidden'] = 'hidden' in self.options
        subnode['numbered'] = self.options.get('numbered', 0)
        subnode['titlesonly'] = 'titlesonly' in self.options
        set_source_info(self, subnode)
        wrappernode = nodes.compound(classes=['toctree-wrapper'])
        wrappernode.append(subnode)
        ret.append(wrappernode)
        return ret
class Latest(Directive):
    """
    Directive to notify Sphinx about the hierarchical structure of the docs,
    and to include a table-of-contents like tree in the current document.
    """
    has_content = True
    required_arguments = 0
    optional_arguments = 0
    final_argument_whitespace = False
    option_spec = {
        'maxdepth': int,
        'limit': int,
        'glob': directives.flag,
        'hidden': directives.flag,
        'numbered': int_or_nothing,
        'titlesonly': directives.flag,
    }

    def run(self):
        env = self.state.document.settings.env
        suffix = env.config.source_suffix
        glob = 'glob' in self.options
        limit = 'limit' in self.options

        ret = []
        # (title, ref) pairs, where ref may be a document, or an external link,
        # and title may be None if the document's title is to be used
        entries = []
        includefiles = []
        all_docnames = env.found_docs.copy()
        # don't add the currently visited file in catch-all patterns
        all_docnames.remove(env.docname)
        for entry in self.content:
            if not entry:
                continue
            if not glob:
                # look for explicit titles ("Some Title <document>")
                m = explicit_title_re.match(entry)
                if m:
                    ref = m.group(2)
                    title = m.group(1)
                    docname = ref
                else:
                    ref = docname = entry
                    title = None
                # remove suffixes (backwards compatibility)
                if docname.endswith(suffix):
                    docname = docname[:-len(suffix)]
                # absolutize filenames
                docname = docname_join(env.docname, docname)
                if url_re.match(ref) or ref == 'self':
                    entries.append((title, ref))
                elif docname not in env.found_docs:
                    ret.append(
                        self.state.document.reporter.warning(
                            'toctree contains reference to nonexisting '
                            'document %r' % docname,
                            line=self.lineno))
                    env.note_reread()
                else:
                    entries.append((title, docname))
                    includefiles.append(docname)
            else:
                patname = docname_join(env.docname, entry)
                docnames = sorted(patfilter(all_docnames, patname))
                for docname in docnames:
                    all_docnames.remove(docname)  # don't include it again
                    entries.append((None, docname))
                    includefiles.append(docname)
                if not docnames:
                    ret.append(
                        self.state.document.reporter.warning(
                            'toctree glob pattern %r didn\'t match any documents'
                            % entry,
                            line=self.lineno))

        sorted_entries = {}
        for entry in entries:
            metadata = env.metadata.get(entry[1], {})

            if 'date' not in metadata:
                continue
            try:
                pub_date = parse_date(metadata['date'])
                env.metadata.get(entry[1], {})
            except ValueError, exc:
                continue

            sorted_entries[pub_date.isoformat()] = entry

        ordered_keys = sorted_entries.keys()
        ordered_keys.sort(reverse=True)

        subnode = addnodes.toctree()
        subnode['parent'] = env.docname
        # entries contains all entries (self references, external links etc.)
        subnode['entries'] = []
        for date in ordered_keys:
            subnode['entries'].append(sorted_entries[date])

        if limit:
            del subnode['entries'][self.options.get('limit'
                                                    ):len(subnode['entries'])]

        # includefiles only entries that are documents
        subnode['includefiles'] = includefiles
        subnode['maxdepth'] = self.options.get('maxdepth', -1)

        subnode['glob'] = glob
        subnode['hidden'] = 'hidden' in self.options
        subnode['numbered'] = self.options.get('numbered', 0)
        subnode['titlesonly'] = 'titlesonly' in self.options
        wrappernode = nodes.compound(classes=['toctree-wrapper'])
        wrappernode.append(subnode)
        ret.append(wrappernode)
        return ret
示例#47
0
def process_blogtree(app, doctree, fromdocname):
    env = app.builder.env
    if env.config.disqus_shortname and doctree.traverse(published_para):
        node = disqus(classes=['blog-disqus'])
        node['shortname'] = env.config.disqus_shortname
        node['identifier'] = "/%s" % fromdocname
        node['title'] = env.titles[fromdocname][0]
        node['developer'] = env.config.disqus_developer
        doctree += node
    for node in doctree.traverse(blogtree):
        rss_output = node['output']
        rss_title = node['title']
        rss_link = node['link']
        rss_description = node['description']
        rss_items = []
        replacement = []
        for docname in node['entries']:
            blogentry = env.get_doctree(docname)
            for published in blogentry.traverse(published_para):
                section_node = nodes.section()
                title = env.titles[docname]
                section_node['ids'] = blogentry[0]['ids']
                author = published['author']
                date = published['date']
                title_node = nodes.title()
                ref_node = nodes.reference(classes=['blog-ref'])
                ref_node['internal'] = True
                ref_node['refdocname'] = docname
                ref_node['refuri'] = \
                        app.builder.get_relative_uri(fromdocname, docname)
                ref_node['refuri'] += '#' + section_node['ids'][0]
                ref_node += title[0]
                title_node += ref_node
                section_node += title_node
                para_node = nodes.paragraph(classes=['blog-published'])
                para_node += nodes.Text(u'Published')
                if author:
                    para_node += nodes.Text(u' by ')
                    author_node = nodes.emphasis(classes=['blog-author'])
                    author_node += nodes.Text(author)
                    para_node += author_node
                if date:
                    para_node += nodes.Text(u' on ')
                    date_node = nodes.emphasis(classes=['blog-date'])
                    date_node += nodes.Text(date)
                    para_node += date_node
                section_node += para_node
                for subnode in blogentry[0]:
                    if isinstance(subnode,
                                  (nodes.title, published_para, disqus)):
                        continue
                    if isinstance(subnode, blogcut):
                        para_node = nodes.paragraph()
                        ref_node = nodes.reference(classes=['blog-more'])
                        ref_node['internal'] = True
                        ref_node['refdocname'] = docname
                        ref_node['refuri'] = \
                                app.builder.get_relative_uri(fromdocname, docname)
                        ref_node['refuri'] += '#' + section_node['ids'][0]
                        ref_node += nodes.Text(u'Read more\u2026')
                        para_node += ref_node
                        section_node += para_node
                        break
                    section_node += subnode.deepcopy()
                env.resolve_references(section_node, fromdocname, app.builder)
                replacement.append(section_node)
                if rss_output:
                    rss_item_title = title[0]
                    rss_item_link = rss_link + app.builder.get_target_uri(
                        docname)
                    rss_item_description = nodes.compound()
                    for subnode in blogentry[0]:
                        if isinstance(subnode,
                                      (nodes.title, published_para, disqus)):
                            continue
                        if isinstance(subnode, blogcut):
                            break
                        rss_item_description += subnode.deepcopy()
                    env.resolve_references(rss_item_description, docname,
                                           app.builder)
                    rss_item_description = app.builder.render_partial(
                        rss_item_description)['body']
                    if date:
                        match = re.match(r'^(\d{4})-(\d{2})-(\d{2})$', date)
                        assert match is not None
                        rss_item_date = datetime.datetime(
                            int(match.group(1)), int(match.group(2)),
                            int(match.group(3)))
                    rss_item = PyRSS2Gen.RSSItem(
                        title=rss_item_title,
                        link=rss_item_link,
                        description=rss_item_description,
                        guid=PyRSS2Gen.Guid(rss_item_link),
                        pubDate=rss_item_date)
                    rss_items.append(rss_item)
        node.replace_self(replacement)
        if rss_output:
            rss_path = os.path.join(app.builder.outdir, rss_output)
            rss = PyRSS2Gen.RSS2(title=rss_title,
                                 link=rss_link,
                                 description=rss_description,
                                 lastBuildDate=datetime.datetime.utcnow(),
                                 items=rss_items)
            rss.write_xml(open(rss_path, "w"), encoding="utf-8")
示例#48
0
    def run(self):
        env = self.state.document.settings.env
        stat_example = None
        stat_group, stat_name, stat_type = self.arguments[0:3]
        if (len(self.arguments) > 3):
            stat_example = self.arguments[3]

        # First, make a generic desc() node to be the parent.
        node = sphinx.addnodes.desc()
        node.document = self.state.document
        node['objtype'] = 'stat'

        # Next, make a signature node. This creates a permalink and a
        # highlighted background when the link is selected.
        title = sphinx.addnodes.desc_signature(stat_name, '')
        title['ids'].append(nodes.make_id('stat-'+stat_name))
        title['names'].append(stat_name)
        title['first'] = False
        title['objtype'] = 'stat'
        self.add_name(title)
        title.set_class('ts-stat-title')

        # Finally, add a desc_name() node to display the name of the
        # configuration variable.
        title += sphinx.addnodes.desc_name(stat_name, stat_name)

        node.append(title)

        # This has to be a distinct node before the title. if nested then
        # the browser will scroll forward to just past the title.
        anchor = nodes.target('', '', names=[stat_name])
        # Second (optional) arg is 'msgNode' - no idea what I should pass for that
        # or if it even matters, although I now think it should not be used.
        self.state.document.note_explicit_target(title)
        env.domaindata['ts']['stat'][stat_name] = env.docname

        fl = nodes.field_list()
        fl.append(self.make_field('Collection', stat_group))
        if ('type' in self.options):
            fl.append(self.make_field('Type', self.options['type']))
        if ('unit' in self.options):
            fl.append(self.make_field('Units', self.options['unit']))
        fl.append(self.make_field('Datatype', stat_type))
        if ('introduced' in self.options and len(self.options['introduced']) > 0):
            fl.append(self.make_field('Introduced', self.options['introduced']))
        if ('deprecated' in self.options):
            if (len(self.options['deprecated']) > 0):
                fl.append(self.make_field('Deprecated', self.options['deprecated']))
            else:
                fl.append(self.make_field('Deprecated', 'Yes'))
        if ('ungathered' in self.options):
            fl.append(self.make_field('Gathered', 'No'))
        if (stat_example):
            fl.append(self.make_field('Example', stat_example))

        # Get any contained content
        nn = nodes.compound();
        self.state.nested_parse(self.content, self.content_offset, nn)

        # Create an index node so that Sphinx adds this statistic to the
        # index. nodes.make_id() specifies the link anchor name that is
        # implicitly generated by the anchor node above.
        indexnode = sphinx.addnodes.index(entries=[])
        indexnode['entries'].append(
            ('single', _('%s') % stat_name, nodes.make_id(stat_name), '')
        )

        return [ indexnode, node, fl, nn ]
示例#49
0
def process_feed(app, doctree, fromdocname):
    env = app.builder.env
    if env.config.disqus_shortname and doctree.traverse(entrymeta):
        node = disqus(classes=['feed-disqus'])
        node['shortname'] = env.config.disqus_shortname
        node['identifier'] = "/%s" % fromdocname
        node['title'] = env.titles[fromdocname][0]
        node['developer'] = env.config.disqus_developer
        doctree += node
    for node in doctree.traverse(feed):
        rss_filename = node['rss']
        rss_title = node['title']
        rss_link = node['link']
        rss_description = node['description']
        rss_date = datetime.datetime.utcnow()
        rss_items = []
        replacement = []
        for docname in node['entries']:
            entry = env.get_doctree(docname)
            for meta in entry.traverse(entrymeta):
                section_node = nodes.section()
                title = env.titles[docname]
                section_node['ids'] = entry[0]['ids']
                title_node = nodes.title()
                ref_node = nodes.reference(classes=['feed-ref'])
                ref_node['internal'] = True
                ref_node['refdocname'] = docname
                ref_node['refuri'] = \
                        app.builder.get_relative_uri(fromdocname, docname)
                ref_node['refuri'] += '#' + section_node['ids'][0]
                ref_node += title[0]
                title_node += ref_node
                section_node += title_node
                rss_item_title = "%s" % title[0]
                rss_item_link = rss_link + app.builder.get_target_uri(docname)
                rss_item_description = nodes.compound()
                for subnode in entry[0]:
                    if isinstance(subnode, (nodes.title, disqus)):
                        continue
                    if isinstance(subnode, entrycut):
                        para_node = nodes.paragraph()
                        ref_node = nodes.reference(classes=['feed-more'])
                        ref_node['internal'] = True
                        ref_node['refdocname'] = docname
                        ref_node['refuri'] = \
                                app.builder.get_relative_uri(fromdocname, docname)
                        ref_node['refuri'] += '#' + section_node['ids'][0]
                        ref_node += nodes.Text('Read more\u2026')
                        para_node += ref_node
                        section_node += para_node
                        break
                    section_node += subnode.deepcopy()
                    if isinstance(subnode, entrymeta):
                        continue
                    rss_item_description += subnode.deepcopy()
                env.resolve_references(section_node, fromdocname, app.builder)
                replacement.append(section_node)
                env.resolve_references(rss_item_description, docname,
                                       app.builder)
                if app.builder.format == 'html':
                    rss_item_description = app.builder.render_partial(
                        rss_item_description)['body']
                    rss_item_date = meta['date']
                    rss_item = RSSItem(rss_item_title, rss_item_link,
                                       rss_item_description, rss_item_date)
                    rss_items.append(rss_item)
        node.replace_self(replacement)
        if app.builder.format == 'html':
            rss_feed = RSSFeed(rss_title, rss_link, rss_description, rss_date,
                               rss_items)
            if rss_filename:
                rss_path = os.path.join(app.builder.outdir, rss_filename)
                rss_stream = open(rss_path, 'wb')
                write_rss(rss_feed, rss_stream)
                rss_stream.close()
def process_feed(app, doctree, fromdocname):
    env = app.builder.env
    document = new_document('')

    for node in doctree.traverse(feed):
        rss_filename = node['rss']
        rss_title = node['title']
        rss_link = node['link']
        rss_description = node['description']
        rss_date = datetime.datetime.utcnow()
        rss_items = []
        for docname in node['entries']:
            entry = env.get_doctree(docname)

            for field in entry.traverse(nodes.field):
                field_date = [f for f in field.traverse(nodes.field_name)][0]
                pars = []
                for b in field.traverse(nodes.field_body):
                    for p in b.traverse(nodes.paragraph):
                        pars.append(p)

                rss_item_description = nodes.compound()
                for p in pars[1:]:
                    rss_item_description += p.deepcopy()

                document += rss_item_description
                app.env.resolve_references(
                    document,
                    node['link'],
                    app.builder,
                )
                document.remove(rss_item_description)

                if app.builder.format == 'html':
                    rss_item_description = "\n".join(
                        app.builder.render_partial(p)['body']
                        for p in rss_item_description
                    )
                    rss_item_date = dateutil.parser.parse(field_date.astext().strip())
                    rss_item_title = "%s: %s" % (field_date.astext(), pars[0].astext())
                    rss_item = RSSItem(
                        rss_item_title,
                        node['link'],
                        rss_item_description,
                        rss_item_date,
                    )
                    rss_items.append(rss_item)

        node.replace_self([])

        if app.builder.format == 'html':
            rss_feed = RSSFeed(
                rss_title,
                rss_link,
                rss_description,
                rss_date,
                rss_items,
            )
            if rss_filename:
                rss_path = os.path.join(app.builder.outdir, rss_filename)
                with open(rss_path, 'wb') as rss_stream:
                    write_rss(rss_feed, rss_stream)
示例#51
0
 def run(self):
     env = self.state.document.settings.env
     suffix = env.config.source_suffix
     glob = 'glob' in self.options
             
     # (title, ref) pairs, where ref may only be a document
     # external links are forbidden, since we have no way of dating them
     # and title may be None if the document's title is to be used
     entries = []
     includefiles = []
     
     all_docnames = env.found_docs.copy()
     # don't add the currently visited file in catch-all patterns
     all_docnames.remove(env.docname)
     
     ret = []
     
     for entry in self.content:
         if not entry:
             continue
         if not glob:
             # look for explicit titles ("Some Title <document>")
             m = explicit_title_re.match(entry)
             if m:
                 ref = m.group(2)
                 title = m.group(1)
                 docname = ref
             else:
                 ref = docname = entry
                 title = None
             # remove suffixes (backwards compatibility)
             if docname.endswith(suffix):
                 docname = docname[:-len(suffix)]
             # absolutize filenames
             docname = docname_join(env.docname, docname)
             if url_re.match(ref) or ref == 'self':
                 entries.append((title, ref))
             elif docname not in env.found_docs:
                 ret.append(self.state.document.reporter.warning(
                     'toctree contains reference to nonexisting '
                     'document %r' % docname, line=self.lineno))
                 env.note_reread()
             else:
                 entries.append((title, docname))
                 includefiles.append(docname)
         else:
             patname = docname_join(env.docname, entry)
             docnames = patfilter(all_docnames, patname)
             for docname in docnames:
                 all_docnames.remove(docname) # don't include it again
                 entries.append((None, docname))
                 includefiles.append(docname)
             if not docnames:
                 ret.append(self.state.document.reporter.warning(
                     'latest list glob pattern %r didn\'t match any documents'
                     % entry, line=self.lineno))
     
     subnode = latest()
     subnode['parent'] = env.docname
     # entries contains all entries (self references, external links etc.)
     subnode['entries'] = entries
     # includefiles only entries that are documents
     subnode['includefiles'] = includefiles
     subnode['maxdepth'] = self.options.get('maxdepth', -1)
     subnode['glob'] = glob
     subnode['titlesonly'] = 'titlesonly' in self.options
     #what does this do?
     set_source_info(self, subnode)
     wrappernode = nodes.compound(classes=['feed-latest-wrapper'])
     wrappernode.append(subnode)
     ret.append(wrappernode)
     return ret
示例#52
0
    def run(self):
        env = self.state.document.settings.env
        suffixes = env.config.source_suffix
        glob = 'glob' in self.options

        ret = []
        # (title, ref) pairs, where ref may be a document, or an external link,
        # and title may be None if the document's title is to be used
        entries = []
        includefiles = []
        all_docnames = env.found_docs.copy()
        # don't add the currently visited file in catch-all patterns
        try:
            all_docnames.remove(env.docname)
        except KeyError:
            if env.docname == "<<string>>":
                # This comes from rst2html.
                pass
            else:
                logger = logging.getLogger("CustomTocTreeCollector")
                logger.warning(
                    "[CustomTocTreeCollector] unable to remove document '{0}' from {1}"
                    .format(env.docname, ", ".join(all_docnames)))

        for entry in self.content:
            if not entry:
                continue
            if glob and ('*' in entry or '?' in entry or '[' in entry):
                patname = docname_join(env.docname, entry)
                docnames = sorted(patfilter(all_docnames, patname))
                for docname in docnames:
                    all_docnames.remove(docname)  # don't include it again
                    entries.append((None, docname))
                    includefiles.append(docname)
                if not docnames:
                    ret.append(
                        self.state.document.reporter.warning(
                            '[CustomTocTree] glob pattern %r didn\'t match any documents'
                            % entry,
                            line=self.lineno))
            else:
                # look for explicit titles ("Some Title <document>")
                m = explicit_title_re.match(entry)
                if m:
                    ref = m.group(2)
                    title = m.group(1)
                    docname = ref
                else:
                    ref = docname = entry
                    title = None
                # remove suffixes (backwards compatibility)
                for suffix in suffixes:
                    if docname.endswith(suffix):
                        docname = docname[:-len(suffix)]
                        break
                # absolutize filenames
                docname = docname_join(env.docname, docname)
                if url_re.match(ref) or ref == 'self':
                    entries.append((title, ref))
                elif docname not in env.found_docs:
                    ret.append(
                        self.state.document.reporter.warning(
                            '[CustomTocTree] contains reference to nonexisting '
                            'document %r' % docname,
                            line=self.lineno))
                    env.note_reread()
                else:
                    all_docnames.discard(docname)
                    entries.append((title, docname))
                    includefiles.append(docname)
        subnode = addnodes.toctree()
        subnode['parent'] = env.docname
        # entries contains all entries (self references, external links etc.)
        if 'reversed' in self.options:
            entries.reverse()
        subnode['entries'] = entries
        # includefiles only entries that are documents
        subnode['includefiles'] = includefiles
        subnode['maxdepth'] = self.options.get('maxdepth', -1)
        subnode['caption'] = self.options.get('caption')
        subnode['glob'] = glob
        subnode['hidden'] = 'hidden' in self.options
        subnode['includehidden'] = 'includehidden' in self.options
        subnode['numbered'] = self.options.get('numbered', 0)
        subnode['titlesonly'] = 'titlesonly' in self.options
        set_source_info(self, subnode)
        wrappernode = nodes.compound(classes=['toctree-wrapper'])
        wrappernode.append(subnode)
        self.add_name(wrappernode)
        ret.append(wrappernode)
        return ret
示例#53
0
    def run(self):
        env = self.state.document.settings.env
        stat_example = None
        stat_group, stat_name, stat_type = self.arguments[0:3]
        if len(self.arguments) > 3:
            stat_example = self.arguments[3]

        # First, make a generic desc() node to be the parent.
        node = sphinx.addnodes.desc()
        node.document = self.state.document
        node["objtype"] = "stat"

        # Next, make a signature node. This creates a permalink and a
        # highlighted background when the link is selected.
        title = sphinx.addnodes.desc_signature(stat_name, "")
        title["ids"].append(nodes.make_id("stat-" + stat_name))
        title["names"].append(stat_name)
        title["first"] = False
        title["objtype"] = "stat"
        self.add_name(title)
        title.set_class("ts-stat-title")

        # Finally, add a desc_name() node to display the name of the
        # configuration variable.
        title += sphinx.addnodes.desc_name(stat_name, stat_name)

        node.append(title)

        # This has to be a distinct node before the title. if nested then
        # the browser will scroll forward to just past the title.
        anchor = nodes.target("", "", names=[stat_name])
        # Second (optional) arg is 'msgNode' - no idea what I should pass for that
        # or if it even matters, although I now think it should not be used.
        self.state.document.note_explicit_target(title)
        env.domaindata["ts"]["stat"][stat_name] = env.docname

        fl = nodes.field_list()
        fl.append(self.make_field("Collection", stat_group))
        if "type" in self.options:
            fl.append(self.make_field("Type", self.options["type"]))
        if "unit" in self.options:
            fl.append(self.make_field("Units", self.options["unit"]))
        fl.append(self.make_field("Datatype", stat_type))
        if "introduced" in self.options and len(self.options["introduced"]) > 0:
            fl.append(self.make_field("Introduced", self.options["introduced"]))
        if "deprecated" in self.options:
            if len(self.options["deprecated"]) > 0:
                fl.append(self.make_field("Deprecated", self.options["deprecated"]))
            else:
                fl.append(self.make_field("Deprecated", "Yes"))
        if "ungathered" in self.options:
            fl.append(self.make_field("Gathered", "No"))
        if stat_example:
            fl.append(self.make_field("Example", stat_example))

        # Get any contained content
        nn = nodes.compound()
        self.state.nested_parse(self.content, self.content_offset, nn)

        # Create an index node so that Sphinx adds this statistic to the
        # index. nodes.make_id() specifies the link anchor name that is
        # implicitly generated by the anchor node above.
        indexnode = sphinx.addnodes.index(entries=[])
        indexnode["entries"].append(("single", _("%s") % stat_name, nodes.make_id(stat_name), ""))

        return [indexnode, node, fl, nn]
示例#54
0
    def run(self):
        env = self.state.document.settings.env
        cv_default = None
        cv_scope, cv_name, cv_type = self.arguments[0:3]
        if len(self.arguments) > 3:
            cv_default = self.arguments[3]

        # First, make a generic desc() node to be the parent.
        node = sphinx.addnodes.desc()
        node.document = self.state.document
        node["objtype"] = "cv"

        # Next, make a signature node. This creates a permalink and a
        # highlighted background when the link is selected.
        title = sphinx.addnodes.desc_signature(cv_name, "")
        title["ids"].append(nodes.make_id(cv_name))
        title["ids"].append(cv_name)
        title["names"].append(cv_name)
        title["first"] = False
        title["objtype"] = "cv"
        self.add_name(title)
        title.set_class("ts-cv-title")

        # Finally, add a desc_name() node to display the name of the
        # configuration variable.
        title += sphinx.addnodes.desc_name(cv_name, cv_name)

        node.append(title)

        if "class" in self.options:
            title.set_class(self.options.get("class"))
        # This has to be a distinct node before the title. if nested then
        # the browser will scroll forward to just past the title.
        anchor = nodes.target("", "", names=[cv_name])
        # Second (optional) arg is 'msgNode' - no idea what I should pass for that
        # or if it even matters, although I now think it should not be used.
        self.state.document.note_explicit_target(title)
        env.domaindata["ts"]["cv"][cv_name] = env.docname

        fl = nodes.field_list()
        fl.append(self.make_field("Scope", cv_scope))
        fl.append(self.make_field("Type", cv_type))
        if cv_default:
            fl.append(self.make_field("Default", cv_default))
        else:
            fl.append(self.make_field("Default", sphinx.addnodes.literal_emphasis(text="*NONE*")))
        if "metric" in self.options:
            fl.append(self.make_field("Metric", self.options["metric"]))
        if "reloadable" in self.options:
            fl.append(self.make_field("Reloadable", "Yes"))
        if "overridable" in self.options:
            fl.append(self.make_field("Overridable", "Yes"))
        if "deprecated" in self.options:
            fl.append(self.make_field("Deprecated", "Yes"))

        # Get any contained content
        nn = nodes.compound()
        self.state.nested_parse(self.content, self.content_offset, nn)

        # Create an index node so that Sphinx adds this config variable to the
        # index. nodes.make_id() specifies the link anchor name that is
        # implicitly generated by the anchor node above.
        indexnode = sphinx.addnodes.index(entries=[])
        indexnode["entries"].append(("single", _("%s") % cv_name, nodes.make_id(cv_name), ""))

        return [indexnode, node, fl, nn]
示例#55
0
def my_toctree_run(self):
    """Show non existing entries of toctree
    
    :param sphinx.directives.other.TocTree self: The instance object
    :rtype: list
    :return: list of the nodes made in this method
    
    Defined to replace the method :meth:`sphinx.directives.other.TocTree.run`

    Only :code:`%r` following are replaced with :code:`%s` to avoid unreadable string.
    """
    env = self.state.document.settings.env
    suffixes = env.config.source_suffix
    glob = 'glob' in self.options
    caption = self.options.get('caption')
    if caption:
        self.options.setdefault('name', nodes.fully_normalize_name(caption))

    ret = []
    # (title, ref) pairs, where ref may be a document, or an external link,
    # and title may be None if the document's title is to be used
    entries = []
    includefiles = []
    all_docnames = env.found_docs.copy()
    # don't add the currently visited file in catch-all patterns
    all_docnames.remove(env.docname)
    for entry in self.content:
        if not entry:
            continue
        if glob and ('*' in entry or '?' in entry or '[' in entry):
            patname = docname_join(env.docname, entry)
            docnames = sorted(patfilter(all_docnames, patname))
            for docname in docnames:
                all_docnames.remove(docname)  # don't include it again
                entries.append((None, docname))
                includefiles.append(docname)
            if not docnames:
                ret.append(
                    self.state.document.reporter.warning(
                        'toctree glob pattern %r didn\'t match any documents' %
                        entry,
                        line=self.lineno))
        else:
            # look for explicit titles ("Some Title <document>")
            m = explicit_title_re.match(entry)
            if m:
                ref = m.group(2)
                title = m.group(1)
                docname = ref
            else:
                ref = docname = entry
                title = None
            # remove suffixes (backwards compatibility)
            for suffix in suffixes:
                if docname.endswith(suffix):
                    docname = docname[:-len(suffix)]
                    break
            # absolutize filenames
            docname = docname_join(env.docname, docname)
            if url_re.match(ref) or ref == 'self':
                entries.append((title, ref))
            elif docname not in env.found_docs:
                ret.append(
                    self.state.document.reporter.warning(
                        u'toctree contains reference to nonexisting '
                        u'document %s' % docname,
                        line=self.lineno))
                env.note_reread()
            else:
                all_docnames.discard(docname)
                entries.append((title, docname))
                includefiles.append(docname)
    subnode = addnodes.toctree()
    subnode['parent'] = env.docname
    # entries contains all entries (self references, external links etc.)
    subnode['entries'] = entries
    # includefiles only entries that are documents
    subnode['includefiles'] = includefiles
    subnode['maxdepth'] = self.options.get('maxdepth', -1)
    subnode['caption'] = caption
    subnode['glob'] = glob
    subnode['hidden'] = 'hidden' in self.options
    subnode['includehidden'] = 'includehidden' in self.options
    subnode['numbered'] = self.options.get('numbered', 0)
    subnode['titlesonly'] = 'titlesonly' in self.options
    set_source_info(self, subnode)
    wrappernode = nodes.compound(classes=['toctree-wrapper'])
    wrappernode.append(subnode)
    self.add_name(wrappernode)
    ret.append(wrappernode)
    return ret
示例#56
0
    def run(self):
        env = self.state.document.settings.env
        suffixes = env.config.source_suffix
        glob = 'glob' in self.options
        caption = self.options.get('caption')
        if caption:
            self.options.setdefault('name', nodes.fully_normalize_name(caption))

        ret = []
        # (title, ref) pairs, where ref may be a document, or an external link,
        # and title may be None if the document's title is to be used
        entries = []
        includefiles = []
        all_docnames = env.found_docs.copy()
        # don't add the currently visited file in catch-all patterns
        all_docnames.remove(env.docname)
        for entry in self.content:
            if not entry:
                continue
            if glob and ('*' in entry or '?' in entry or '[' in entry):
                patname = docname_join(env.docname, entry)
                docnames = sorted(patfilter(all_docnames, patname))
                for docname in docnames:
                    all_docnames.remove(docname)  # don't include it again
                    entries.append((None, docname))
                    includefiles.append(docname)
                if not docnames:
                    ret.append(self.state.document.reporter.warning(
                        'toctree glob pattern %r didn\'t match any documents'
                        % entry, line=self.lineno))
            else:
                # look for explicit titles ("Some Title <document>")
                m = explicit_title_re.match(entry)
                if m:
                    ref = m.group(2)
                    title = m.group(1)
                    docname = ref
                else:
                    ref = docname = entry
                    title = None
                # remove suffixes (backwards compatibility)
                for suffix in suffixes:
                    if docname.endswith(suffix):
                        docname = docname[:-len(suffix)]
                        break
                # absolutize filenames
                docname = docname_join(env.docname, docname)
                if url_re.match(ref) or ref == 'self':
                    entries.append((title, ref))
                elif docname not in env.found_docs:
                    ret.append(self.state.document.reporter.warning(
                        'toctree contains reference to nonexisting '
                        'document %r' % docname, line=self.lineno))
                    env.note_reread()
                else:
                    all_docnames.discard(docname)
                    entries.append((title, docname))
                    includefiles.append(docname)
        subnode = addnodes.toctree()
        subnode['parent'] = env.docname
        # entries contains all entries (self references, external links etc.)
        subnode['entries'] = entries
        # includefiles only entries that are documents
        subnode['includefiles'] = includefiles
        subnode['maxdepth'] = self.options.get('maxdepth', -1)
        subnode['caption'] = caption
        subnode['glob'] = glob
        subnode['hidden'] = 'hidden' in self.options
        subnode['includehidden'] = 'includehidden' in self.options
        subnode['numbered'] = self.options.get('numbered', 0)
        subnode['titlesonly'] = 'titlesonly' in self.options
        set_source_info(self, subnode)
        wrappernode = nodes.compound(classes=['toctree-wrapper'])
        wrappernode.append(subnode)
        self.add_name(wrappernode)
        ret.append(wrappernode)
        return ret
示例#57
0
    def _process_validation_keywords(self, schema, typename=None, path=''):
        node_list = []
        typename = typename or schema['type']

        if typename == 'string':
            if not ('minLength' in schema or 'maxLength' in schema):
                node_list.append(nodes.emphasis(text='No length restriction'))
            if schema.get('minLength', 0):
                text = 'Minimum length: {}'.format(schema['minLength'])
                node_list.append(nodes.line(text=text))
            if 'maxLength' in schema:
                text = 'Maximum length: {}'.format(schema['maxLength'])
                node_list.append(nodes.line(text=text))
            if 'pattern' in schema:
                node_list.append(
                    nodes.line(text='Must match the following pattern:'))
                node_list.append(
                    nodes.literal_block(text=schema['pattern'],
                                        language='none'))

        elif typename == 'array':
            if schema.get('minItems', 0):
                text = 'Minimum length: {}'.format(schema['minItems'])
                node_list.append(nodes.line(text=text))
            if 'maxItems' in schema:
                text = 'Maximum length: {}'.format(schema['maxItems'])
                node_list.append(nodes.line(text=text))
            if 'additionalItems' in schema and 'items' in schema:
                if isinstance(schema['items'],
                              list) and schema['additionalItems'] == False:
                    node_list.append(
                        nodes.emphasis(text='Additional items not permitted'))
            elif not ('minItems' in schema or 'maxItems' in schema):
                node_list.append(nodes.emphasis(text='No length restriction'))

            if 'items' in schema:
                node_list.append(
                    self._create_array_items_node(schema['items'], path=path))

        # TODO: more numerical validation keywords
        elif typename in ['integer', 'number']:
            if 'minimum' in schema:
                text = 'Minimum value: {}'.format(schema['minimum'])
                node_list.append(nodes.line(text=text))
            if 'maximum' in schema:
                text = 'Maximum value: {}'.format(schema['maximum'])
                node_list.append(nodes.line(text=text))

        if 'enum' in schema:
            node_list.append(self._create_enum_node(schema['enum']))

        if 'default' in schema:
            if typename in ['string', 'integer', 'number']:
                if typename == 'string' and not schema['default']:
                    default = "''"
                else:
                    default = schema['default']
                text = 'Default value: {}'.format(default)
                node_list.append(nodes.line(text=text))
            else:
                default_node = nodes.compound()
                default_node.append(nodes.line(text='Default value:'))
                default_node.append(
                    nodes.literal_block(text=pformat(schema['default']),
                                        language='none'))
                node_list.append(default_node)

        return node_list
示例#58
0
    def run(self):
        env = self.state.document.settings.env
        cv_default = None
        cv_scope, cv_name, cv_type = self.arguments[0:3]
        if (len(self.arguments) > 3):
            cv_default = self.arguments[3]

        # First, make a generic desc() node to be the parent.
        node = sphinx.addnodes.desc()
        node.document = self.state.document
        node['objtype'] = 'cv'

        # Next, make a signature node. This creates a permalink and a
        # highlighted background when the link is selected.
        title = sphinx.addnodes.desc_signature(cv_name, '')
        title['ids'].append(nodes.make_id(cv_name))
        title['ids'].append(cv_name)
        title['names'].append(cv_name)
        title['first'] = False
        title['objtype'] = 'cv'
        self.add_name(title)
        title.set_class('ts-cv-title')

        # Finally, add a desc_name() node to display the name of the
        # configuration variable.
        title += sphinx.addnodes.desc_name(cv_name, cv_name)

        node.append(title)

        if ('class' in self.options):
            title.set_class(self.options.get('class'))
        # This has to be a distinct node before the title. if nested then
        # the browser will scroll forward to just past the title.
        anchor = nodes.target('', '', names=[cv_name])
        # Second (optional) arg is 'msgNode' - no idea what I should pass for that
        # or if it even matters, although I now think it should not be used.
        self.state.document.note_explicit_target(title)
        env.domaindata['ts']['cv'][cv_name] = env.docname

        fl = nodes.field_list()
        fl.append(self.make_field('Scope', cv_scope))
        fl.append(self.make_field('Type', cv_type))
        if (cv_default):
            fl.append(self.make_field('Default', cv_default))
        else:
            fl.append(self.make_field('Default', sphinx.addnodes.literal_emphasis(text='*NONE*')))
        if ('units' in self.options):
            fl.append(self.make_field('Units', self.options['units']))
        if ('reloadable' in self.options):
            fl.append(self.make_field('Reloadable', 'Yes'))
        if ('overridable' in self.options):
            fl.append(self.make_field('Overridable', 'Yes'))
        if ('deprecated' in self.options):
            fl.append(self.make_field('Deprecated', 'Yes'))

        # Get any contained content
        nn = nodes.compound();
        self.state.nested_parse(self.content, self.content_offset, nn)

        # Create an index node so that Sphinx adds this config variable to the
        # index. nodes.make_id() specifies the link anchor name that is
        # implicitly generated by the anchor node above.
        indexnode = sphinx.addnodes.index(entries=[])
        indexnode['entries'].append(
            ('single', _('%s') % cv_name, nodes.make_id(cv_name), '')
        )

        return [ indexnode, node, fl, nn ]
示例#59
0
    def run(self):
        env = self.state.document.settings.env
        cv_default = None
        cv_scope, cv_name, cv_type = self.arguments[0:3]
        if (len(self.arguments) > 3):
            cv_default = self.arguments[3]

        # First, make a generic desc() node to be the parent.
        node = sphinx.addnodes.desc()
        node.document = self.state.document
        node['objtype'] = 'cv'

        # Next, make a signature node. This creates a permalink and a
        # highlighted background when the link is selected.
        title = sphinx.addnodes.desc_signature(cv_name, '')
        title['ids'].append(nodes.make_id(cv_name))
        title['ids'].append(cv_name)
        title['names'].append(cv_name)
        title['first'] = False
        title['objtype'] = 'cv'
        self.add_name(title)
        title.set_class('ts-cv-title')

        # Finally, add a desc_name() node to display the name of the
        # configuration variable.
        title += sphinx.addnodes.desc_name(cv_name, cv_name)

        node.append(title)

        if ('class' in self.options):
            title.set_class(self.options.get('class'))
        # This has to be a distinct node before the title. if nested then
        # the browser will scroll forward to just past the title.
        anchor = nodes.target('', '', names=[cv_name])
        # Second (optional) arg is 'msgNode' - no idea what I should pass for that
        # or if it even matters, although I now think it should not be used.
        self.state.document.note_explicit_target(title)
        env.domaindata['ts']['cv'][cv_name] = env.docname

        fl = nodes.field_list()
        fl.append(self.make_field('Scope', cv_scope))
        fl.append(self.make_field('Type', cv_type))
        if (cv_default):
            fl.append(self.make_field('Default', cv_default))
        else:
            fl.append(
                self.make_field(
                    'Default',
                    sphinx.addnodes.literal_emphasis(text='*NONE*')))
        if ('units' in self.options):
            fl.append(self.make_field('Units', self.options['units']))
        if ('reloadable' in self.options):
            fl.append(self.make_field('Reloadable', 'Yes'))
        if ('overridable' in self.options):
            fl.append(self.make_field('Overridable', 'Yes'))
        if ('deprecated' in self.options):
            fl.append(self.make_field('Deprecated', 'Yes'))

        # Get any contained content
        nn = nodes.compound()
        self.state.nested_parse(self.content, self.content_offset, nn)

        # Create an index node so that Sphinx adds this config variable to the
        # index. nodes.make_id() specifies the link anchor name that is
        # implicitly generated by the anchor node above.
        indexnode = sphinx.addnodes.index(entries=[])
        if sphinx.version_info >= (1, 4):
            indexnode['entries'].append(
                ('single', _('%s') % cv_name, nodes.make_id(cv_name), '', ''))
        else:
            indexnode['entries'].append(
                ('single', _('%s') % cv_name, nodes.make_id(cv_name), ''))

        return [indexnode, node, fl, nn]