예제 #1
0
파일: roles.py 프로젝트: daleevans/sphinx
def abbr_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    # type: (str, str, str, int, Inliner, Dict, List[str]) -> Tuple[List[nodes.Node], List[nodes.system_message]]  # NOQA
    text = utils.unescape(text)
    m = _abbr_re.search(text)
    if m is None:
        return [nodes.abbreviation(text, text, **options)], []
    abbr = text[:m.start()].strip()
    expl = m.group(1)
    options = options.copy()
    options['explanation'] = expl
    return [nodes.abbreviation(abbr, abbr, **options)], []
예제 #2
0
def abbr_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    # type: (str, str, str, int, Inliner, Dict, List[str]) -> Tuple[List[nodes.Node], List[nodes.system_message]]  # NOQA
    text = utils.unescape(text)
    m = _abbr_re.search(text)
    if m is None:
        return [nodes.abbreviation(text, text, **options)], []
    abbr = text[:m.start()].strip()
    expl = m.group(1)
    options = options.copy()
    options['explanation'] = expl
    return [nodes.abbreviation(abbr, abbr, **options)], []
예제 #3
0
def abbr_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    # type: (str, str, str, int, Inliner, Dict, List[str]) -> Tuple[List[nodes.Node], List[nodes.system_message]]  # NOQA
    warnings.warn('abbr_role() is deprecated.  Please use Abbrevation class instead.',
                  RemovedInSphinx40Warning, stacklevel=2)
    text = utils.unescape(text)
    m = _abbr_re.search(text)
    if m is None:
        return [nodes.abbreviation(text, text, **options)], []
    abbr = text[:m.start()].strip()
    expl = m.group(1)
    options = options.copy()
    options['explanation'] = expl
    return [nodes.abbreviation(abbr, abbr, **options)], []
예제 #4
0
    def run(self) -> Tuple[List[Node], List[system_message]]:
        matched = self.abbr_re.search(self.text)
        if matched:
            text = self.text[:matched.start()].strip()
            self.options['explanation'] = matched.group(1)
        else:
            text = self.text

        return [nodes.abbreviation(self.rawtext, text, **self.options)], []
예제 #5
0
    def handle_options(self, sig, signode):
        super(ProtobufServiceMethod, self).handle_options(sig, signode)
        shortname = ProtobufDomain.roles[self.objtype].remove_prefix_func(
            self.options.get('input'))
        params_in = addnodes.desc_parameterlist()
        if shortname == self.options.get('input'):
            paramnode = nodes.inline(text=self.options.get('input'),
                                     classes=["inputtype"])
        else:
            paramnode = nodes.inline(classes=["inputtype"])
            paramnode += nodes.abbreviation(
                text=shortname, explanation=self.options.get('input'))
        params_in.append(paramnode)

        signode += nodes.inline('', ' ')
        signode += params_in
        signode += nodes.inline(text=" -> ")

        if self.options.get('output_stream') == "yes":
            signode += nodes.inline(
                text="stream of ",
                classes=["type_annotation", "streamannotation"])
            signode.parent['classes'].append("streaming")

        shortname = ProtobufDomain.roles[self.objtype].remove_prefix_func(
            self.options.get('output'))
        params_out = addnodes.desc_parameterlist()
        if shortname == self.options.get('output'):
            paramnode = nodes.inline(text=self.options.get('output'),
                                     classes=["outputtype"])
        else:
            paramnode = nodes.inline(classes=["outputtype"])
            paramnode += nodes.abbreviation(
                text=shortname, explanation=self.options.get('output'))
        params_out.append(paramnode)

        signode += params_out
예제 #6
0
 def handle_signature(self, sig, signode):
     # TODO: add to ToC tree of current document. Perhaps get inspiration from
     # https://github.com/rtfd/sphinx-autoapi/blob/60464d0d237d0753e5147a0ec1677f01708a545c/autoapi/extension.py
     # on how to do that.
     sig = sig.strip()
     protobuf_object_type_str = _protobuf_obj_type_to_pretty[self.objtype]
     signode += addnodes.desc_type(text=protobuf_object_type_str)
     signode += nodes.inline('', ' -- ')
     shortname = ProtobufDomain.roles[self.objtype].remove_prefix_func(sig)
     if shortname == sig:
         signamenode = addnodes.desc_name(text=sig)
     else:
         signamenode = addnodes.desc_name()
         signamenode += nodes.abbreviation(text=shortname, explanation=sig)
     signode += signamenode
     signode['sig'] = sig
     self.handle_options(sig, signode)
     return sig
예제 #7
0
    def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                     contnode):
        if typ in {"abbr", "abpl", "gls"}:
            target = f"glossary:{target}".lower()

            # for name, sig, typ, docname, anchor, prio in self.get_objects():
            #     print(name, typ, anchor.lower(), sig)

            match = [(docname, anchor, name, sig) for name, sig, typ, docname,
                     anchor, prio in self.get_objects()
                     if anchor.lower() == target.lower()]

        else:
            return None

        if len(match) > 0:
            todocname = match[0][0]
            targ = match[0][1]

            if typ == "abbr":
                name = self.data['abbreviation-name'][match[0][2]]
            elif typ == "gls":
                name = self.data['names'][match[0][2]]
            elif typ == "abpl" and (match[0][2]
                                    in self.data['abbreviation-plural']):
                name = self.data['abbreviation-plural'][match[0][2]]
            elif typ == "abpl":
                name = self.data['abbreviation-name'][match[0][2]] + "s"
            else:
                name = match[0][2]
            sig = match[0][3]

            if typ in {"abbr", "abpl"}:
                contnode = nodes.abbreviation(text=nodes.Text(name),
                                              explanation=sig)
            else:
                contnode = nodes.Text(name)
            #contnode.elements = [nodes.Text(name)]
            return make_refnode(builder, fromdocname, todocname, targ,
                                contnode, targ)
        else:
            print('Awww, found nothing')
            return None
예제 #8
0
def abbr(name, rawtext, text, lineno, inliner, options={}, content=[]):
    abbr, title = parse_link(text)
    set_classes(options)
    if not abbr:
        return [nodes.abbreviation(title, title, **options)], []
    return [nodes.abbreviation(abbr, abbr, title=title, **options)], []
예제 #9
0
파일: abbr.py 프로젝트: mosra/m.css
def abbr(name, rawtext, text, lineno, inliner, options={}, content=[]):
    abbr, title = parse_link(text)
    set_classes(options)
    if not abbr:
        return [nodes.abbreviation(title, title, **options)], []
    return [nodes.abbreviation(abbr, abbr, title=title, **options)], []
예제 #10
0
    def run(self):
        env = self.state.document.settings.env
        extcode_config = env.app.config.extcode

        if not extcode_config:
            if all(opt not in self.options for opt in self.extra_option_spec):
                return super(ExtCode, self).run()  # nothing to do special

        rendered_block = self.options.get('rendered-block',
                                          extcode_config.get('rendered-block'))

        line_annotations = {}
        annotations = self.options.get('annotations', [])
        annotationsmap = dict((k.astext(), v) for k, v in annotations)
        for i, c in enumerate(self.content):
            match = annotation_matcher(c)
            if match:
                self.content[i], label = match.groups()
                if label in annotationsmap:
                    line_annotations[i] = (label, annotationsmap[label])
                else:
                    #TODO: warning
                    line_annotations[i] = (label, None)

        # get literal from modified self.content
        literal = super(ExtCode, self).run()[0]
        # line_annotations attribute will be used for writer (not yet)
        literal['line_annotations'] = line_annotations

        wrapper = extcode(classes=['extcode'])
        set_source_info(self, wrapper)

        #check: can parse rst? and partial build?
        try:
            partial_doc = sandbox_rst_parser(u'\n'.join(self.content),
                                             env.doc2path(env.docname),
                                             env.settings)
            partial_out = sandbox_partial_builder(partial_doc, env)
        except Exception as e:
            env.warn(env.docname,
                     u'extcode: partial build failed: %s' % str(e),
                     lineno=self.lineno)
            partial_doc = None
            partial_out = None

        if literal['language'] == 'rst' and rendered_block:
            wrapper['classes'].append('extcode-layout-' + rendered_block)

            rendered = nodes.container()
            set_source_info(self, rendered)

            only_html = addnodes.only(expr='html')
            set_source_info(self, only_html)
            only_html += nodes.raw(partial_out,
                                   partial_out,
                                   format='html',
                                   classes=['extcode-rendered'])
            rendered += only_html

            if 'rendered-image' in self.options:
                only_xml = addnodes.only(expr='xml')
                set_source_info(self, only_xml)
                only_xml += nodes.image(self.options['rendered-image'],
                                        uri=self.options['rendered-image'])
                rendered += only_xml

            #FIXME: need translation support
            make_text = lambda t: nodes.inline(t, t)

            if rendered_block == 'horizontal':
                table = build_table(
                    [[make_text('literal'),
                      make_text('rendered')], [literal, rendered]], [1, 1],
                    head_rows=1,
                    attrs={'classes': ['extcode-layout']})
                table.setdefault('classes', []).append('extcode-layout')
                wrapper.append(table)

            elif rendered_block == 'vertical':
                table = build_table([[make_text('literal'), literal],
                                     [make_text('rendered'), rendered]],
                                    [2, 8],
                                    stub_columns=1,
                                    attrs={'classes': ['extcode-layout']})
                table.setdefault('classes', []).append('extcode-layout')
                wrapper.append(table)

            else:  # toggle, tab
                wrapper.append(literal)
                wrapper.append(rendered)
        else:
            wrapper.append(literal)

        if line_annotations and 'annotate-inline' in self.options:
            prefix = '... '  #TODO prefixi customization
            contents = []
            for i in range(0, len(self.content)):
                label, value = line_annotations.get(i, ('', None))
                line = nodes.line()
                if label and value:
                    #FIXME: label and explanation need translation support
                    abbr = nodes.abbreviation(
                        label, label
                    )  #TODO: label customization (i.e. render with number)
                    abbr['explanation'] = value.astext()
                    line.append(nodes.inline(prefix, prefix))
                    line.append(abbr)
                elif label:
                    line.append(nodes.inline(prefix, prefix))
                    line.append(nodes.Text(label, label))
                contents.append(line)
            overlay = nodes.line_block(classes=['extcode-overlay'])
            set_source_info(self, overlay)
            overlay.extend(contents)
            wrapper.append(overlay)

        if annotations and 'annotate-block' in self.options:
            annotations['classes'] = ['extcode-annotations']
            set_source_info(self, annotations)
            wrapper.append(annotations)

        return [wrapper]
예제 #11
0
    def run(self) -> list[Any]:
        self.assert_has_content()

        package_name = self.options['tdpackage']

        section = nodes.section()
        section.line = self.lineno
        section.lineno = self.lineno

        td_title = self.arguments[0]
        title = nodes.title(text=td_title)
        section['ids'].append(f"{package_name}-{td_title}")
        TDPROTO_TARGETS[(package_name, td_title)] = section

        structure_description = []
        fields_list = nodes.bullet_list()
        fields_list.append(nodes.line(text='Fields:'))

        for x in self.content:
            if not x.startswith(':field '):
                structure_description.append(x)
                continue

            field_options_str, field_text = tuple(x.split(':',
                                                          maxsplit=2
                                                          )[1:])
            field_text = field_text.lstrip(' ')

            field_options_list = field_options_str.split()

            field_line = TdprotoStructFieldLine()

            for i, option in enumerate(field_options_list):
                if i == 0:
                    ...
                elif i == 1:
                    field_line.append(nodes.literal(text=option))
                elif i == 2:
                    if '`' in option:
                        is_array = False

                        if option.startswith('array'):
                            is_array = True

                        reference_target = option.split('`')[1]
                        reference_name = reference_target.split('-')[1]

                        new_ref = addnodes.pending_xref(
                            refdomain='tdproto',
                            reftarget=reference_name,
                            reftype='tdmodels',
                            refdoc='data_index',
                            refexplicit=True,
                            refwarn=True,
                        )
                        ref_name = option.replace(
                            f"`{reference_target}`", reference_name)
                        new_ref.append(nodes.inline(text=ref_name))

                        if is_array:
                            start_node = nodes.inline(text=' (array[')
                        else:
                            start_node = nodes.inline(text=' (')

                        start_node.append(new_ref)

                        if is_array:
                            start_node.append(nodes.inline(text='])'))
                        else:
                            start_node.append(nodes.inline(text=')'))

                        field_line.append(start_node)
                    else:
                        field_line.append(nodes.inline(text=f" ({option})"))
                elif i == 3:
                    if option == 'omitempty':
                        omit_empty_abbreviation = nodes.abbreviation(
                            text=' 💥 ')
                        omit_empty_abbreviation.attributes['explanation'] \
                            = OMIT_EMPTY_STR

                        field_line.append(omit_empty_abbreviation)
                    elif option == 'nullable':
                        maybe_null_abbreviation = nodes.abbreviation(
                            text=' 0️⃣ ')
                        maybe_null_abbreviation.attributes['explanation'] \
                            = MAYBE_NULL_STR

                        field_line.append(maybe_null_abbreviation)
                    else:
                        raise ValueError('Unknown modifier')
                else:
                    raise ValueError('Too many options')

            field_line.append(nodes.inline(text=" — "))
            field_line.append(nodes.inline(text=field_text))

            fields_list.append(field_line)

        paragraph = nodes.paragraph()
        self.state.nested_parse(
            self.content[:2],
            self.content_offset,
            paragraph,
        )

        section.extend([title, paragraph, fields_list])

        return [section]
예제 #12
0
def make_stat_table(parent_docname: str,
                    metadata: DefaultDict[str, dict]) -> nodes.table:
    """Create a table of statistics on executed notebooks."""

    # top-level element
    table = nodes.table()
    table["classes"] += ["colwidths-auto"]
    # self.set_source_info(table)

    # column settings element
    ncols = len(_key2header) + 1
    tgroup = nodes.tgroup(cols=ncols)
    table += tgroup
    colwidths = [round(100 / ncols, 2)] * ncols
    for colwidth in colwidths:
        colspec = nodes.colspec(colwidth=colwidth)
        tgroup += colspec

    # header
    thead = nodes.thead()
    tgroup += thead
    row = nodes.row()
    thead += row

    for name in ["Document"] + list(_key2header.values()):
        row.append(nodes.entry("", nodes.paragraph(text=name)))

    # body
    tbody = nodes.tbody()
    tgroup += tbody

    for docname in sorted(metadata):
        data = metadata[docname].get("exec_data")
        if not data:
            continue
        row = nodes.row()
        tbody += row

        # document name
        doclink = pending_xref(
            refdoc=parent_docname,
            reftarget=posixpath.relpath(docname,
                                        posixpath.dirname(parent_docname)),
            reftype="doc",
            refdomain="std",
            refexplicit=True,
            refwarn=True,
            classes=["xref", "doc"],
        )
        doclink += nodes.inline(text=docname)
        paragraph = nodes.paragraph()
        paragraph += doclink
        row.append(nodes.entry("", paragraph))

        # other rows
        for name in _key2header.keys():
            paragraph = nodes.paragraph()
            if name == "succeeded" and data[name] is False:
                paragraph += nodes.abbreviation(
                    text=_key2transform[name](data[name]),
                    explanation=(data["error"] or ""),
                )
            else:
                paragraph += nodes.Text(_key2transform[name](data[name]))
            row.append(nodes.entry("", paragraph))

    return table
예제 #13
0
def abbr(name, rawtext, text, lineno, inliner, options={}, content=[]):
    abbr, title = parse_link(text)
    if not title:
        return [nodes.abbreviation(abbr, abbr)], []
    return [nodes.abbreviation(abbr, abbr, title=title)], []