def visit_language_specific_pages_node_html(self, node):
    node['classes'] = ['tabbable']

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

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

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

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

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

        first = False

    node.append(ul)

    pages = nodes.admonition()
    pages['classes'] = ['tab-content']

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

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

        first = False

    node.append(pages)

    self.body.append(self.starttag(node, 'div'))
Esempio n. 2
0
def visit_language_specific_pages_node_html(self, node):
    node['classes'] = ['tabbable']

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

    href = tab('', 'Ovation API:')
    href['classes'] = ['disabled']
    paragraph = nodes.paragraph('', '')
    li = nodes.list_item('')
    li['classes'] = ['disabled']

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

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

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

        first = False

    node.append(ul)

    pages = nodes.admonition()
    pages['classes'] = ['tab-content']

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

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

        first = False

    node.append(pages)

    self.body.append(self.starttag(node, 'div'))
Esempio n. 3
0
    def get_admonition(self, token, name, classes, title):

        line = token.map[0]

        if name == "admonition":
            # parse title
            node = nodes.admonition(title, classes=classes[1:].split(","))
            state_machine = MockStateMachine(self, line)
            state = MockState(self, state_machine, line)
            textnodes, messages = state.inline_text(title, line)
            title_node = nodes.title(title, "", *textnodes)
            self.add_line_and_source_path(title_node, token)
            node += title_node
            node += messages
            return node

        node_cls = STD_ADMONITIONS.get(name, None)
        if node_cls is None:
            self.current_node.append(
                self.reporter.warning(
                    f"admonition name not recognised, defaulting to note: {name}",
                    line=line,
                ))
            node_cls = nodes.note
        return node_cls(title, classes=classes[1:].split(","))
    def run(self) -> List[Node]:
        env = self.env
        content = ViewList()
        domain_name, typ = self.name.split(":")[0], self.name.split(":")[1]

        # If class in options add to class array
        classes, class_name = [domain_name, typ], self.options.get("class", [])
        if class_name:
            classes.extend(class_name)

        section = nodes.admonition(classes=classes, ids=[typ])
        emph = nodes.emphasis()

        if self.arguments != []:
            content.append(self.arguments[0], 0)
            self.content.insert(0, content)

        self.content[0] = "{}. ".format(typ.title()) + self.content[0]
        self.state.nested_parse(self.content, self.content_offset, emph)

        node = proof_node()
        section += emph
        node += section

        return [node]
Esempio n. 5
0
    def run(self):
        sponsor_link = self.env.config.sponsor_link
        organization = self.env.config.organization

        admonition_node = nodes.admonition(classes=["admonition-sponsor"])
        admonition_node += nodes.title(text="Sponsor")

        # Parse admonition body contents.
        # Needs to use a container here instead of list otherwise exception.
        node_list = nodes.container()
        self.state.nested_parse(self.content, self.content_offset, node_list)
        admonition_node += node_list.children

        # Add sponsor button for HTML and fallback for PDF.
        html = f"<iframe src=\"{sponsor_link}/button\" title=\"Sponsor {organization}\" height=\"35\" width=\"116\" style=\"border: 0; display: block;\"></iframe>"
        html_node = nodes.raw(text=html, format="html")
        only_pdf = addnodes.only(expr="latex")
        only_pdf_paragraph = nodes.inline()
        self.state.nested_parse(
            nodes.inline(text=f":link:`Sponsor Us <{sponsor_link}?o=esb>`"), 0,
            only_pdf_paragraph)
        only_pdf += only_pdf_paragraph

        admonition_node += html_node
        admonition_node += only_pdf

        return [admonition_node]
Esempio n. 6
0
    def run(self):
        filename = self.arguments[0]

        cwd = os.getcwd()
        os.chdir(TMPDIR)

        parts = []
        try:
            code = AsdfFile.read(filename, _get_yaml_content=True)
            code = '{0}{1}\n'.format(ASDF_MAGIC, version_string) + code.strip().decode('utf-8')
            literal = nodes.literal_block(code, code)
            literal['language'] = 'yaml'
            set_source_info(self, literal)
            parts.append(literal)

            ff = AsdfFile.read(filename)
            for i, block in enumerate(ff.blocks.internal_blocks):
                data = codecs.encode(block.data.tostring(), 'hex')
                if len(data) > 40:
                    data = data[:40] + '...'.encode()
                allocated = block._allocated
                size = block._size
                data_size = block._data_size
                flags = block._flags

                if flags & BLOCK_FLAG_STREAMED:
                    allocated = size = data_size = 0

                lines = []
                lines.append('BLOCK {0}:'.format(i))

                human_flags = []
                for key, val in FLAGS.items():
                    if flags & key:
                        human_flags.append(val)
                if len(human_flags):
                    lines.append('    flags: {0}'.format(' | '.join(human_flags)))
                if block.compression:
                    lines.append('    compression: {0}'.format(block.compression))
                lines.append('    allocated_size: {0}'.format(allocated))
                lines.append('    used_size: {0}'.format(size))
                lines.append('    data_size: {0}'.format(data_size))
                lines.append('    data: {0}'.format(data))

                code = '\n'.join(lines)

                literal = nodes.literal_block(code, code)
                literal['language'] = 'yaml'
                set_source_info(self, literal)
                parts.append(literal)

        finally:
            os.chdir(cwd)

        result = nodes.admonition()
        textnodes, messages = self.state.inline_text(filename, self.lineno)
        title = nodes.title(filename, '', *textnodes)
        result += title
        result.children.extend(parts)
        return [result]
Esempio n. 7
0
 def run(self):
     groServer = self.config.grossular_server
     groProject = self.config.grossular_project
     res = requests.get(API.UseCaseListAll(groServer, groProject))
     res.encoding = "utf8"
     jsobj = json.loads(res.text)
     nodeList = []
     self.info(
         "grossular: read {caseCount} cases".format(caseCount=len(jsobj)))
     for caseObj in jsobj:
         caseDetailObj = json.loads(
             requests.get(API.UseCaseDetail(groServer, caseObj['id'])).text)
         targetid = REF_ID % caseObj['id']
         nodeList.append(nodes.target('', '', ids=[targetid]))
         admonBar = nodes.admonition()
         admonBar += nodes.title('admonTitle', "用例名称")
         admonBar += nodes.paragraph('caseName', caseObj['name'])
         nodeList.append(admonBar)
         nodeList.append(nodes.paragraph("caseComment",
                                         caseObj['comments']))
         nodeList.extend(
             self.genCaseCrossRefNodes(caseDetailObj=caseDetailObj,
                                       crossFieldName='concrete',
                                       crossTitle='具体用例参见:'))
         nodeList.extend(
             self.genCaseCrossRefNodes(caseDetailObj=caseDetailObj,
                                       crossFieldName='extension',
                                       crossTitle='该用例功能被以下用例扩展:'))
         nodeList.extend(
             self.genCaseCrossRefNodes(caseDetailObj=caseDetailObj,
                                       crossFieldName='include',
                                       crossTitle='该用例包括以下子用例:'))
     return nodeList
Esempio n. 8
0
File: rst.py Progetto: saalaa/adoc
    def run(self):
        node = nodes.admonition()

        version_label = self.version_labels[self.name]
        label = version_label.format(self.arguments[0])

        if len(self.arguments) == 2:
            inodes, messages = self.state.inline_text(self.arguments[1],
                                                      self.lineno + 1)

            node.append(nodes.paragraph(self.arguments[1], '', *inodes))

        if self.content:
            self.state.nested_parse(self.content, self.content_offset, node)

        if len(node):
            label = nodes.inline('',
                                 '{}: '.format(label),
                                 classes=['versionmodified'])

            node[0].insert(0, label)
        else:
            label = nodes.inline('',
                                 '{}.'.format(label),
                                 classes=['versionmodified'])

            node.append(nodes.paragraph('', '', label))

        return [node]
Esempio n. 9
0
    def run(self):
        self.assert_has_content()

        node = nodes.admonition('\n'.join(self.content))
        node.set_class("chemfiles-selection")

        title_text = self.arguments[0]
        textnodes, _ = self.state.inline_text(title_text, self.lineno)

        target = nodes.target('', '', ids=[nodes.make_id(title_text)])
        target.append(
            nodes.reference(
                '',
                '',
                refid=nodes.make_id(title_text),
                *textnodes,
            ))

        title = nodes.title(title_text, '', target)
        title['add_permalink'] = True
        node.append(title)

        self.state.nested_parse(self.content, self.content_offset, node)

        return [node]
Esempio n. 10
0
    def run(self):
        self.assert_has_content()

        container = question("", multi="multi" in self.options)
        self.set_source_info(container)

        admonition = nodes.admonition("")

        title = self.arguments[0] if len(self.arguments) > 0 else "Question"

        textnodes, _ = self.state.inline_text(title, self.lineno)
        label = nodes.title(title, *textnodes)

        content = nodes.container("",
                                  is_div=True,
                                  classes=["question-content"])
        self.state.nested_parse(self.content, self.content_offset, content)

        buttons = check_buttons("")

        admonition += label
        admonition += content
        admonition += buttons

        container += admonition

        return [container]
def process_worked_example_nodes(app, doctree, fromdocname):
    env = app.builder.env

    if not hasattr(env, WORKEDEXAMPLE_ENV_ATTRIBUTE):
        setattr(env, WORKEDEXAMPLE_ENV_ATTRIBUTE, [])

    for node in doctree.traverse(worked_example_list):
        title = node['title']
        tag = node['tag']

        title_node = nodes.title('', title)
        admonition_node = nodes.admonition('')
        admonition_node['classes'] += ['note']
        admonition_node += title_node

        items = []
        for example in getattr(env, WORKEDEXAMPLE_ENV_ATTRIBUTE):
            if tag not in example['tags'].split(','):
                continue

            uri = f"{app.builder.get_relative_uri(fromdocname, example['docname'])}#{example['target']['refid']}"
            reference = nodes.reference('', example['title'], refuri=uri)
            reference['translatable'] = True

            paragraph = nodes.paragraph('', '', reference)
            item = nodes.list_item('', paragraph)
            items.append(item)

        if not items:
            raise Error(f'No worked examples are tagged with {tag}')

        admonition_node += nodes.bullet_list('', *items)
        node.replace_self(admonition_node)
Esempio n. 12
0
def toctree_directive(dirname, arguments, options, content, lineno,
                      content_offset, block_text, state, state_machine):

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

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

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

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

    return [node]
Esempio n. 13
0
    def run(self):
        filename = self.arguments[0]

        cwd = os.getcwd()
        os.chdir(TMPDIR)

        parts = []
        try:
            code = AsdfFile.read(filename, _get_yaml_content=True)
            code = '{0}{1}\n'.format(ASDF_MAGIC, version_string) + code.strip()
            literal = nodes.literal_block(code, code)
            literal['language'] = 'yaml'
            set_source_info(self, literal)
            parts.append(literal)

            ff = AsdfFile.read(filename)
            for i, block in enumerate(ff.blocks.internal_blocks):
                data = block.data.tostring().encode('hex')
                if len(data) > 40:
                    data = data[:40] + '...'
                allocated = block._allocated
                size = block._size
                data_size = block._data_size
                flags = block._flags

                if flags & BLOCK_FLAG_STREAMED:
                    allocated = size = data_size = 0

                lines = []
                lines.append('BLOCK {0}:'.format(i))

                human_flags = []
                for key, val in FLAGS.items():
                    if flags & key:
                        human_flags.append(val)
                if len(human_flags):
                    lines.append('    flags: {0}'.format(' | '.join(human_flags)))
                if block.compression:
                    lines.append('    compression: {0}'.format(block.compression))
                lines.append('    allocated_size: {0}'.format(allocated))
                lines.append('    used_size: {0}'.format(size))
                lines.append('    data_size: {0}'.format(data_size))
                lines.append('    data: {0}'.format(data))

                code = '\n'.join(lines)

                literal = nodes.literal_block(code, code)
                literal['language'] = 'yaml'
                set_source_info(self, literal)
                parts.append(literal)

        finally:
            os.chdir(cwd)

        result = nodes.admonition()
        textnodes, messages = self.state.inline_text(filename, self.lineno)
        title = nodes.title(filename, '', *textnodes)
        result += title
        result.children.extend(parts)
        return [result]
Esempio n. 14
0
    def run(self):
        env = self.env
        env.note_dependency(_glossary_file_name(env.app))
        key, number = _parse_id(self.arguments[0])

        i = self.env.glossary_entries_index[key][number]
        entry = self.env.glossary_entries[i]

        adm_node = nodes.admonition('')
        adm_node += nodes.title(entry['name'], entry['name'])

        target_id = 'gl-%s-%d' % (key, env.new_serialno('gl-' + key))
        adm_node += nodes.target('', '', ids=[target_id])

        view_list = ViewList()
        for line in entry['definition'].splitlines():
            view_list.append(line, "glossaire.csv", 0)
        nested_parse_with_titles(self.state, view_list, adm_node)

        if not hasattr(env, 'glossary_references'):
            env.glossary_references = {}
        if not i in env.glossary_references:
            env.glossary_references[i] = []
        env.glossary_references[i].append({
            'type': 'DEF',
            'docname': env.docname,
            'lineno': self.lineno,
            'target_id': target_id,
        })

        return [adm_node]
def create_top_node(title):
    top_node = nodes.container()
    admon_node = nodes.admonition()
    title_node = nodes.title()
    title_node += nodes.Text(title)
    admon_node += title_node
    top_node += admon_node
    return top_node
Esempio n. 16
0
    def run(self):
        self.assert_has_content()
        env = self.state.document.settings.env

        targetid = 'task-{}'.format(env.new_serialno('task'))
        targetnode = nodes.target('', '', ids=[targetid])

        name = "Задача"
        if "name" in self.options:
            name = self.options["name"]
        headernode = taskheader('')
        headernode.targetid = targetid
        headernode.name = name
        headernode.docname = env.docname
        headernode.title = True

        content = self.content
        state = 0
        last_idx = -1
        res = [[], [], []]
        for idx, line in enumerate(self.content):
            if line.strip() == "|":
                if last_idx + 1 < idx:
                    res[state] = content[last_idx + 1:idx]
                else:
                    res[state] = None
                state += 1
                last_idx = idx

        if not hasattr(env, 'task_all_tasks'):
            env.task_all_tasks = []

        path = env.doc2path(env.docname)
        directory = os.path.dirname(path)
        if directory not in FILES:
            FILES[directory] = [
                open(directory + "/" + x + ".inc", "w")
                for x in ("all_tasks", "all_suggests", "all_answers")
            ]
        for i in range(3):
            if res[i] and "\n".join(res[i]).strip():
                f = FILES[directory][i]
                f.write(".. taskref::\n")
                f.write("    :name: {}\n".format(name))
                f.write("    :targetid: {}\n".format(targetid))
                f.write("    :docname: {}\n".format(env.docname))
                f.write("\n    ")
                f.write("\n    ".join(res[i]))
                f.write("\n\n")
                f.flush()
        res_node = nodes.paragraph(rawsource="\n".join(res[0]))
        self.state.nested_parse(res[0], self.content_offset, res_node)

        wrap_node = nodes.admonition(classes=["task"])
        wrap_node += [headernode, res_node]

        return [targetnode, wrap_node]
Esempio n. 17
0
 def run(self):
     text = "\n".join(self.content)
     ad = nodes.admonition(rawsource=text)
     st = nodes.strong()
     st.append(nodes.Text("See also:"))
     ad.append(st)
     ad.append(nodes.Text("\n"))
     self.state.nested_parse(self.content, 0, ad)
     return [ad]
def doctree_read(app, doctree):
    for node in doctree.traverse(is_builtin_admonition):
        new_node = admonition()
        name = node.__class__.__name__.title()
        title_node = title(name, name)
        new_node += title_node
        for child in node.children:
            new_node += child
            node.remove(child)
        node.replace_self(new_node)
Esempio n. 19
0
    def make_node(self, lang='en'):
        if lang not in texts.keys():
            lang = 'en'

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

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

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

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

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

        item.append(field_list)

        return item
Esempio n. 20
0
 def make_checker_chaining(self):
     symbol = self.lookup_auto_symbol()
     if not symbol:
         return
     next_checkers = symbol.properties.get('flycheck-next-checkers')
     if not next_checkers:
         return
     title = nodes.title('', 'Chained syntax checkers')
     intro = nodes.paragraph()
     intro += nodes.Text('The following syntax checkers are ')
     chained = addnodes.pending_xref('chained',
                                     reftype='term',
                                     refdomain='std',
                                     reftarget='chaining',
                                     refwarn=True,
                                     refexplicit=True,
                                     reftitle='chaining',
                                     refdoc=self.env.docname)
     chained += nodes.emphasis('', 'chained')
     intro += chained
     intro += nodes.Text(' after this syntax checker:')
     checker_list = nodes.enumerated_list()
     para = nodes.paragraph()
     para += checker_list
     outro = nodes.paragraph()
     outro += nodes.Text('The ')
     outro += nodes.strong('', 'first')
     outro += nodes.Text(' suitable syntax checker is used.')
     chaining = nodes.admonition(
         '',
         title,
         intro,
         para,
         outro,
         classes=['note', 'el-flycheck-checker-chaining'])
     for next_checker in next_checkers:
         xref = addnodes.pending_xref(next_checker.checker,
                                      reftype='flyc-checker',
                                      refdomain='el',
                                      refexplicit=False,
                                      reftarget=next_checker.checker,
                                      refwarn=False,
                                      refdoc=self.env.docname)
         set_role_source_info(self.state.inliner, self.lineno, xref)
         xref += nodes.literal('',
                               next_checker.checker,
                               classes=['xref', 'el', 'el-flyc-checker'])
         para = nodes.paragraph()
         para += xref
         if next_checker.warnings_only:
             para += nodes.Text(', if there are only warnings')
         if next_checker.no_errors:
             para += nodes.Text(', if there are no errors')
         checker_list += nodes.list_item('', para)
     return chaining
Esempio n. 21
0
 def apply(self):
     nodes_list_pages = list(self.document.traverse(list_pages))
     if nodes_list_pages:
         page_path = self.document.settings.neorg_page_path
         page_list = self._web.list_descendants(page_path)
         for node in nodes_list_pages:
             title = 'List of Pages'
             admonition = nodes.admonition()
             admonition += nodes.title(title, title)
             admonition += gene_link_tree(page_list)
             node.replace_self(admonition)
Esempio n. 22
0
File: wiki.py Progetto: tkf/neorg
 def apply(self):
     nodes_list_pages = list(self.document.traverse(list_pages))
     if nodes_list_pages:
         page_path = self.document.settings.neorg_page_path
         page_list = self._web.list_descendants(page_path)
         for node in nodes_list_pages:
             title = 'List of Pages'
             admonition = nodes.admonition()
             admonition += nodes.title(title, title)
             admonition += gene_link_tree(page_list)
             node.replace_self(admonition)
Esempio n. 23
0
 def run(self):
     # Raise an error if the directive does not have contents.
     self.assert_has_content()
     text = '\n'.join(self.content)
     # Create the admonition node, to be populated by `nested_parse`.
     admonition_node = nodes.admonition(rawsource=text)
     # Parse the directive contents.
     self.state.nested_parse(self.content, self.content_offset,
                             admonition_node)
     title = nodes.title('', 'XXX')
     admonition_node.insert(0, title)
     return [admonition_node]
 def run(self):
     self.content = statemachine.StringList([
         '|cover|',
         '',
         '(中略)詳細は書籍 `自走プログラマー <https://gihyo.jp/book/2020/978-4-297-11197-7>`__ をご参照ください',
     ])
     text = '\n'.join(self.content)
     admonition_node = nodes.admonition(text, **{'classes': [self.name]})
     self.add_name(admonition_node)
     self.state.nested_parse(self.content, self.content_offset,
                             admonition_node)
     return [admonition_node]
Esempio n. 25
0
 def run(self):
     # Raise an error if the directive does not have contents.
     self.assert_has_content()
     text = '\n'.join(self.content)
     # Create the admonition node, to be populated by `nested_parse`.
     admonition_node = nodes.admonition(rawsource=text)
     # Parse the directive contents.
     self.state.nested_parse(self.content, self.content_offset,
                             admonition_node)
     title = nodes.title('', 'XXX')
     admonition_node.insert(0, title)
     return [admonition_node]
Esempio n. 26
0
 def apply(self):
     lcode = self.document.settings.language_code
     language = languages.get_language(lcode)
     for node in self.document.traverse(nodes.Admonition):
         node_name = node.__class__.__name__
         # Set class, so that we know what node this admonition came from.
         node["classes"].append(node_name)
         if not isinstance(node, nodes.admonition):
             # Specific admonition.  Transform into a generic admonition.
             admonition = nodes.admonition(node.rawsource, *node.children, **node.attributes)
             title = nodes.title("", language.labels[node_name])
             admonition.insert(0, title)
             node.replace_self(admonition)
Esempio n. 27
0
 def apply(self):
     lcode = self.document.settings.language_code
     language = languages.get_language(lcode)
     for node in self.document.traverse(nodes.Admonition):
         node_name = node.__class__.__name__
         # Set class, so that we know what node this admonition came from.
         node['classes'].append(node_name)
         if not isinstance(node, nodes.admonition):
             # Specific admonition.  Transform into a generic admonition.
             admonition = nodes.admonition(node.rawsource, *node.children,
                                           **node.attributes)
             title = nodes.title('', language.labels[node_name])
             admonition.insert(0, title)
             node.replace_self(admonition)
    def create_top_node(title):
        """ Creates a container node containing an admonition with the given title inside.

        Args:
            title (str): Title text to be displayed.

        Returns:
            (nodes.container) Container node with the title laid out.
        """
        top_node = nodes.container()
        admon_node = nodes.admonition()
        title_node = nodes.title()
        title_node += nodes.Text(title)
        admon_node += title_node
        top_node += admon_node
        return top_node
Esempio n. 29
0
    def run(self) -> List[Node]:
        typ = self.name.split(":")[1]

        # If class in options add to class array
        classes, class_name = ["proof", typ], self.options.get("class", [])
        if class_name:
            classes.extend(class_name)

        section = nodes.admonition(classes=classes, ids=[typ])

        self.content[0] = "{}. ".format(typ.title()) + self.content[0]
        self.state.nested_parse(self.content, 0, section)

        node = proof_node()
        node += section

        return [node]
Esempio n. 30
0
    def run(self):
        self.assert_has_content()
        classes = ["toggle"]
        if "show" in self.options:
            classes.append("toggle-shown")

        if len(self.arguments) == 0:
            parent = nodes.container(classes=classes)
            self.state.nested_parse(self.content, self.content_offset, parent)
        else:
            parent = nodes.admonition(classes=["toggle-body"])
            title = nodes.title(self.arguments[0], self.arguments[0])
            body = nodes.container(classes=classes)
            self.state.nested_parse(self.content, self.content_offset, body)
            parent += title
            parent += body
        return [parent]
    def make_node(self, lang='en'):
        if lang not in texts.keys():
            lang = 'en'
        arg_map = texts[lang]["arg_map"]
        task_title = texts[lang]["task_title"]
        module_title = texts[lang]["module_title"]

        module_args = {}

        # Search task definition for modules and associated arguments.
        for key, value in self.args.items():
            if key not in arg_map.keys():
                module_args[key] = value

        # Create task node (using type: admonition)
        item = nodes.admonition()
        title = nodes.title(text=self.name)
        item.append(title)

        # Add modules and arguments to task node
        for module, args in module_args.items():
            field_list = nodes.field_list()  # wrap module header in field_list
            field_list.append(self.make_arg_simple(module_title, module))
            item.append(field_list)
            if isinstance(args, str):
                item.append(nodes.literal_block(text=args))
            else:
                item.append(self.make_list_representation(args))

        # Handle non-module task parameters.
        field_list = nodes.field_list()
        for arg, txt in arg_map.items():
            if not txt:  # skip name etc...
                continue
            if arg not in self.args:
                continue
            value = self.args[arg]  # value of that task arg
            if isinstance(value, list) or isinstance(value, dict):
                field_list.append(self.make_arg_complex(txt, value))
            else:
                field_list.append(self.make_arg_simple(txt, value))

        item.append(field_list)

        return item
Esempio n. 32
0
    def get_admonition(self, token, name, classes, title):
        """Create an admonition node. """
        line = token.map[0]

        if name == "admonition":
            # parse title
            node = nodes.admonition(title, classes=classes[1:].split(","))
            state_machine = MockStateMachine(self, line)
            state = MockState(self, state_machine, line)
            textnodes, messages = state.inline_text(title, line)
            title_node = nodes.title(title, "", *textnodes)
            self.add_line_and_source_path(title_node, token)
            node += title_node
            node += messages
            return node

        node_cls = STD_ADMONITIONS.get(name)
        return node_cls(title, classes=classes[1:].split(","))
Esempio n. 33
0
    def run(self):  #
        # Create the root admonition node.
        content = '\n'.join(self.content)
        options = {'classes': ['note']}
        admonition = nodes.admonition(content, **options)

        # Create the title node.
        title = f"Update — {self.arguments[0]}"
        text_nodes, _ = self.state.inline_text(title, self.lineno)
        title = nodes.title(title, '', *text_nodes)
        title.source, title.line = \
                self.state_machine.get_source_and_line(self.lineno)
        admonition += title

        # Create the content node.
        self.state.nested_parse(self.content, self.content_offset, admonition)

        return [admonition]
Esempio n. 34
0
 def make_checker_chaining(self):
     symbol = self.lookup_auto_symbol()
     if not symbol:
         return
     next_checkers = symbol.properties.get('flycheck-next-checkers')
     if not next_checkers:
         return
     title = nodes.title('', 'Chained syntax checkers')
     intro = nodes.paragraph()
     intro += nodes.Text('The following syntax checkers are ')
     chained = addnodes.pending_xref(
         'chained', reftype='term', refdomain='std', reftarget='chaining',
         refwarn=True, refexplicit=True, reftitle='chaining',
         refdoc=self.env.docname)
     chained += nodes.emphasis('', 'chained')
     intro += chained
     intro += nodes.Text(' after this syntax checker:')
     checker_list = nodes.enumerated_list()
     para = nodes.paragraph()
     para += checker_list
     outro = nodes.paragraph()
     outro += nodes.Text('The ')
     outro += nodes.strong('', 'first')
     outro += nodes.Text(' suitable syntax checker is used.')
     chaining = nodes.admonition(
         '', title, intro, para, outro,
         classes=['note', 'el-flycheck-checker-chaining'])
     for next_checker in next_checkers:
         xref = addnodes.pending_xref(
             next_checker.checker,
             reftype='flyc-checker', refdomain='el',
             refexplicit=False, reftarget=next_checker.checker,
             refwarn=False, refdoc=self.env.docname)
         set_role_source_info(self.state.inliner, self.lineno, xref)
         xref += nodes.literal('', next_checker.checker,
                               classes=['xref', 'el', 'el-flyc-checker'])
         para = nodes.paragraph()
         para += xref
         if next_checker.warnings_only:
             para += nodes.Text(', if there are only warnings')
         if next_checker.no_errors:
             para += nodes.Text(', if there are no errors')
         checker_list += nodes.list_item('', para)
     return chaining
    def create_presentation_node(self, env, tag, attributes, target_node):
        # Initialize admonition node.
        admonition_node = nodes.admonition()
        admonition_node["classes"] += ["traceable"]

        # Construct title node.
        admonition_node += self.create_title_node(env, tag, attributes)

        # Construct placeholder node for attribute list.
        attribute_list_node = traceable_attribute_list()
        attribute_list_node["traceable-tag"] = tag
        attribute_list_node["traceable-target"] = target_node
        attribute_list_node["traceable-attributes"] = attributes
        admonition_node += attribute_list_node

        # Finalize admonition node.
        self.state.nested_parse(self.content, self.content_offset,
                                admonition_node)
        return admonition_node
Esempio n. 36
0
    def format(self, app, docname, node, traceable, options):
        env = app.builder.env

        admonition = nodes.admonition()
        admonition["classes"] += ["traceable"]

        # Assign the traceable's unique ID to the admonition node, so
        # that HTML bookmarks ("somewhere.html#bookmark") work.
        admonition["ids"].append(traceable.target_node["refid"])

        # Add title and attribute list.
        admonition += self.create_title_node(traceable)
        admonition += self.create_attribute_list_node(app, docname, traceable)

        # Fill content of admonition node.
        while node.children:
            admonition += node.children.pop(0)

        return [admonition]
Esempio n. 37
0
    def format(self, app, docname, node, traceable, options):
        env = app.builder.env

        admonition = nodes.admonition()
        admonition["classes"] += ["traceable"]

        # Assign the traceable's unique ID to the admonition node, so
        # that HTML bookmarks ("somewhere.html#bookmark") work.
        admonition["ids"].append(traceable.target_node["refid"])

        # Add title and attribute list.
        admonition += self.create_title_node(traceable)
        admonition += self.create_attribute_list_node(app, docname, traceable)

        # Fill content of admonition node.
        while node.children:
            admonition += node.children.pop(0)

        return [admonition]
Esempio n. 38
0
    def run(self):
        filename = self.arguments[0]

        cwd = os.getcwd()
        os.chdir(TMPDIR)

        parts = []
        try:
            code = AsdfFile.read(filename, _get_yaml_content=True)
            if len(code.strip()):
                literal = nodes.literal_block(code, code)
                literal['language'] = 'yaml'
                set_source_info(self, literal)
                parts.append(literal)

            ff = AsdfFile.read(filename)
            for i, block in enumerate(ff.blocks.internal_blocks):
                data = block.data.tostring().encode('hex')
                if len(data) > 40:
                    data = data[:40] + '...'
                allocated = block._allocated
                size = block._size
                flags = block._flags
                if flags:
                    allocated = 0
                    size = 0
                code = BLOCK_DISPLAY.format(i, flags, allocated, size, data)
                literal = nodes.literal_block(code, code)
                literal['language'] = 'yaml'
                set_source_info(self, literal)
                parts.append(literal)

        finally:
            os.chdir(cwd)

        result = nodes.admonition()
        textnodes, messages = self.state.inline_text(filename, self.lineno)
        title = nodes.title(filename, '', *textnodes)
        result += title
        result.children.extend(parts)
        return [result]
Esempio n. 39
0
    def run(self):
        filename = self.arguments[0]

        cwd = os.getcwd()
        os.chdir(TMPDIR)

        parts = []
        try:
            code = AsdfFile.read(filename, _get_yaml_content=True)
            if len(code.strip()):
                literal = nodes.literal_block(code, code)
                literal['language'] = 'yaml'
                set_source_info(self, literal)
                parts.append(literal)

            ff = AsdfFile.read(filename)
            for i, block in enumerate(ff.blocks.internal_blocks):
                data = block.data.tostring().encode('hex')
                if len(data) > 40:
                    data = data[:40] + '...'
                allocated = block._allocated
                size = block._size
                flags = block._flags
                if flags:
                    allocated = 0
                    size = 0
                code = BLOCK_DISPLAY.format(i, flags, allocated, size, data)
                literal = nodes.literal_block(code, code)
                literal['language'] = 'yaml'
                set_source_info(self, literal)
                parts.append(literal)

        finally:
            os.chdir(cwd)

        result = nodes.admonition()
        textnodes, messages = self.state.inline_text(filename, self.lineno)
        title = nodes.title(filename, '', *textnodes)
        result += title
        result.children.extend(parts)
        return [result]
Esempio n. 40
0
    def run(self):
        if not hasattr(self.env, 'bioconda_lint_checks'):
            self.env.bioconda_lint_checks = {
                str(check): check
                for check in get_checks()
            }
        # gather data
        check_name = self.arguments[0]
        if check_name not in self.env.bioconda_lint_checks:
            self.error("Duplicate lint description")
        check = self.env.bioconda_lint_checks.pop(check_name)
        _, lineno = inspect.getsourcelines(check)
        lineno += 1
        fname = inspect.getfile(check)
        doclines = inspect.getdoc(check).splitlines()
        docline_src = [(fname, i)
                       for i in range(lineno, lineno + len(doclines))]
        lines = StringList(doclines, items=docline_src)

        # create a new section with title
        section = nodes.section(ids=[nodes.make_id(check_name)])
        title_text = f'":py:class:`{check_name}`"'
        title_nodes, messages = self.state.inline_text(title_text, self.lineno)
        title = nodes.title(check_name, '', *title_nodes)
        section += title

        admonition = nodes.admonition()
        title_text = doclines[0].rstrip('.')
        title_nodes, messages = self.state.inline_text(title_text, lineno)
        title = nodes.title(title_text, '', *title_nodes)
        admonition += title
        admonition += messages
        self.state.nested_parse(lines[1:], 0, admonition)
        section += admonition

        # add remaining content of directive
        par = nodes.paragraph()
        self.state.nested_parse(self.content, self.content_offset, par)
        section += par

        return [section]
Esempio n. 41
0
    def make_variable_properties(self):
        """Get a node for the variable properties.

        Look at all special properties of the documented variables, and create
        an admonition that describes all these properties in a human-readable
        way.

        Return the admonition node, or ``None``, if the documented variable has
        no special properties.

        """
        title = corenodes.title('Variable properties', 'Variable properties')
        body = corenodes.paragraph('', '')
        props = corenodes.admonition(
            '', title, body, classes=['note', 'el-variable-properties'])
        if self.is_local_variable:
            body += corenodes.Text(
                'Automatically becomes buffer-local when set.  ')
        if self.is_risky_variable:
            body += corenodes.Text(
                'This variable may be risky if used as a file-local '
                'variable.  ')
        safe_predicate = self.get_safe_variable_predicate()
        if safe_predicate:
            body += corenodes.Text(
                'This variable is safe as a file local variable if its value '
                'satisfies the predicate ')
            if SYMBOL_PATTERN.match(safe_predicate):
                xref = addnodes.pending_xref(
                    safe_predicate, reftype='function', refdomain='el',
                    refexplicit=False, reftarget=safe_predicate,
                    refwarn=False, refdoc=self.env.docname)
                set_role_source_info(self.state.inliner, self.lineno, xref)
                xref += corenodes.literal(safe_predicate, safe_predicate,
                                          classes=['xref', 'el', 'el-function'])
                body += xref
            else:
                body += corenodes.literal(safe_predicate, safe_predicate)
            body += corenodes.Text('. ')
        return props if len(body) > 0 else None
Esempio n. 42
0
File: wiki.py Progetto: tkf/neorg
 def apply(self):
     nodes_list_pages = list(self.document.traverse(recent_pages))
     if nodes_list_pages:
         page_path = self.document.settings.neorg_page_path
         for node in nodes_list_pages:
             date_page = self._web.recent_pages(page_path,
                                                node.get('num', 10))
             title = 'Recently Updated Pages'
             admonition = nodes.admonition()
             admonition += nodes.title(title, title)
             bullet_list = nodes.bullet_list(bullet='*')
             bullet_list += [
                 nodes.list_item(
                     '',
                     with_children(
                         nodes.paragraph,
                         [nodes.Text(u'{0}: '.format(d))] +
                         list(gene_link(u'./{0}'.format(l)))
                         ))
                 for (d, l) in date_page]
             admonition += bullet_list
             node.replace_self(admonition)
Esempio n. 43
0
    def run(self):
        self.assert_has_content()

        node = addnodes.only()
        node.document = self.state.document
        set_source_info(self, node)
        node['expr'] = 'iguide'

        text = '\n'.join(self.content)
        admonition_node = nodes.admonition(text, **self.options)
        self.add_name(admonition_node)
            
        title_text = self.arguments[0]
        textnodes, messages = self.state.inline_text(title_text,
                                                     self.lineno)
        admonition_node += nodes.title(title_text, '', *textnodes)
        admonition_node += messages
        admonition_node['classes'] += ['iguide']
        
        self.state.nested_parse(self.content, self.content_offset,
                                admonition_node)
        node += admonition_node

        return [node]
Esempio n. 44
0
 def run(self):
     ul = nodes.bullet_list()
     outdated = False
     for item in self.content:
         split = item.split(' @ ')
         path = split[0]
         region_name = split[1]
         specified_hash = split[2] if len(split) >= 3 else ''
         regions = SLP.get(path)
         region = regions[region_name]
         li = nodes.list_item()
         ul += li
         p = nodes.paragraph('', '')
         li += p
         p += nodes.Text('Defined at ')
         text = '%s:%d-%d' % (region.path, region.start, region.end)
         url = 'https://github.com/bemusic/bemuse/blob/%s/%s#L%d-%d' % (
             HEAD, region.path, region.start, region.end)
         p += nodes.reference('', text, refuri=url)
         expected_hash = region.hash()
         p += nodes.Text(' (%s)' % (region_name,))
         if specified_hash != expected_hash:
             p += nodes.Text(' [outdated: %s]' % (expected_hash,))
             li['classes'].append('outdated')
             outdated = True
     admonition = nodes.admonition()
     admonition['classes'].append('srcref')
     if outdated: admonition['classes'].append('outdated')
     admonition += nodes.title('', 'Source code reference')
     admonition += ul
     # path = '..//%s.txt' % (self.arguments[0])
     # self.state.document.settings.record_dependencies.add(path)
     # with open(path) as f:
     #     data = f.read()
     # self.state_machine.insert_input(data.splitlines(), path)
     return [admonition]