Beispiel #1
0
def page_role(_role: str,
              rawtext: str,
              text: str,
              lineno: int,
              inliner: Inliner,
              options: dict = None,
              _content: dict = None):
    if options is None:
        options = {}

    set_classes(options)

    if "/" in text:
        parts = [escape(x) for x in text.rsplit("/", 1)]
    else:
        msg = inliner.reporter.error(
            "Page specification must be in the form <page_slug>/<text>",
            line=lineno)
        prb = inliner.problematic(text, rawtext, msg)

        return [prb], [msg]

    try:
        url = url_for("wiki.page", page=parts[0])
        name = parts[1]

        html = f"""<a href="{url}">{name}</a>"""

        node = nodes.raw(html, html, format="html", **options)
        return [node], []
    except Exception as e:
        msg = inliner.reporter.error(str(e), line=lineno)
        prb = inliner.problematic(text, rawtext, msg)

        return [prb], [msg]
Beispiel #2
0
def icon_role(_role: str,
              rawtext: str,
              text: str,
              lineno: int,
              inliner: Inliner,
              options: dict = None,
              _content: dict = None):
    if options is None:
        options = {}

    set_classes(options)

    if "/" in text:
        parts = [escape(x) for x in text.split("/")]
    else:
        msg = inliner.reporter.error(
            "Icon specification must be in the form <type>/<name>",
            line=lineno)
        prb = inliner.problematic(text, rawtext, msg)

        return [prb], [msg]

    if len(parts) != 2:
        msg = inliner.reporter.error(
            "Icon specification must be in the form <type>/<name>",
            line=lineno)
        prb = inliner.problematic(text, rawtext, msg)

        return [prb], [msg]
    else:
        if parts[0] == "light":
            weight = "fal"
        elif parts[0] == "regular":
            weight = "far"
        elif parts[0] == "solid":
            weight = "fas"
        elif parts[0] == "branding":
            weight = "fab"
        else:
            msg = inliner.reporter.error(
                "Icon type must be one of light, regular, solid or branding",
                line=lineno)
            prb = inliner.problematic(text, rawtext, msg)

            return [prb], [msg]

        html = f"""<i class="uk-icon fa-fw {weight} fa-{parts[1]}"></i>"""

        node = nodes.raw(html, html, format="html", **options)
        return [node], []
def fcicon_role(name: str,
                rawtext: str,
                text: str,
                lineno: int,
                inliner: Inliner,
                options: dict = {},
                content: List[str] = []):
    """FreeCAD Icon role function.

    Returns 2 part tuple containing list of nodes to insert into the
    document and a list of system messages.  Both are allowed to be
    empty.

    For additional information on role functions, see:
        * https://docutils.readthedocs.io/en/sphinx-docs/howto/rst-roles.html
        * https://doughellmann.com/blog/2010/05/09/defining-custom-roles-in-sphinx/

    :param name: The role name used in the document.
    :param rawtext: The entire markup snippet, with role.
    :param text: The text marked with the role.
    :param lineno: The line number where rawtext appears in the input.
    :param inliner: The inliner instance that called us.
    :param options: Directive options for customization.
    :param content: The directive content for customization.
    """
    try:
        pattern = re.compile('([\w\s]+) \((sm|md|lg)\) \<(.*\.\w+)\>')
        result = pattern.search(text)
        if not result or len(result.groups()) != 3:
            raise ValueError
        alt, size, filename = result.groups()
    except ValueError:
        msg = inliner.reporter.error(
            'FreeCAD Icon must include alt, size (sm, md, or lg), and filename (e.g. :fcicon:`My Icon Alt (md) <MyIcon.svg>`); '
            '"%s" is invalid.' % text, line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    app = inliner.document.settings.env.app
    try:
        freecad_icon_directory = app.config.freecad_icon_directory
        if not freecad_icon_directory:
            raise AttributeError
    except AttributeError:
        raise ValueError(
            'freecad_icon_directory configuration value is not set')
    image = make_image_node(freecad_icon_directory, alt, size, filename)
    return [image], []
Beispiel #4
0
def nxt_hint_role_fn(_: str, rawtext: str, text: str, lineno: int, inliner:
        Inliner, *args: Any) -> Tuple[List[Node], List[system_message]]:
    """The nxt_hint role handler for inline text outside code blocks."""

    node = nxt_hint()
    groups = re.search(NXT_HINT_REGEX,
                       rawtext.replace('\n', ' ').replace('\r', ''))

    try:
        node.term, node.tip = groups.group(1), groups.group(2)
    except IndexError:
        msg = inliner.reporter.error(
            f'Inline term "{text}" is invalid.', line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]

    return [node], []
Beispiel #5
0
def indexmarkup_role(
        typ: str,
        rawtext: str,
        text: str,
        lineno: int,
        inliner: Inliner,
        options: Dict = {},
        content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
    """Role for PEP/RFC references that generate an index entry."""
    warnings.warn(
        'indexmarkup_role() is deprecated.  Please use PEP or RFC class instead.',
        RemovedInSphinx40Warning,
        stacklevel=2)
    env = inliner.document.settings.env
    if not typ:
        assert env.temp_data['default_role']
        typ = env.temp_data['default_role'].lower()
    else:
        typ = typ.lower()

    has_explicit_title, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    targetid = 'index-%s' % env.new_serialno('index')
    indexnode = addnodes.index()
    targetnode = nodes.target('', '', ids=[targetid])
    inliner.document.note_explicit_target(targetnode)
    if typ == 'pep':
        indexnode['entries'] = [
            ('single', _('Python Enhancement Proposals; PEP %s') % target,
             targetid, '', None)
        ]
        anchor = ''
        anchorindex = target.find('#')
        if anchorindex > 0:
            target, anchor = target[:anchorindex], target[anchorindex:]
        if not has_explicit_title:
            title = "PEP " + utils.unescape(title)
        try:
            pepnum = int(target)
        except ValueError:
            msg = inliner.reporter.error('invalid PEP number %s' % target,
                                         line=lineno)
            prb = inliner.problematic(rawtext, rawtext, msg)
            return [prb], [msg]
        ref = inliner.document.settings.pep_base_url + 'pep-%04d' % pepnum
        sn = nodes.strong(title, title)
        rn = nodes.reference('',
                             '',
                             internal=False,
                             refuri=ref + anchor,
                             classes=[typ])
        rn += sn
        return [indexnode, targetnode, rn], []
    elif typ == 'rfc':
        indexnode['entries'] = [('single', 'RFC; RFC %s' % target, targetid,
                                 '', None)]
        anchor = ''
        anchorindex = target.find('#')
        if anchorindex > 0:
            target, anchor = target[:anchorindex], target[anchorindex:]
        if not has_explicit_title:
            title = "RFC " + utils.unescape(title)
        try:
            rfcnum = int(target)
        except ValueError:
            msg = inliner.reporter.error('invalid RFC number %s' % target,
                                         line=lineno)
            prb = inliner.problematic(rawtext, rawtext, msg)
            return [prb], [msg]
        ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum
        sn = nodes.strong(title, title)
        rn = nodes.reference('',
                             '',
                             internal=False,
                             refuri=ref + anchor,
                             classes=[typ])
        rn += sn
        return [indexnode, targetnode, rn], []
    else:
        raise ValueError('unknown role type: %s' % typ)