summaryrefslogtreecommitdiffstats
path: root/myst_parser/sphinx_ext/directives.py
blob: 39ca2c659260e64386dbc8ad48a0f48832f5775b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""MyST specific directives"""
from copy import copy
from typing import List, Tuple, cast

from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.directives import SphinxDirective
from sphinx.util.docutils import SphinxRole

from myst_parser.mocking import MockState


def align(argument):
    return directives.choice(argument, ("left", "center", "right"))


def figwidth_value(argument):
    if argument.lower() == "image":
        return "image"
    else:
        return directives.length_or_percentage_or_unitless(argument, "px")


class SubstitutionReferenceRole(SphinxRole):
    """Implement substitution references as a role.

    Note, in ``docutils/parsers/rst/roles.py`` this is left unimplemented.
    """

    def run(self) -> Tuple[List[nodes.Node], List[nodes.system_message]]:
        subref_node = nodes.substitution_reference(self.rawtext, self.text)
        self.set_source_info(subref_node, self.lineno)
        subref_node["refname"] = nodes.fully_normalize_name(self.text)
        return [subref_node], []


class FigureMarkdown(SphinxDirective):
    """Directive for creating a figure with Markdown compatible syntax.

    Example::

        :::{figure-md} target
        <img src="img/fun-fish.png" alt="fishy" class="bg-primary mb-1" width="200px">

        This is a caption in **Markdown**
        :::

    """

    required_arguments = 0
    optional_arguments = 1  # image target
    final_argument_whitespace = True
    has_content = True

    option_spec = {
        "width": figwidth_value,
        "class": directives.class_option,
        "align": align,
        "name": directives.unchanged,
    }

    def run(self) -> List[nodes.Node]:
        figwidth = self.options.pop("width", None)
        figclasses = self.options.pop("class", None)
        align = self.options.pop("align", None)

        if not isinstance(self.state, MockState):
            return [self.figure_error("Directive is only supported in myst parser")]
        state = cast(MockState, self.state)

        # ensure html image enabled
        myst_extensions = copy(state._renderer.md_config.enable_extensions)
        node = nodes.Element()
        try:
            state._renderer.md_config.enable_extensions = list(
                state._renderer.md_config.enable_extensions
            ) + ["html_image"]
            state.nested_parse(self.content, self.content_offset, node)
        finally:
            state._renderer.md_config.enable_extensions = myst_extensions

        if not len(node.children) == 2:
            return [
                self.figure_error(
                    "content should be one image, "
                    "followed by a single paragraph caption"
                )
            ]

        image_node, caption_para = node.children
        if isinstance(image_node, nodes.paragraph):
            image_node = image_node[0]

        if not isinstance(image_node, nodes.image):
            return [
                self.figure_error(
                    "content should be one image (not found), "
                    "followed by single paragraph caption"
                )
            ]

        if not isinstance(caption_para, nodes.paragraph):
            return [
                self.figure_error(
                    "content should be one image, "
                    "followed by single paragraph caption (not found)"
                )
            ]

        caption_node = nodes.caption(caption_para.rawsource, "", *caption_para.children)
        caption_node.source = caption_para.source
        caption_node.line = caption_para.line

        figure_node = nodes.figure("", image_node, caption_node)
        self.set_source_info(figure_node)

        if figwidth is not None:
            figure_node["width"] = figwidth
        if figclasses:
            figure_node["classes"] += figclasses
        if align:
            figure_node["align"] = align
        if self.arguments:
            self.options["name"] = self.arguments[0]
            self.add_name(figure_node)

        return [figure_node]

    def figure_error(self, message):
        """A warning for reporting an invalid figure."""
        error = self.state_machine.reporter.error(
            message,
            nodes.literal_block(self.block_text, self.block_text),
            line=self.lineno,
        )
        return error