当前位置: 首页>>代码示例>>Python>>正文


Python nodes.Node方法代码示例

本文整理汇总了Python中docutils.nodes.Node方法的典型用法代码示例。如果您正苦于以下问题:Python nodes.Node方法的具体用法?Python nodes.Node怎么用?Python nodes.Node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在docutils.nodes的用法示例。


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

示例1: visit_inline

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def visit_inline(self, node):
    # type: (nodes.Node) -> None
    classes = node.get('classes', [])
    if classes in [['menuselection'], ['guilabel']]:
        self.body.append(r'\sphinxmenuselection{')
        self.context.append('}')
    elif classes in [['accelerator']]:
        self.body.append(r'\sphinxaccelerator{')
        self.context.append('}')
    elif classes in [['xref','doc']] and not self.in_title:
        self.body.append(ur'第\DUrole{%s}{' % ','.join(classes))
        self.context.append(u'}章')
    elif classes and not self.in_title:
        self.body.append(r'\DUrole{%s}{' % ','.join(classes))
        self.context.append('}')
    else:
        self.context.append('') 
开发者ID:future-architect,项目名称:typescript-guide,代码行数:19,代码来源:numdoc.py

示例2: visit_inline

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def visit_inline(self, node):
    # type: (nodes.Node) -> None
    classes = node.get('classes', [])
    if classes in [['menuselection'], ['guilabel']]:
        self.body.append(r'\sphinxmenuselection{')
        self.context.append('}')
    elif classes in [['accelerator']]:
        self.body.append(r'\sphinxaccelerator{')
        self.context.append('}')
    elif classes in [['xref','doc']] and not self.in_title:
        self.body.append(u(r'第\DUrole{%s}{') % u(',').join(classes))
        self.context.append(u'}章')
    elif classes and not self.in_title:
        self.body.append(u(r'\DUrole{%s}{') % u(',').join(classes))
        self.context.append('}')
    else:
        self.context.append('') 
开发者ID:future-architect,项目名称:typescript-guide,代码行数:19,代码来源:numdoc_py3.py

示例3: process_only_nodes

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def process_only_nodes(config, document, tags):
    # type: (nodes.Node, Tags) -> None
    """Filter ``only`` nodes which does not match *tags* or html (through config)"""
    ret_html_cell = config['jupyter_allow_html_only'] 
    for node in document.traverse(addnodes.only):
        try:
            ret = tags.eval_condition(node['expr'])  #check for jupyter only
            if ret_html_cell and node['expr'] == 'html':  #allow html only cells if option is specified
                ret = True
        except Exception as err:
            logger.warning(__('exception while evaluating only directive expression: %s'), err,
                           location=node)
            node.replace_self(node.children or nodes.comment())
        else:
            if ret:
                node.replace_self(node.children or nodes.comment())
            else:
                # A comment on the comment() nodes being inserted: replacing by [] would
                # result in a "Losing ids" exception if there is a target node before
                # the only node, so we make sure docutils can transfer the id to
                # something, even if it's just a comment and will lose the id anyway...
                node.replace_self(nodes.comment()) 
开发者ID:QuantEcon,项目名称:sphinxcontrib-jupyter,代码行数:24,代码来源:__init__.py

示例4: figure_wrapper

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def figure_wrapper(directive, node, caption):
    # type: (Directive, nodes.Node, unicode) -> nodes.figure
    figure_node = nodes.figure('', node)
    if 'align' in node:
        figure_node['align'] = node.attributes.pop('align')

    parsed = nodes.Element()
    directive.state.nested_parse(ViewList([caption], source=''),
                                 directive.content_offset, parsed)
    caption_node = nodes.caption(parsed[0].rawsource, '',
                                 *parsed[0].children)
    caption_node.source = parsed[0].source
    caption_node.line = parsed[0].line
    figure_node += caption_node
    return figure_node 
开发者ID:kevinpt,项目名称:symbolator,代码行数:17,代码来源:symbolator_sphinx.py

示例5: visit_collected_footnote

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def visit_collected_footnote(self, node):
    # type: (nodes.Node) -> None
    self.in_footnote += 1
    if 'footnotetext' in node:
        self.body.append('\\footnotetext{')
    else:
        if self.in_parsed_literal:
            self.body.append('\\footnote{')
        else:
            self.body.append('\\footnote{') 
开发者ID:future-architect,项目名称:typescript-guide,代码行数:12,代码来源:orgfootnote.py

示例6: depart_collected_footnote

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def depart_collected_footnote(self, node):
    # type: (nodes.Node) -> None
    if 'footnotetext' in node:
        self.body.append('}\\ignorespaces ')
    else:
        if self.in_parsed_literal:
            self.body.append('}')
        else:
            self.body.append('}')
    self.in_footnote -= 1 
开发者ID:future-architect,项目名称:typescript-guide,代码行数:12,代码来源:orgfootnote.py

示例7: parse_generated_content

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def parse_generated_content(state: RSTState, content: StringList, documenter: Documenter
                            ) -> List[Node]:
    """Parse a generated content by Documenter."""
    with switch_source_input(state, content):
        if documenter.titles_allowed:
            node = nodes.section()  # type: Element
            # necessary so that the child nodes get the right source/line set
            node.document = state.document
            nested_parse_with_titles(state, content, node)
        else:
            node = nodes.paragraph()
            node.document = state.document
            state.nested_parse(content, 0, node)

        return node.children 
开发者ID:thu-coai,项目名称:cotk,代码行数:17,代码来源:directive.py

示例8: run

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def run(self) -> List[Node]:
        reporter = self.state.document.reporter

        try:
            source, lineno = reporter.get_source_and_line(self.lineno)  # type: ignore
        except AttributeError:
            source, lineno = (None, None)
        logger.debug('[autodoc] %s:%s: input:\n%s', source, lineno, self.block_text)

        # look up target Documenter
        objtype = self.name[4:]  # strip prefix (auto-).
        doccls = get_documenters(self.env.app)[objtype]

        # process the options with the selected documenter's option_spec
        try:
            documenter_options = process_documenter_options(doccls, self.config, self.options)
        except (KeyError, ValueError, TypeError) as exc:
            # an option is either unknown or has a wrong type
            logger.error('An option to %s is either unknown or has an invalid value: %s' %
                         (self.name, exc), location=(source, lineno))
            return []

        # generate the output
        params = DocumenterBridge(self.env, reporter, documenter_options, lineno, self.state)
        documenter = doccls(params, self.arguments[0])
        documenter.generate(more_content=self.content)
        if not params.result:
            return []

        logger.debug('[autodoc] output:\n%s', '\n'.join(params.result))

        # record all filenames as dependencies -- this will at least
        # partially make automatic invalidation possible
        for fn in params.filename_set:
            self.state.document.settings.record_dependencies.add(fn)

        result = parse_generated_content(self.state, params.result, documenter)
        return result 
开发者ID:thu-coai,项目名称:cotk,代码行数:40,代码来源:directive.py

示例9: run

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def run(self) -> typing.List[nodes.Node]:
        self.assert_has_content()
        text = "\n".join(self.content)

        gen = []
        # Add html version
        html_text = '<div class="highlight">\n' + text + "\n</div>"
        gen.append(nodes.raw(text, html_text, format="html"))

        # Add latex version
        latex_text = "\\begin{sphinxVerbatim}[commandchars=\\\\\\{\\}]\n"
        transformed = text
        transformed = transformed.replace("\\", "\\textbackslash{}")
        transformed = self.pat_pre.sub("", transformed)
        transformed = self.pat_color.sub(r"\\textcolor[HTML]{\1}{\2}", transformed)
        transformed = self.pat_bold.sub(r"\\textbf{\1}", transformed)
        transformed = transformed.replace("&lt;", "<")
        transformed = transformed.replace("&gt;", ">")
        transformed = transformed.replace("&apos;", r"\textsc{\char39}")
        transformed = transformed.replace("&quot;", '"')
        latex_text += transformed
        latex_text += "\n\\end{sphinxVerbatim}"
        gen.append(nodes.raw(text, latex_text, format="latex"))

        return gen


# }}}

# -- Fix instance variables being cross-referenced --------------------------- {{{ 
开发者ID:Rahix,项目名称:tbot,代码行数:32,代码来源:conf.py

示例10: run

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def run(self):
        # type: () -> List[nodes.Node]
        if self.arguments:
            document = self.state.document
            if self.content:
                return [document.reporter.warning(
                    __('Symbolator directive cannot have both content and '
                    'a filename argument'), line=self.lineno)]
            env = self.state.document.settings.env
            argument = search_image_for_language(self.arguments[0], env)
            rel_filename, filename = env.relfn2path(argument)
            env.note_dependency(rel_filename)
            try:
                with codecs.open(filename, 'r', 'utf-8') as fp:
                    symbolator_code = fp.read()
            except (IOError, OSError):
                return [document.reporter.warning(
                    __('External Symbolator file %r not found or reading '
                    'it failed') % filename, line=self.lineno)]
        else:
            symbolator_code = '\n'.join(self.content)
            if not symbolator_code.strip():
                return [self.state_machine.reporter.warning(
                    __('Ignoring "symbolator" directive without content.'),
                    line=self.lineno)]
        node = symbolator()
        node['code'] = symbolator_code
        node['options'] = {}
        if 'symbolator_cmd' in self.options:
            node['options']['symbolator_cmd'] = self.options['symbolator_cmd']
        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']
            
        if 'name' in self.options:
          node['options']['name'] = self.options['name']

        caption = self.options.get('caption')
        if caption:
            node = figure_wrapper(self, node, caption)

        self.add_name(node)
        return [node] 
开发者ID:kevinpt,项目名称:symbolator,代码行数:46,代码来源:symbolator_sphinx.py

示例11: run_directive

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError as detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError as error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank()) 
开发者ID:skarlekar,项目名称:faces,代码行数:61,代码来源:states.py

示例12: make_field

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def make_field(
        self,
        types: Dict[str, List[nodes.Node]],
        domain: str,
        items: Tuple[str, List[nodes.inline]],
        env: BuildEnvironment = None,
    ) -> nodes.field:
        def makerefs(rolename, name, node):
            return self.make_xrefs(rolename, domain, name, node, env=env)

        def handle_item(
            fieldarg: str, content: List[nodes.inline]
        ) -> nodes.definition_list_item:
            head = nodes.term()
            head += makerefs(self.rolename, fieldarg, addnodes.literal_strong)
            fieldtype = types.pop(fieldarg, None)
            if fieldtype is not None:
                head += nodes.Text(" : ")
                if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text):
                    (text_node,) = fieldtype  # type: nodes.Text
                    head += makerefs(
                        self.typerolename, text_node.astext(), addnodes.literal_emphasis
                    )
                else:
                    head += fieldtype

            body_content = nodes.paragraph("", "", *content)
            body = nodes.definition("", body_content)

            return nodes.definition_list_item("", head, body)

        fieldname = nodes.field_name("", self.label)
        if len(items) == 1 and self.can_collapse:
            fieldarg, content = items[0]
            bodynode = handle_item(fieldarg, content)
        else:
            bodynode = self.list_type()
            for fieldarg, content in items:
                bodynode += handle_item(fieldarg, content)
        fieldbody = nodes.field_body("", bodynode)
        return nodes.field("", fieldname, fieldbody)


# replace matching field types with ours 
开发者ID:theislab,项目名称:scvelo,代码行数:46,代码来源:conf.py

示例13: patched_make_field

# 需要导入模块: from docutils import nodes [as 别名]
# 或者: from docutils.nodes import Node [as 别名]
def patched_make_field(
    self,  # type: TypedField
    types,  # type: typing.Dict[str, typing.List[nodes.Node]]
    domain,  # type: str
    items,  # type: typing.Tuple
    env=None,  # type: typing.Any
):
    # type: (...) -> nodes.field
    def handle_item(fieldarg, content):
        # type: (str, str) -> nodes.paragraph
        par = nodes.paragraph()
        par += addnodes.literal_strong("", fieldarg)  # Patch: this line added
        # par.extend(self.make_xrefs(self.rolename, domain, fieldarg,
        #                            addnodes.literal_strong, env=env))
        if fieldarg in types:
            par += nodes.Text(" (")
            # NOTE: using .pop() here to prevent a single type node to be
            # inserted twice into the doctree, which leads to
            # inconsistencies later when references are resolved
            fieldtype = types.pop(fieldarg)
            if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text):
                typename = u"".join(n.astext() for n in fieldtype)
                par.extend(
                    self.make_xrefs(
                        self.typerolename,
                        domain,
                        typename,
                        addnodes.literal_emphasis,
                        env=env,
                    )
                )
            else:
                par += fieldtype
            par += nodes.Text(")")
        par += nodes.Text(" -- ")
        par += content
        return par

    fieldname = nodes.field_name("", self.label)
    if len(items) == 1 and self.can_collapse:
        fieldarg, content = items[0]
        bodynode = handle_item(fieldarg, content)
    else:
        bodynode = self.list_type()
        for fieldarg, content in items:
            bodynode += nodes.list_item("", handle_item(fieldarg, content))
    fieldbody = nodes.field_body("", bodynode)
    return nodes.field("", fieldname, fieldbody) 
开发者ID:Rahix,项目名称:tbot,代码行数:50,代码来源:conf.py


注:本文中的docutils.nodes.Node方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。