code: def run(arguments, content, options, state_machine, state, lineno):
      document = state_machine.document
      config = document.settings.env.config
      nofigs = "nofigs" in options
  
      if config.plot_srcset and setup.app.builder.name == "singlehtml":
          raise ExtensionError(
              "plot_srcset option not compatible with single HTML writer"
          )
  
      formats = get_plot_formats(config)
      default_fmt = formats[0][0]
  
      options.setdefault("include-source", config.plot_include_source)
      options.setdefault(
          "show-source-link", config.plot_html_show_source_link
      )
  
      if "class" in options:
          # classes are parsed into a list of string, and output by simply
          # printing the list, abusing the fact that RST guarantees to strip
          # non-conforming characters
          options["class"] = ["plot-directive"] + options["class"]
      else:
          options.setdefault("class", ["plot-directive"])
      keep_context = "context" in options
      context_opt = None if not keep_context else options["context"]
  
      rst_file = document.attributes["source"]
      rst_dir = os.path.dirname(rst_file)
  
      if len(arguments):
          if not config.plot_basedir:
              source_file_name = os.path.join(
                  setup.app.builder.srcdir, directives.uri(arguments[0])
              )
          else:
              source_file_name = os.path.join(
                  setup.confdir,
                  config.plot_basedir,
                  directives.uri(arguments[0]),
              )
          # If there is content, it will be passed as a caption.
          caption = "\n".join(content)
  
          # Enforce unambiguous use of captions.
          if "caption" in options:
              if caption:
                  raise ValueError(
                      "Caption specified in both content and options."
                      " Please remove ambiguity."
                  )
              # Use caption option
              caption = options["caption"]
  
          # If the optional function name is provided, use it
          if len(arguments) == 2:
              function_name = arguments[1]
          else:
              function_name = None
  
          code = Path(source_file_name).read_text(encoding="utf-8")
          output_base = os.path.basename(source_file_name)
      else:
          source_file_name = rst_file
          code = textwrap.dedent("\n".join(map(str, content)))
          counter = document.attributes.get("_plot_counter", 0) + 1
          document.attributes["_plot_counter"] = counter
          base, ext = os.path.splitext(
              os.path.basename(source_file_name)
          )
          output_base = "%s-%d.py" % (base, counter)
          function_name = None
          caption = options.get("caption", "")
  
      base, source_ext = os.path.splitext(output_base)
      if source_ext in (".py", ".rst", ".txt"):
          output_base = base
      else:
          source_ext = ""
  
      # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
      output_base = output_base.replace(".", "-")
  
      # is it in doctest format?
      is_doctest = contains_doctest(code)
      if "format" in options:
          if options["format"] == "python":
              is_doctest = False
          else:
              is_doctest = True
  
      # determine output directory name fragment
      source_rel_name = relpath(source_file_name, setup.confdir)
      source_rel_dir = os.path.dirname(source_rel_name).lstrip(
          os.path.sep
      )
  
      # build_dir: where to place output files (temporarily)
      build_dir = os.path.join(
          os.path.dirname(setup.app.doctreedir),
          "plot_directive",
          source_rel_dir,
      )
      # get rid of .. in paths, also changes pathsep
      # see note in Python docs for warning about symbolic links on Windows.
      # need to compare source and dest paths at end
      build_dir = os.path.normpath(build_dir)
      os.makedirs(build_dir, exist_ok=True)
  
      # how to link to files from the RST file
      try:
          build_dir_link = relpath(build_dir, rst_dir).replace(
              os.path.sep, "/"
          )
      except ValueError:
          # on Windows, relpath raises ValueError when path and start are on
          # different mounts/drives
          build_dir_link = build_dir
  
      # get list of included rst files so that the output is updated when any
      # plots in the included files change. These attributes are modified by the
      # include directive (see the docutils.parsers.rst.directives.misc module).
      try:
          source_file_includes = [
              os.path.join(os.getcwd(), t[0])
              for t in state.document.include_log
          ]
      except AttributeError:
          # the document.include_log attribute only exists in docutils >=0.17,
          # before that we need to inspect the state machine
          possible_sources = {
              os.path.join(setup.confdir, t[0])
              for t in state_machine.input_lines.items
          }
          source_file_includes = [
              f for f in possible_sources if os.path.isfile(f)
          ]
      # remove the source file itself from the includes
      try:
          source_file_includes.remove(source_file_name)
      except ValueError:
          pass
  
      # save script (if necessary)
      if options["show-source-link"]:
          Path(build_dir, output_base + source_ext).write_text(
              doctest.script_from_examples(code)
              if source_file_name == rst_file and is_doctest
              else code,
              encoding="utf-8",
          )
  
      # make figures
      try:
          results = render_figures(
              code=code,
              code_path=source_file_name,
              output_dir=build_dir,
              output_base=output_base,
              context=keep_context,
              function_name=function_name,
              config=config,
              context_reset=context_opt == "reset",
              close_figs=context_opt == "close-figs",
              code_includes=source_file_includes,
          )
          errors = []
      except PlotError as err:
          reporter = state.memo.reporter
          sm = reporter.system_message(
              2,
              "Exception occurred in plotting {}\n from {}:\n{}".format(
                  output_base, source_file_name, err
              ),
              line=lineno,
          )
          results = [(code, [])]
          errors = [sm]
  
      # Properly indent the caption
      if caption and config.plot_srcset:
          caption = f":caption: {caption}"
      elif caption:
          caption = "\n" + "\n".join(
              "      " + line.strip() for line in caption.split("\n")
          )
      # generate output restructuredtext
      total_lines = []
      for j, (code_piece, images) in enumerate(results):
          if options["include-source"]:
              if is_doctest:
                  lines = ["", *code_piece.splitlines()]
              else:
                  lines = [
                      ".. code-block:: python",
                      "",
                      *textwrap.indent(code_piece, "    ").splitlines(),
                  ]
              source_code = "\n".join(lines)
          else:
              source_code = ""
  
          if nofigs:
              images = []
  
          opts = [
              f":{key}: {val}"
              for key, val in options.items()
              if key
              in ("alt", "height", "width", "scale", "align", "class")
          ]
  
          # Not-None src_name signals the need for a source download in the
          # generated html
          if j == 0 and options["show-source-link"]:
              src_name = output_base + source_ext
          else:
              src_name = None
          if config.plot_srcset:
              srcset = [*_parse_srcset(config.plot_srcset).values()]
              template = TEMPLATE_SRCSET
          else:
              srcset = None
              template = TEMPLATE
  
          result = jinja2.Template(
              config.plot_template or template
          ).render(
              default_fmt=default_fmt,
              build_dir=build_dir_link,
              src_name=src_name,
              multi_image=len(images) > 1,
              options=opts,
              srcset=srcset,
              images=images,
              source_code=source_code,
              html_show_formats=config.plot_html_show_formats
              and len(images),
              caption=caption,
          )
          total_lines.extend(result.split("\n"))
          total_lines.extend("\n")
  
      if total_lines:
          state_machine.insert_input(
              total_lines, source=source_file_name
          )
  
      return errors
  
imports: import contextlib
  import doctest
  from io import StringIO
  import itertools
  import os
  from os.path import relpath
  from pathlib import Path
  import re
  import shutil
  import sys
  import textwrap
  import traceback
  from docutils.parsers.rst import directives, Directive
  from docutils.parsers.rst.directives.images import Image
  import jinja2
  from sphinx.errors import ExtensionError
  import matplotlib
  from matplotlib.backend_bases import FigureManagerBase
  import matplotlib.pyplot
  from matplotlib import _pylab_helpers, cbook
label_desc: Use image node_id 15 for calling a global function with example usage: run(arguments, content, options, state_machine, state, lineno) and returns: errors