We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add import statements to examples in documentation
See title.

The examples in the documentation should also include the `from manim import *` at the very least, and actually we could provide best-practice examples where we dont do a *-import, but rather import classes/functions separately.

This can of course be an iterative process: start with adding `from manim import *` first, and become more specific later.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `docs/source/manim_directive.py`
Content:
```
1 r"""
2 A directive for including Manim videos in a Sphinx document
3 ===========================================================
4 
5 When rendering the HTML documentation, the ``.. manim::`` directive
6 implemented here allows to include rendered videos.
7 
8 Its basic usage that allows processing **inline content**
9 looks as follows::
10 
11     .. manim:: MyScene
12 
13         class MyScene(Scene):
14             def construct(self):
15                 ...
16 
17 It is required to pass the name of the class representing the
18 scene to be rendered to the directive.
19 
20 As a second application, the directive can also be used to
21 render scenes that are defined within doctests, for example::
22 
23     .. manim:: DirectiveDoctestExample
24         :ref_classes: Dot
25 
26         >>> dot = Dot(color=RED)
27         >>> dot.color
28         <Color #fc6255>
29         >>> class DirectiveDoctestExample(Scene):
30         ...     def construct(self):
31         ...         self.play(Create(dot))
32 
33 
34 Options
35 -------
36 
37 Options can be passed as follows::
38 
39     .. manim:: <Class name>
40         :<option name>: <value>
41 
42 The following configuration options are supported by the
43 directive:
44 
45     hide_source
46         If this flag is present without argument,
47         the source code is not displayed above the rendered video.
48 
49     quality : {'low', 'medium', 'high', 'fourk'}
50         Controls render quality of the video, in analogy to
51         the corresponding command line flags.
52 
53     save_as_gif
54         If this flag is present without argument,
55         the scene is rendered as a gif.
56 
57     save_last_frame
58         If this flag is present without argument,
59         an image representing the last frame of the scene will
60         be rendered and displayed, instead of a video.
61 
62     ref_classes
63         A list of classes, separated by spaces, that is
64         rendered in a reference block after the source code.
65 
66     ref_functions
67         A list of functions, separated by spaces,
68         that is rendered in a reference block after the source code.
69 
70     ref_methods
71         A list of methods, separated by spaces,
72         that is rendered in a reference block after the source code.
73 
74 """
75 import os
76 import shutil
77 from os.path import relpath
78 from pathlib import Path
79 from typing import List
80 
81 import jinja2
82 from docutils import nodes
83 from docutils.parsers.rst import Directive, directives
84 from docutils.statemachine import StringList
85 
86 from manim import QUALITIES
87 
88 classnamedict = {}
89 
90 
91 class skip_manim_node(nodes.Admonition, nodes.Element):
92     pass
93 
94 
95 def visit(self, node, name=""):
96     self.visit_admonition(node, name)
97 
98 
99 def depart(self, node):
100     self.depart_admonition(node)
101 
102 
103 def process_name_list(option_input: str, reference_type: str) -> List[str]:
104     r"""Reformats a string of space separated class names
105     as a list of strings containing valid Sphinx references.
106 
107     Tests
108     -----
109 
110     ::
111 
112         >>> process_name_list("Tex TexTemplate", "class")
113         [":class:`~.Tex`", ":class:`~.TexTemplate`"]
114         >>> process_name_list("Scene.play Mobject.rotate", "func")
115         [":func:`~.Scene.play`", ":func:`~.Mobject.rotate`"]
116     """
117     return [f":{reference_type}:`~.{name}`" for name in option_input.split()]
118 
119 
120 class ManimDirective(Directive):
121     r"""The manim directive, rendering videos while building
122     the documentation.
123 
124     See the module docstring for documentation.
125     """
126     has_content = True
127     required_arguments = 1
128     optional_arguments = 0
129     option_spec = {
130         "hide_source": bool,
131         "quality": lambda arg: directives.choice(
132             arg, ("low", "medium", "high", "fourk")
133         ),
134         "save_as_gif": bool,
135         "save_last_frame": bool,
136         "ref_modules": lambda arg: process_name_list(arg, "mod"),
137         "ref_classes": lambda arg: process_name_list(arg, "class"),
138         "ref_functions": lambda arg: process_name_list(arg, "func"),
139         "ref_methods": lambda arg: process_name_list(arg, "meth"),
140     }
141     final_argument_whitespace = True
142 
143     def run(self):
144         if "skip-manim" in self.state.document.settings.env.app.builder.tags.tags:
145             node = skip_manim_node()
146             self.state.nested_parse(
147                 StringList(self.content[0]), self.content_offset, node
148             )
149             return [node]
150 
151         from manim import config
152 
153         global classnamedict
154 
155         clsname = self.arguments[0]
156         if clsname not in classnamedict:
157             classnamedict[clsname] = 1
158         else:
159             classnamedict[clsname] += 1
160 
161         hide_source = "hide_source" in self.options
162         save_as_gif = "save_as_gif" in self.options
163         save_last_frame = "save_last_frame" in self.options
164         assert not (save_as_gif and save_last_frame)
165 
166         ref_content = (
167             self.options.get("ref_modules", [])
168             + self.options.get("ref_classes", [])
169             + self.options.get("ref_functions", [])
170             + self.options.get("ref_methods", [])
171         )
172         if ref_content:
173             ref_block = "References: " + " ".join(ref_content)
174 
175         else:
176             ref_block = ""
177 
178         if "quality" in self.options:
179             quality = f'{self.options["quality"]}_quality'
180         else:
181             quality = "example_quality"
182         frame_rate = QUALITIES[quality]["frame_rate"]
183         pixel_height = QUALITIES[quality]["pixel_height"]
184         pixel_width = QUALITIES[quality]["pixel_width"]
185         qualitydir = f"{pixel_height}p{frame_rate}"
186 
187         state_machine = self.state_machine
188         document = state_machine.document
189 
190         source_file_name = document.attributes["source"]
191         source_rel_name = relpath(source_file_name, setup.confdir)
192         source_rel_dir = os.path.dirname(source_rel_name)
193         while source_rel_dir.startswith(os.path.sep):
194             source_rel_dir = source_rel_dir[1:]
195 
196         dest_dir = os.path.abspath(
197             os.path.join(setup.app.builder.outdir, source_rel_dir)
198         )
199         if not os.path.exists(dest_dir):
200             os.makedirs(dest_dir)
201 
202         source_block = [
203             ".. code-block:: python",
204             "",
205             *["    " + line for line in self.content],
206         ]
207         source_block = "\n".join(source_block)
208 
209         config.media_dir = Path(setup.confdir) / "media"
210         config.images_dir = "{media_dir}/images"
211         config.video_dir = "{media_dir}/videos/{quality}"
212         output_file = f"{clsname}-{classnamedict[clsname]}"
213         config.assets_dir = Path("_static")
214 
215         config_code = [
216             f'config["frame_rate"] = {frame_rate}',
217             f'config["pixel_height"] = {pixel_height}',
218             f'config["pixel_width"] = {pixel_width}',
219             f'config["save_last_frame"] = {save_last_frame}',
220             f'config["save_as_gif"] = {save_as_gif}',
221             f'config["write_to_movie"] = {not save_last_frame}',
222             f'config["output_file"] = r"{output_file}"',
223         ]
224 
225         user_code = self.content
226         if user_code[0].startswith(">>> "):  # check whether block comes from doctest
227             user_code = [
228                 line[4:] for line in user_code if line.startswith((">>> ", "... "))
229             ]
230 
231         code = [
232             "from manim import *",
233             *config_code,
234             *user_code,
235             f"{clsname}().render()",
236         ]
237         exec("\n".join(code), globals())
238 
239         # copy video file to output directory
240         if not (save_as_gif or save_last_frame):
241             filename = f"{output_file}.mp4"
242             filesrc = config.get_dir("video_dir") / filename
243             destfile = os.path.join(dest_dir, filename)
244             shutil.copyfile(filesrc, destfile)
245         elif save_as_gif:
246             filename = f"{output_file}.gif"
247             filesrc = config.get_dir("video_dir") / filename
248         elif save_last_frame:
249             filename = f"{output_file}.png"
250             filesrc = config.get_dir("images_dir") / filename
251         else:
252             raise ValueError("Invalid combination of render flags received.")
253 
254         rendered_template = jinja2.Template(TEMPLATE).render(
255             clsname=clsname,
256             clsname_lowercase=clsname.lower(),
257             hide_source=hide_source,
258             filesrc_rel=os.path.relpath(filesrc, setup.confdir),
259             output_file=output_file,
260             save_last_frame=save_last_frame,
261             save_as_gif=save_as_gif,
262             source_block=source_block,
263             ref_block=ref_block,
264         )
265         state_machine.insert_input(
266             rendered_template.split("\n"), source=document.attributes["source"]
267         )
268 
269         return []
270 
271 
272 def setup(app):
273     import manim
274 
275     app.add_node(skip_manim_node, html=(visit, depart))
276 
277     setup.app = app
278     setup.config = app.config
279     setup.confdir = app.confdir
280 
281     app.add_directive("manim", ManimDirective)
282 
283     metadata = {"parallel_read_safe": False, "parallel_write_safe": True}
284     return metadata
285 
286 
287 TEMPLATE = r"""
288 {% if not hide_source %}
289 .. raw:: html
290 
291     <div id="{{ clsname_lowercase }}" class="admonition admonition-manim-example">
292     <p class="admonition-title">Example: {{ clsname }} <a class="headerlink" href="#{{ clsname_lowercase }}">¶</a></p>
293 
294 {% endif %}
295 
296 {% if not (save_as_gif or save_last_frame) %}
297 .. raw:: html
298 
299     <video class="manim-video" controls loop autoplay src="./{{ output_file }}.mp4"></video>
300 
301 {% elif save_as_gif %}
302 .. image:: /{{ filesrc_rel }}
303     :align: center
304 
305 {% elif save_last_frame %}
306 .. image:: /{{ filesrc_rel }}
307     :align: center
308 
309 {% endif %}
310 {% if not hide_source %}
311 {{ source_block }}
312 
313 {{ ref_block }}
314 
315 {% endif %}
316 
317 .. raw:: html
318 
319     </div>
320 """
321
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/docs/source/manim_directive.py b/docs/source/manim_directive.py
--- a/docs/source/manim_directive.py
+++ b/docs/source/manim_directive.py
@@ -202,6 +202,7 @@
         source_block = [
             ".. code-block:: python",
             "",
+            "    from manim import *\n",
             *["    " + line for line in self.content],
         ]
         source_block = "\n".join(source_block)

{"golden_diff": "diff --git a/docs/source/manim_directive.py b/docs/source/manim_directive.py\n--- a/docs/source/manim_directive.py\n+++ b/docs/source/manim_directive.py\n@@ -202,6 +202,7 @@\n         source_block = [\n             \".. code-block:: python\",\n             \"\",\n+            \"    from manim import *\\n\",\n             *[\"    \" + line for line in self.content],\n         ]\n         source_block = \"\\n\".join(source_block)\n", "issue": "Add import statements to examples in documentation\nSee title.\r\n\r\nThe examples in the documentation should also include the `from manim import *` at the very least, and actually we could provide best-practice examples where we dont do a *-import, but rather import classes/functions separately.\r\n\r\nThis can of course be an iterative process: start with adding `from manim import *` first, and become more specific later.\n", "before_files": [{"content": "r\"\"\"\nA directive for including Manim videos in a Sphinx document\n===========================================================\n\nWhen rendering the HTML documentation, the ``.. manim::`` directive\nimplemented here allows to include rendered videos.\n\nIts basic usage that allows processing **inline content**\nlooks as follows::\n\n    .. manim:: MyScene\n\n        class MyScene(Scene):\n            def construct(self):\n                ...\n\nIt is required to pass the name of the class representing the\nscene to be rendered to the directive.\n\nAs a second application, the directive can also be used to\nrender scenes that are defined within doctests, for example::\n\n    .. manim:: DirectiveDoctestExample\n        :ref_classes: Dot\n\n        >>> dot = Dot(color=RED)\n        >>> dot.color\n        <Color #fc6255>\n        >>> class DirectiveDoctestExample(Scene):\n        ...     def construct(self):\n        ...         self.play(Create(dot))\n\n\nOptions\n-------\n\nOptions can be passed as follows::\n\n    .. manim:: <Class name>\n        :<option name>: <value>\n\nThe following configuration options are supported by the\ndirective:\n\n    hide_source\n        If this flag is present without argument,\n        the source code is not displayed above the rendered video.\n\n    quality : {'low', 'medium', 'high', 'fourk'}\n        Controls render quality of the video, in analogy to\n        the corresponding command line flags.\n\n    save_as_gif\n        If this flag is present without argument,\n        the scene is rendered as a gif.\n\n    save_last_frame\n        If this flag is present without argument,\n        an image representing the last frame of the scene will\n        be rendered and displayed, instead of a video.\n\n    ref_classes\n        A list of classes, separated by spaces, that is\n        rendered in a reference block after the source code.\n\n    ref_functions\n        A list of functions, separated by spaces,\n        that is rendered in a reference block after the source code.\n\n    ref_methods\n        A list of methods, separated by spaces,\n        that is rendered in a reference block after the source code.\n\n\"\"\"\nimport os\nimport shutil\nfrom os.path import relpath\nfrom pathlib import Path\nfrom typing import List\n\nimport jinja2\nfrom docutils import nodes\nfrom docutils.parsers.rst import Directive, directives\nfrom docutils.statemachine import StringList\n\nfrom manim import QUALITIES\n\nclassnamedict = {}\n\n\nclass skip_manim_node(nodes.Admonition, nodes.Element):\n    pass\n\n\ndef visit(self, node, name=\"\"):\n    self.visit_admonition(node, name)\n\n\ndef depart(self, node):\n    self.depart_admonition(node)\n\n\ndef process_name_list(option_input: str, reference_type: str) -> List[str]:\n    r\"\"\"Reformats a string of space separated class names\n    as a list of strings containing valid Sphinx references.\n\n    Tests\n    -----\n\n    ::\n\n        >>> process_name_list(\"Tex TexTemplate\", \"class\")\n        [\":class:`~.Tex`\", \":class:`~.TexTemplate`\"]\n        >>> process_name_list(\"Scene.play Mobject.rotate\", \"func\")\n        [\":func:`~.Scene.play`\", \":func:`~.Mobject.rotate`\"]\n    \"\"\"\n    return [f\":{reference_type}:`~.{name}`\" for name in option_input.split()]\n\n\nclass ManimDirective(Directive):\n    r\"\"\"The manim directive, rendering videos while building\n    the documentation.\n\n    See the module docstring for documentation.\n    \"\"\"\n    has_content = True\n    required_arguments = 1\n    optional_arguments = 0\n    option_spec = {\n        \"hide_source\": bool,\n        \"quality\": lambda arg: directives.choice(\n            arg, (\"low\", \"medium\", \"high\", \"fourk\")\n        ),\n        \"save_as_gif\": bool,\n        \"save_last_frame\": bool,\n        \"ref_modules\": lambda arg: process_name_list(arg, \"mod\"),\n        \"ref_classes\": lambda arg: process_name_list(arg, \"class\"),\n        \"ref_functions\": lambda arg: process_name_list(arg, \"func\"),\n        \"ref_methods\": lambda arg: process_name_list(arg, \"meth\"),\n    }\n    final_argument_whitespace = True\n\n    def run(self):\n        if \"skip-manim\" in self.state.document.settings.env.app.builder.tags.tags:\n            node = skip_manim_node()\n            self.state.nested_parse(\n                StringList(self.content[0]), self.content_offset, node\n            )\n            return [node]\n\n        from manim import config\n\n        global classnamedict\n\n        clsname = self.arguments[0]\n        if clsname not in classnamedict:\n            classnamedict[clsname] = 1\n        else:\n            classnamedict[clsname] += 1\n\n        hide_source = \"hide_source\" in self.options\n        save_as_gif = \"save_as_gif\" in self.options\n        save_last_frame = \"save_last_frame\" in self.options\n        assert not (save_as_gif and save_last_frame)\n\n        ref_content = (\n            self.options.get(\"ref_modules\", [])\n            + self.options.get(\"ref_classes\", [])\n            + self.options.get(\"ref_functions\", [])\n            + self.options.get(\"ref_methods\", [])\n        )\n        if ref_content:\n            ref_block = \"References: \" + \" \".join(ref_content)\n\n        else:\n            ref_block = \"\"\n\n        if \"quality\" in self.options:\n            quality = f'{self.options[\"quality\"]}_quality'\n        else:\n            quality = \"example_quality\"\n        frame_rate = QUALITIES[quality][\"frame_rate\"]\n        pixel_height = QUALITIES[quality][\"pixel_height\"]\n        pixel_width = QUALITIES[quality][\"pixel_width\"]\n        qualitydir = f\"{pixel_height}p{frame_rate}\"\n\n        state_machine = self.state_machine\n        document = state_machine.document\n\n        source_file_name = document.attributes[\"source\"]\n        source_rel_name = relpath(source_file_name, setup.confdir)\n        source_rel_dir = os.path.dirname(source_rel_name)\n        while source_rel_dir.startswith(os.path.sep):\n            source_rel_dir = source_rel_dir[1:]\n\n        dest_dir = os.path.abspath(\n            os.path.join(setup.app.builder.outdir, source_rel_dir)\n        )\n        if not os.path.exists(dest_dir):\n            os.makedirs(dest_dir)\n\n        source_block = [\n            \".. code-block:: python\",\n            \"\",\n            *[\"    \" + line for line in self.content],\n        ]\n        source_block = \"\\n\".join(source_block)\n\n        config.media_dir = Path(setup.confdir) / \"media\"\n        config.images_dir = \"{media_dir}/images\"\n        config.video_dir = \"{media_dir}/videos/{quality}\"\n        output_file = f\"{clsname}-{classnamedict[clsname]}\"\n        config.assets_dir = Path(\"_static\")\n\n        config_code = [\n            f'config[\"frame_rate\"] = {frame_rate}',\n            f'config[\"pixel_height\"] = {pixel_height}',\n            f'config[\"pixel_width\"] = {pixel_width}',\n            f'config[\"save_last_frame\"] = {save_last_frame}',\n            f'config[\"save_as_gif\"] = {save_as_gif}',\n            f'config[\"write_to_movie\"] = {not save_last_frame}',\n            f'config[\"output_file\"] = r\"{output_file}\"',\n        ]\n\n        user_code = self.content\n        if user_code[0].startswith(\">>> \"):  # check whether block comes from doctest\n            user_code = [\n                line[4:] for line in user_code if line.startswith((\">>> \", \"... \"))\n            ]\n\n        code = [\n            \"from manim import *\",\n            *config_code,\n            *user_code,\n            f\"{clsname}().render()\",\n        ]\n        exec(\"\\n\".join(code), globals())\n\n        # copy video file to output directory\n        if not (save_as_gif or save_last_frame):\n            filename = f\"{output_file}.mp4\"\n            filesrc = config.get_dir(\"video_dir\") / filename\n            destfile = os.path.join(dest_dir, filename)\n            shutil.copyfile(filesrc, destfile)\n        elif save_as_gif:\n            filename = f\"{output_file}.gif\"\n            filesrc = config.get_dir(\"video_dir\") / filename\n        elif save_last_frame:\n            filename = f\"{output_file}.png\"\n            filesrc = config.get_dir(\"images_dir\") / filename\n        else:\n            raise ValueError(\"Invalid combination of render flags received.\")\n\n        rendered_template = jinja2.Template(TEMPLATE).render(\n            clsname=clsname,\n            clsname_lowercase=clsname.lower(),\n            hide_source=hide_source,\n            filesrc_rel=os.path.relpath(filesrc, setup.confdir),\n            output_file=output_file,\n            save_last_frame=save_last_frame,\n            save_as_gif=save_as_gif,\n            source_block=source_block,\n            ref_block=ref_block,\n        )\n        state_machine.insert_input(\n            rendered_template.split(\"\\n\"), source=document.attributes[\"source\"]\n        )\n\n        return []\n\n\ndef setup(app):\n    import manim\n\n    app.add_node(skip_manim_node, html=(visit, depart))\n\n    setup.app = app\n    setup.config = app.config\n    setup.confdir = app.confdir\n\n    app.add_directive(\"manim\", ManimDirective)\n\n    metadata = {\"parallel_read_safe\": False, \"parallel_write_safe\": True}\n    return metadata\n\n\nTEMPLATE = r\"\"\"\n{% if not hide_source %}\n.. raw:: html\n\n    <div id=\"{{ clsname_lowercase }}\" class=\"admonition admonition-manim-example\">\n    <p class=\"admonition-title\">Example: {{ clsname }} <a class=\"headerlink\" href=\"#{{ clsname_lowercase }}\">\u00b6</a></p>\n\n{% endif %}\n\n{% if not (save_as_gif or save_last_frame) %}\n.. raw:: html\n\n    <video class=\"manim-video\" controls loop autoplay src=\"./{{ output_file }}.mp4\"></video>\n\n{% elif save_as_gif %}\n.. image:: /{{ filesrc_rel }}\n    :align: center\n\n{% elif save_last_frame %}\n.. image:: /{{ filesrc_rel }}\n    :align: center\n\n{% endif %}\n{% if not hide_source %}\n{{ source_block }}\n\n{{ ref_block }}\n\n{% endif %}\n\n.. raw:: html\n\n    </div>\n\"\"\"\n", "path": "docs/source/manim_directive.py"}], "after_files": [{"content": "r\"\"\"\nA directive for including Manim videos in a Sphinx document\n===========================================================\n\nWhen rendering the HTML documentation, the ``.. manim::`` directive\nimplemented here allows to include rendered videos.\n\nIts basic usage that allows processing **inline content**\nlooks as follows::\n\n    .. manim:: MyScene\n\n        class MyScene(Scene):\n            def construct(self):\n                ...\n\nIt is required to pass the name of the class representing the\nscene to be rendered to the directive.\n\nAs a second application, the directive can also be used to\nrender scenes that are defined within doctests, for example::\n\n    .. manim:: DirectiveDoctestExample\n        :ref_classes: Dot\n\n        >>> dot = Dot(color=RED)\n        >>> dot.color\n        <Color #fc6255>\n        >>> class DirectiveDoctestExample(Scene):\n        ...     def construct(self):\n        ...         self.play(Create(dot))\n\n\nOptions\n-------\n\nOptions can be passed as follows::\n\n    .. manim:: <Class name>\n        :<option name>: <value>\n\nThe following configuration options are supported by the\ndirective:\n\n    hide_source\n        If this flag is present without argument,\n        the source code is not displayed above the rendered video.\n\n    quality : {'low', 'medium', 'high', 'fourk'}\n        Controls render quality of the video, in analogy to\n        the corresponding command line flags.\n\n    save_as_gif\n        If this flag is present without argument,\n        the scene is rendered as a gif.\n\n    save_last_frame\n        If this flag is present without argument,\n        an image representing the last frame of the scene will\n        be rendered and displayed, instead of a video.\n\n    ref_classes\n        A list of classes, separated by spaces, that is\n        rendered in a reference block after the source code.\n\n    ref_functions\n        A list of functions, separated by spaces,\n        that is rendered in a reference block after the source code.\n\n    ref_methods\n        A list of methods, separated by spaces,\n        that is rendered in a reference block after the source code.\n\n\"\"\"\nimport os\nimport shutil\nfrom os.path import relpath\nfrom pathlib import Path\nfrom typing import List\n\nimport jinja2\nfrom docutils import nodes\nfrom docutils.parsers.rst import Directive, directives\nfrom docutils.statemachine import StringList\n\nfrom manim import QUALITIES\n\nclassnamedict = {}\n\n\nclass skip_manim_node(nodes.Admonition, nodes.Element):\n    pass\n\n\ndef visit(self, node, name=\"\"):\n    self.visit_admonition(node, name)\n\n\ndef depart(self, node):\n    self.depart_admonition(node)\n\n\ndef process_name_list(option_input: str, reference_type: str) -> List[str]:\n    r\"\"\"Reformats a string of space separated class names\n    as a list of strings containing valid Sphinx references.\n\n    Tests\n    -----\n\n    ::\n\n        >>> process_name_list(\"Tex TexTemplate\", \"class\")\n        [\":class:`~.Tex`\", \":class:`~.TexTemplate`\"]\n        >>> process_name_list(\"Scene.play Mobject.rotate\", \"func\")\n        [\":func:`~.Scene.play`\", \":func:`~.Mobject.rotate`\"]\n    \"\"\"\n    return [f\":{reference_type}:`~.{name}`\" for name in option_input.split()]\n\n\nclass ManimDirective(Directive):\n    r\"\"\"The manim directive, rendering videos while building\n    the documentation.\n\n    See the module docstring for documentation.\n    \"\"\"\n    has_content = True\n    required_arguments = 1\n    optional_arguments = 0\n    option_spec = {\n        \"hide_source\": bool,\n        \"quality\": lambda arg: directives.choice(\n            arg, (\"low\", \"medium\", \"high\", \"fourk\")\n        ),\n        \"save_as_gif\": bool,\n        \"save_last_frame\": bool,\n        \"ref_modules\": lambda arg: process_name_list(arg, \"mod\"),\n        \"ref_classes\": lambda arg: process_name_list(arg, \"class\"),\n        \"ref_functions\": lambda arg: process_name_list(arg, \"func\"),\n        \"ref_methods\": lambda arg: process_name_list(arg, \"meth\"),\n    }\n    final_argument_whitespace = True\n\n    def run(self):\n        if \"skip-manim\" in self.state.document.settings.env.app.builder.tags.tags:\n            node = skip_manim_node()\n            self.state.nested_parse(\n                StringList(self.content[0]), self.content_offset, node\n            )\n            return [node]\n\n        from manim import config\n\n        global classnamedict\n\n        clsname = self.arguments[0]\n        if clsname not in classnamedict:\n            classnamedict[clsname] = 1\n        else:\n            classnamedict[clsname] += 1\n\n        hide_source = \"hide_source\" in self.options\n        save_as_gif = \"save_as_gif\" in self.options\n        save_last_frame = \"save_last_frame\" in self.options\n        assert not (save_as_gif and save_last_frame)\n\n        ref_content = (\n            self.options.get(\"ref_modules\", [])\n            + self.options.get(\"ref_classes\", [])\n            + self.options.get(\"ref_functions\", [])\n            + self.options.get(\"ref_methods\", [])\n        )\n        if ref_content:\n            ref_block = \"References: \" + \" \".join(ref_content)\n\n        else:\n            ref_block = \"\"\n\n        if \"quality\" in self.options:\n            quality = f'{self.options[\"quality\"]}_quality'\n        else:\n            quality = \"example_quality\"\n        frame_rate = QUALITIES[quality][\"frame_rate\"]\n        pixel_height = QUALITIES[quality][\"pixel_height\"]\n        pixel_width = QUALITIES[quality][\"pixel_width\"]\n        qualitydir = f\"{pixel_height}p{frame_rate}\"\n\n        state_machine = self.state_machine\n        document = state_machine.document\n\n        source_file_name = document.attributes[\"source\"]\n        source_rel_name = relpath(source_file_name, setup.confdir)\n        source_rel_dir = os.path.dirname(source_rel_name)\n        while source_rel_dir.startswith(os.path.sep):\n            source_rel_dir = source_rel_dir[1:]\n\n        dest_dir = os.path.abspath(\n            os.path.join(setup.app.builder.outdir, source_rel_dir)\n        )\n        if not os.path.exists(dest_dir):\n            os.makedirs(dest_dir)\n\n        source_block = [\n            \".. code-block:: python\",\n            \"\",\n            \"    from manim import *\\n\",\n            *[\"    \" + line for line in self.content],\n        ]\n        source_block = \"\\n\".join(source_block)\n\n        config.media_dir = Path(setup.confdir) / \"media\"\n        config.images_dir = \"{media_dir}/images\"\n        config.video_dir = \"{media_dir}/videos/{quality}\"\n        output_file = f\"{clsname}-{classnamedict[clsname]}\"\n        config.assets_dir = Path(\"_static\")\n\n        config_code = [\n            f'config[\"frame_rate\"] = {frame_rate}',\n            f'config[\"pixel_height\"] = {pixel_height}',\n            f'config[\"pixel_width\"] = {pixel_width}',\n            f'config[\"save_last_frame\"] = {save_last_frame}',\n            f'config[\"save_as_gif\"] = {save_as_gif}',\n            f'config[\"write_to_movie\"] = {not save_last_frame}',\n            f'config[\"output_file\"] = r\"{output_file}\"',\n        ]\n\n        user_code = self.content\n        if user_code[0].startswith(\">>> \"):  # check whether block comes from doctest\n            user_code = [\n                line[4:] for line in user_code if line.startswith((\">>> \", \"... \"))\n            ]\n\n        code = [\n            \"from manim import *\",\n            *config_code,\n            *user_code,\n            f\"{clsname}().render()\",\n        ]\n        exec(\"\\n\".join(code), globals())\n\n        # copy video file to output directory\n        if not (save_as_gif or save_last_frame):\n            filename = f\"{output_file}.mp4\"\n            filesrc = config.get_dir(\"video_dir\") / filename\n            destfile = os.path.join(dest_dir, filename)\n            shutil.copyfile(filesrc, destfile)\n        elif save_as_gif:\n            filename = f\"{output_file}.gif\"\n            filesrc = config.get_dir(\"video_dir\") / filename\n        elif save_last_frame:\n            filename = f\"{output_file}.png\"\n            filesrc = config.get_dir(\"images_dir\") / filename\n        else:\n            raise ValueError(\"Invalid combination of render flags received.\")\n\n        rendered_template = jinja2.Template(TEMPLATE).render(\n            clsname=clsname,\n            clsname_lowercase=clsname.lower(),\n            hide_source=hide_source,\n            filesrc_rel=os.path.relpath(filesrc, setup.confdir),\n            output_file=output_file,\n            save_last_frame=save_last_frame,\n            save_as_gif=save_as_gif,\n            source_block=source_block,\n            ref_block=ref_block,\n        )\n        state_machine.insert_input(\n            rendered_template.split(\"\\n\"), source=document.attributes[\"source\"]\n        )\n\n        return []\n\n\ndef setup(app):\n    import manim\n\n    app.add_node(skip_manim_node, html=(visit, depart))\n\n    setup.app = app\n    setup.config = app.config\n    setup.confdir = app.confdir\n\n    app.add_directive(\"manim\", ManimDirective)\n\n    metadata = {\"parallel_read_safe\": False, \"parallel_write_safe\": True}\n    return metadata\n\n\nTEMPLATE = r\"\"\"\n{% if not hide_source %}\n.. raw:: html\n\n    <div id=\"{{ clsname_lowercase }}\" class=\"admonition admonition-manim-example\">\n    <p class=\"admonition-title\">Example: {{ clsname }} <a class=\"headerlink\" href=\"#{{ clsname_lowercase }}\">\u00b6</a></p>\n\n{% endif %}\n\n{% if not (save_as_gif or save_last_frame) %}\n.. raw:: html\n\n    <video class=\"manim-video\" controls loop autoplay src=\"./{{ output_file }}.mp4\"></video>\n\n{% elif save_as_gif %}\n.. image:: /{{ filesrc_rel }}\n    :align: center\n\n{% elif save_last_frame %}\n.. image:: /{{ filesrc_rel }}\n    :align: center\n\n{% endif %}\n{% if not hide_source %}\n{{ source_block }}\n\n{{ ref_block }}\n\n{% endif %}\n\n.. raw:: html\n\n    </div>\n\"\"\"\n", "path": "docs/source/manim_directive.py"}]}