plot_directive.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. """
  2. A directive for including a Matplotlib plot in a Sphinx document
  3. ================================================================
  4. By default, in HTML output, `plot` will include a .png file with a link to a
  5. high-res .png and .pdf. In LaTeX output, it will include a .pdf.
  6. The source code for the plot may be included in one of three ways:
  7. 1. **A path to a source file** as the argument to the directive::
  8. .. plot:: path/to/plot.py
  9. When a path to a source file is given, the content of the
  10. directive may optionally contain a caption for the plot::
  11. .. plot:: path/to/plot.py
  12. This is the caption for the plot
  13. Additionally, one may specify the name of a function to call (with
  14. no arguments) immediately after importing the module::
  15. .. plot:: path/to/plot.py plot_function1
  16. 2. Included as **inline content** to the directive::
  17. .. plot::
  18. import matplotlib.pyplot as plt
  19. import matplotlib.image as mpimg
  20. import numpy as np
  21. img = mpimg.imread('_static/stinkbug.png')
  22. imgplot = plt.imshow(img)
  23. 3. Using **doctest** syntax::
  24. .. plot::
  25. A plotting example:
  26. >>> import matplotlib.pyplot as plt
  27. >>> plt.plot([1, 2, 3], [4, 5, 6])
  28. Options
  29. -------
  30. The ``plot`` directive supports the following options:
  31. format : {'python', 'doctest'}
  32. Specify the format of the input
  33. include-source : bool
  34. Whether to display the source code. The default can be changed
  35. using the `plot_include_source` variable in conf.py
  36. encoding : str
  37. If this source file is in a non-UTF8 or non-ASCII encoding, the
  38. encoding must be specified using the `:encoding:` option. The encoding
  39. will not be inferred using the ``-*- coding -*-`` metacomment.
  40. context : bool or str
  41. If provided, the code will be run in the context of all previous plot
  42. directives for which the `:context:` option was specified. This only
  43. applies to inline code plot directives, not those run from files. If
  44. the ``:context: reset`` option is specified, the context is reset
  45. for this and future plots, and previous figures are closed prior to
  46. running the code. ``:context: close-figs`` keeps the context but closes
  47. previous figures before running the code.
  48. nofigs : bool
  49. If specified, the code block will be run, but no figures will be
  50. inserted. This is usually useful with the ``:context:`` option.
  51. Additionally, this directive supports all of the options of the `image`
  52. directive, except for *target* (since plot will add its own target). These
  53. include `alt`, `height`, `width`, `scale`, `align` and `class`.
  54. Configuration options
  55. ---------------------
  56. The plot directive has the following configuration options:
  57. plot_include_source
  58. Default value for the include-source option
  59. plot_html_show_source_link
  60. Whether to show a link to the source in HTML.
  61. plot_pre_code
  62. Code that should be executed before each plot. If not specified or None
  63. it will default to a string containing::
  64. import numpy as np
  65. from matplotlib import pyplot as plt
  66. plot_basedir
  67. Base directory, to which ``plot::`` file names are relative
  68. to. (If None or empty, file names are relative to the
  69. directory where the file containing the directive is.)
  70. plot_formats
  71. File formats to generate. List of tuples or strings::
  72. [(suffix, dpi), suffix, ...]
  73. that determine the file format and the DPI. For entries whose
  74. DPI was omitted, sensible defaults are chosen. When passing from
  75. the command line through sphinx_build the list should be passed as
  76. suffix:dpi,suffix:dpi, ...
  77. plot_html_show_formats
  78. Whether to show links to the files in HTML.
  79. plot_rcparams
  80. A dictionary containing any non-standard rcParams that should
  81. be applied before each plot.
  82. plot_apply_rcparams
  83. By default, rcParams are applied when `context` option is not used in
  84. a plot directive. This configuration option overrides this behavior
  85. and applies rcParams before each plot.
  86. plot_working_directory
  87. By default, the working directory will be changed to the directory of
  88. the example, so the code can get at its data files, if any. Also its
  89. path will be added to `sys.path` so it can import any helper modules
  90. sitting beside it. This configuration option can be used to specify
  91. a central directory (also added to `sys.path`) where data files and
  92. helper modules for all code are located.
  93. plot_template
  94. Provide a customized template for preparing restructured text.
  95. """
  96. import contextlib
  97. from io import StringIO
  98. import itertools
  99. import os
  100. from os.path import relpath
  101. from pathlib import Path
  102. import re
  103. import shutil
  104. import sys
  105. import textwrap
  106. import traceback
  107. from docutils.parsers.rst import directives, Directive
  108. from docutils.parsers.rst.directives.images import Image
  109. import jinja2 # Sphinx dependency.
  110. import matplotlib
  111. from matplotlib.backend_bases import FigureManagerBase
  112. import matplotlib.pyplot as plt
  113. from matplotlib import _pylab_helpers, cbook
  114. matplotlib.use("agg")
  115. align = Image.align
  116. __version__ = 2
  117. # -----------------------------------------------------------------------------
  118. # Registration hook
  119. # -----------------------------------------------------------------------------
  120. @cbook.deprecated("3.1", alternative="PlotDirective")
  121. def plot_directive(name, arguments, options, content, lineno,
  122. content_offset, block_text, state, state_machine):
  123. """Implementation of the ``.. plot::`` directive.
  124. See the module docstring for details.
  125. """
  126. return run(arguments, content, options, state_machine, state, lineno)
  127. def _option_boolean(arg):
  128. if not arg or not arg.strip():
  129. # no argument given, assume used as a flag
  130. return True
  131. elif arg.strip().lower() in ('no', '0', 'false'):
  132. return False
  133. elif arg.strip().lower() in ('yes', '1', 'true'):
  134. return True
  135. else:
  136. raise ValueError('"%s" unknown boolean' % arg)
  137. def _option_context(arg):
  138. if arg in [None, 'reset', 'close-figs']:
  139. return arg
  140. raise ValueError("argument should be None or 'reset' or 'close-figs'")
  141. def _option_format(arg):
  142. return directives.choice(arg, ('python', 'doctest'))
  143. def _option_align(arg):
  144. return directives.choice(arg, ("top", "middle", "bottom", "left", "center",
  145. "right"))
  146. def mark_plot_labels(app, document):
  147. """
  148. To make plots referenceable, we need to move the reference from the
  149. "htmlonly" (or "latexonly") node to the actual figure node itself.
  150. """
  151. for name, explicit in document.nametypes.items():
  152. if not explicit:
  153. continue
  154. labelid = document.nameids[name]
  155. if labelid is None:
  156. continue
  157. node = document.ids[labelid]
  158. if node.tagname in ('html_only', 'latex_only'):
  159. for n in node:
  160. if n.tagname == 'figure':
  161. sectname = name
  162. for c in n:
  163. if c.tagname == 'caption':
  164. sectname = c.astext()
  165. break
  166. node['ids'].remove(labelid)
  167. node['names'].remove(name)
  168. n['ids'].append(labelid)
  169. n['names'].append(name)
  170. document.settings.env.labels[name] = \
  171. document.settings.env.docname, labelid, sectname
  172. break
  173. class PlotDirective(Directive):
  174. """Implementation of the ``.. plot::`` directive.
  175. See the module docstring for details.
  176. """
  177. has_content = True
  178. required_arguments = 0
  179. optional_arguments = 2
  180. final_argument_whitespace = False
  181. option_spec = {
  182. 'alt': directives.unchanged,
  183. 'height': directives.length_or_unitless,
  184. 'width': directives.length_or_percentage_or_unitless,
  185. 'scale': directives.nonnegative_int,
  186. 'align': _option_align,
  187. 'class': directives.class_option,
  188. 'include-source': _option_boolean,
  189. 'format': _option_format,
  190. 'context': _option_context,
  191. 'nofigs': directives.flag,
  192. 'encoding': directives.encoding,
  193. }
  194. def run(self):
  195. """Run the plot directive."""
  196. return run(self.arguments, self.content, self.options,
  197. self.state_machine, self.state, self.lineno)
  198. def setup(app):
  199. import matplotlib
  200. setup.app = app
  201. setup.config = app.config
  202. setup.confdir = app.confdir
  203. app.add_directive('plot', PlotDirective)
  204. app.add_config_value('plot_pre_code', None, True)
  205. app.add_config_value('plot_include_source', False, True)
  206. app.add_config_value('plot_html_show_source_link', True, True)
  207. app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)
  208. app.add_config_value('plot_basedir', None, True)
  209. app.add_config_value('plot_html_show_formats', True, True)
  210. app.add_config_value('plot_rcparams', {}, True)
  211. app.add_config_value('plot_apply_rcparams', False, True)
  212. app.add_config_value('plot_working_directory', None, True)
  213. app.add_config_value('plot_template', None, True)
  214. app.connect('doctree-read', mark_plot_labels)
  215. metadata = {'parallel_read_safe': True, 'parallel_write_safe': True,
  216. 'version': matplotlib.__version__}
  217. return metadata
  218. # -----------------------------------------------------------------------------
  219. # Doctest handling
  220. # -----------------------------------------------------------------------------
  221. def contains_doctest(text):
  222. try:
  223. # check if it's valid Python as-is
  224. compile(text, '<string>', 'exec')
  225. return False
  226. except SyntaxError:
  227. pass
  228. r = re.compile(r'^\s*>>>', re.M)
  229. m = r.search(text)
  230. return bool(m)
  231. def unescape_doctest(text):
  232. """
  233. Extract code from a piece of text, which contains either Python code
  234. or doctests.
  235. """
  236. if not contains_doctest(text):
  237. return text
  238. code = ""
  239. for line in text.split("\n"):
  240. m = re.match(r'^\s*(>>>|\.\.\.) (.*)$', line)
  241. if m:
  242. code += m.group(2) + "\n"
  243. elif line.strip():
  244. code += "# " + line.strip() + "\n"
  245. else:
  246. code += "\n"
  247. return code
  248. def split_code_at_show(text):
  249. """Split code at plt.show()."""
  250. parts = []
  251. is_doctest = contains_doctest(text)
  252. part = []
  253. for line in text.split("\n"):
  254. if (not is_doctest and line.strip() == 'plt.show()') or \
  255. (is_doctest and line.strip() == '>>> plt.show()'):
  256. part.append(line)
  257. parts.append("\n".join(part))
  258. part = []
  259. else:
  260. part.append(line)
  261. if "\n".join(part).strip():
  262. parts.append("\n".join(part))
  263. return parts
  264. # -----------------------------------------------------------------------------
  265. # Template
  266. # -----------------------------------------------------------------------------
  267. TEMPLATE = """
  268. {{ source_code }}
  269. .. only:: html
  270. {% if source_link or (html_show_formats and not multi_image) %}
  271. (
  272. {%- if source_link -%}
  273. `Source code <{{ source_link }}>`__
  274. {%- endif -%}
  275. {%- if html_show_formats and not multi_image -%}
  276. {%- for img in images -%}
  277. {%- for fmt in img.formats -%}
  278. {%- if source_link or not loop.first -%}, {% endif -%}
  279. `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
  280. {%- endfor -%}
  281. {%- endfor -%}
  282. {%- endif -%}
  283. )
  284. {% endif %}
  285. {% for img in images %}
  286. .. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
  287. {% for option in options -%}
  288. {{ option }}
  289. {% endfor %}
  290. {% if html_show_formats and multi_image -%}
  291. (
  292. {%- for fmt in img.formats -%}
  293. {%- if not loop.first -%}, {% endif -%}
  294. `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
  295. {%- endfor -%}
  296. )
  297. {%- endif -%}
  298. {{ caption }}
  299. {% endfor %}
  300. .. only:: not html
  301. {% for img in images %}
  302. .. figure:: {{ build_dir }}/{{ img.basename }}.*
  303. {% for option in options -%}
  304. {{ option }}
  305. {% endfor %}
  306. {{ caption }}
  307. {% endfor %}
  308. """
  309. exception_template = """
  310. .. only:: html
  311. [`source code <%(linkdir)s/%(basename)s.py>`__]
  312. Exception occurred rendering plot.
  313. """
  314. # the context of the plot for all directives specified with the
  315. # :context: option
  316. plot_context = dict()
  317. class ImageFile:
  318. def __init__(self, basename, dirname):
  319. self.basename = basename
  320. self.dirname = dirname
  321. self.formats = []
  322. def filename(self, format):
  323. return os.path.join(self.dirname, "%s.%s" % (self.basename, format))
  324. def filenames(self):
  325. return [self.filename(fmt) for fmt in self.formats]
  326. def out_of_date(original, derived):
  327. """
  328. Return whether *derived* is out-of-date relative to *original*, both of
  329. which are full file paths.
  330. """
  331. return (not os.path.exists(derived) or
  332. (os.path.exists(original) and
  333. os.stat(derived).st_mtime < os.stat(original).st_mtime))
  334. class PlotError(RuntimeError):
  335. pass
  336. def run_code(code, code_path, ns=None, function_name=None):
  337. """
  338. Import a Python module from a path, and run the function given by
  339. name, if function_name is not None.
  340. """
  341. # Change the working directory to the directory of the example, so
  342. # it can get at its data files, if any. Add its path to sys.path
  343. # so it can import any helper modules sitting beside it.
  344. pwd = os.getcwd()
  345. if setup.config.plot_working_directory is not None:
  346. try:
  347. os.chdir(setup.config.plot_working_directory)
  348. except OSError as err:
  349. raise OSError(str(err) + '\n`plot_working_directory` option in'
  350. 'Sphinx configuration file must be a valid '
  351. 'directory path')
  352. except TypeError as err:
  353. raise TypeError(str(err) + '\n`plot_working_directory` option in '
  354. 'Sphinx configuration file must be a string or '
  355. 'None')
  356. elif code_path is not None:
  357. dirname = os.path.abspath(os.path.dirname(code_path))
  358. os.chdir(dirname)
  359. with cbook._setattr_cm(
  360. sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \
  361. contextlib.redirect_stdout(StringIO()):
  362. try:
  363. code = unescape_doctest(code)
  364. if ns is None:
  365. ns = {}
  366. if not ns:
  367. if setup.config.plot_pre_code is None:
  368. exec('import numpy as np\n'
  369. 'from matplotlib import pyplot as plt\n', ns)
  370. else:
  371. exec(str(setup.config.plot_pre_code), ns)
  372. if "__main__" in code:
  373. ns['__name__'] = '__main__'
  374. # Patch out non-interactive show() to avoid triggering a warning.
  375. with cbook._setattr_cm(FigureManagerBase, show=lambda self: None):
  376. exec(code, ns)
  377. if function_name is not None:
  378. exec(function_name + "()", ns)
  379. except (Exception, SystemExit):
  380. raise PlotError(traceback.format_exc())
  381. finally:
  382. os.chdir(pwd)
  383. return ns
  384. def clear_state(plot_rcparams, close=True):
  385. if close:
  386. plt.close('all')
  387. matplotlib.rc_file_defaults()
  388. matplotlib.rcParams.update(plot_rcparams)
  389. def get_plot_formats(config):
  390. default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200}
  391. formats = []
  392. plot_formats = config.plot_formats
  393. for fmt in plot_formats:
  394. if isinstance(fmt, str):
  395. if ':' in fmt:
  396. suffix, dpi = fmt.split(':')
  397. formats.append((str(suffix), int(dpi)))
  398. else:
  399. formats.append((fmt, default_dpi.get(fmt, 80)))
  400. elif isinstance(fmt, (tuple, list)) and len(fmt) == 2:
  401. formats.append((str(fmt[0]), int(fmt[1])))
  402. else:
  403. raise PlotError('invalid image format "%r" in plot_formats' % fmt)
  404. return formats
  405. def render_figures(code, code_path, output_dir, output_base, context,
  406. function_name, config, context_reset=False,
  407. close_figs=False):
  408. """
  409. Run a pyplot script and save the images in *output_dir*.
  410. Save the images under *output_dir* with file names derived from
  411. *output_base*
  412. """
  413. formats = get_plot_formats(config)
  414. # -- Try to determine if all images already exist
  415. code_pieces = split_code_at_show(code)
  416. # Look for single-figure output files first
  417. all_exists = True
  418. img = ImageFile(output_base, output_dir)
  419. for format, dpi in formats:
  420. if out_of_date(code_path, img.filename(format)):
  421. all_exists = False
  422. break
  423. img.formats.append(format)
  424. if all_exists:
  425. return [(code, [img])]
  426. # Then look for multi-figure output files
  427. results = []
  428. all_exists = True
  429. for i, code_piece in enumerate(code_pieces):
  430. images = []
  431. for j in itertools.count():
  432. if len(code_pieces) > 1:
  433. img = ImageFile('%s_%02d_%02d' % (output_base, i, j),
  434. output_dir)
  435. else:
  436. img = ImageFile('%s_%02d' % (output_base, j), output_dir)
  437. for fmt, dpi in formats:
  438. if out_of_date(code_path, img.filename(fmt)):
  439. all_exists = False
  440. break
  441. img.formats.append(fmt)
  442. # assume that if we have one, we have them all
  443. if not all_exists:
  444. all_exists = (j > 0)
  445. break
  446. images.append(img)
  447. if not all_exists:
  448. break
  449. results.append((code_piece, images))
  450. if all_exists:
  451. return results
  452. # We didn't find the files, so build them
  453. results = []
  454. if context:
  455. ns = plot_context
  456. else:
  457. ns = {}
  458. if context_reset:
  459. clear_state(config.plot_rcparams)
  460. plot_context.clear()
  461. close_figs = not context or close_figs
  462. for i, code_piece in enumerate(code_pieces):
  463. if not context or config.plot_apply_rcparams:
  464. clear_state(config.plot_rcparams, close_figs)
  465. elif close_figs:
  466. plt.close('all')
  467. run_code(code_piece, code_path, ns, function_name)
  468. images = []
  469. fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
  470. for j, figman in enumerate(fig_managers):
  471. if len(fig_managers) == 1 and len(code_pieces) == 1:
  472. img = ImageFile(output_base, output_dir)
  473. elif len(code_pieces) == 1:
  474. img = ImageFile("%s_%02d" % (output_base, j), output_dir)
  475. else:
  476. img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
  477. output_dir)
  478. images.append(img)
  479. for fmt, dpi in formats:
  480. try:
  481. figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi)
  482. except Exception:
  483. raise PlotError(traceback.format_exc())
  484. img.formats.append(fmt)
  485. results.append((code_piece, images))
  486. if not context or config.plot_apply_rcparams:
  487. clear_state(config.plot_rcparams, close=not context)
  488. return results
  489. def run(arguments, content, options, state_machine, state, lineno):
  490. document = state_machine.document
  491. config = document.settings.env.config
  492. nofigs = 'nofigs' in options
  493. formats = get_plot_formats(config)
  494. default_fmt = formats[0][0]
  495. options.setdefault('include-source', config.plot_include_source)
  496. keep_context = 'context' in options
  497. context_opt = None if not keep_context else options['context']
  498. rst_file = document.attributes['source']
  499. rst_dir = os.path.dirname(rst_file)
  500. if len(arguments):
  501. if not config.plot_basedir:
  502. source_file_name = os.path.join(setup.app.builder.srcdir,
  503. directives.uri(arguments[0]))
  504. else:
  505. source_file_name = os.path.join(setup.confdir, config.plot_basedir,
  506. directives.uri(arguments[0]))
  507. # If there is content, it will be passed as a caption.
  508. caption = '\n'.join(content)
  509. # If the optional function name is provided, use it
  510. if len(arguments) == 2:
  511. function_name = arguments[1]
  512. else:
  513. function_name = None
  514. code = Path(source_file_name).read_text(encoding='utf-8')
  515. output_base = os.path.basename(source_file_name)
  516. else:
  517. source_file_name = rst_file
  518. code = textwrap.dedent("\n".join(map(str, content)))
  519. counter = document.attributes.get('_plot_counter', 0) + 1
  520. document.attributes['_plot_counter'] = counter
  521. base, ext = os.path.splitext(os.path.basename(source_file_name))
  522. output_base = '%s-%d.py' % (base, counter)
  523. function_name = None
  524. caption = ''
  525. base, source_ext = os.path.splitext(output_base)
  526. if source_ext in ('.py', '.rst', '.txt'):
  527. output_base = base
  528. else:
  529. source_ext = ''
  530. # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
  531. output_base = output_base.replace('.', '-')
  532. # is it in doctest format?
  533. is_doctest = contains_doctest(code)
  534. if 'format' in options:
  535. if options['format'] == 'python':
  536. is_doctest = False
  537. else:
  538. is_doctest = True
  539. # determine output directory name fragment
  540. source_rel_name = relpath(source_file_name, setup.confdir)
  541. source_rel_dir = os.path.dirname(source_rel_name)
  542. while source_rel_dir.startswith(os.path.sep):
  543. source_rel_dir = source_rel_dir[1:]
  544. # build_dir: where to place output files (temporarily)
  545. build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
  546. 'plot_directive',
  547. source_rel_dir)
  548. # get rid of .. in paths, also changes pathsep
  549. # see note in Python docs for warning about symbolic links on Windows.
  550. # need to compare source and dest paths at end
  551. build_dir = os.path.normpath(build_dir)
  552. if not os.path.exists(build_dir):
  553. os.makedirs(build_dir)
  554. # output_dir: final location in the builder's directory
  555. dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir,
  556. source_rel_dir))
  557. if not os.path.exists(dest_dir):
  558. os.makedirs(dest_dir) # no problem here for me, but just use built-ins
  559. # how to link to files from the RST file
  560. dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir),
  561. source_rel_dir).replace(os.path.sep, '/')
  562. try:
  563. build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
  564. except ValueError:
  565. # on Windows, relpath raises ValueError when path and start are on
  566. # different mounts/drives
  567. build_dir_link = build_dir
  568. source_link = dest_dir_link + '/' + output_base + source_ext
  569. # make figures
  570. try:
  571. results = render_figures(code,
  572. source_file_name,
  573. build_dir,
  574. output_base,
  575. keep_context,
  576. function_name,
  577. config,
  578. context_reset=context_opt == 'reset',
  579. close_figs=context_opt == 'close-figs')
  580. errors = []
  581. except PlotError as err:
  582. reporter = state.memo.reporter
  583. sm = reporter.system_message(
  584. 2, "Exception occurred in plotting {}\n from {}:\n{}".format(
  585. output_base, source_file_name, err),
  586. line=lineno)
  587. results = [(code, [])]
  588. errors = [sm]
  589. # Properly indent the caption
  590. caption = '\n'.join(' ' + line.strip()
  591. for line in caption.split('\n'))
  592. # generate output restructuredtext
  593. total_lines = []
  594. for j, (code_piece, images) in enumerate(results):
  595. if options['include-source']:
  596. if is_doctest:
  597. lines = ['', *code_piece.splitlines()]
  598. else:
  599. lines = ['.. code-block:: python', '',
  600. *textwrap.indent(code_piece, ' ').splitlines()]
  601. source_code = "\n".join(lines)
  602. else:
  603. source_code = ""
  604. if nofigs:
  605. images = []
  606. opts = [
  607. ':%s: %s' % (key, val) for key, val in options.items()
  608. if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]
  609. # Not-None src_link signals the need for a source link in the generated
  610. # html
  611. if j == 0 and config.plot_html_show_source_link:
  612. src_link = source_link
  613. else:
  614. src_link = None
  615. result = jinja2.Template(config.plot_template or TEMPLATE).render(
  616. default_fmt=default_fmt,
  617. dest_dir=dest_dir_link,
  618. build_dir=build_dir_link,
  619. source_link=src_link,
  620. multi_image=len(images) > 1,
  621. options=opts,
  622. images=images,
  623. source_code=source_code,
  624. html_show_formats=config.plot_html_show_formats and len(images),
  625. caption=caption)
  626. total_lines.extend(result.split("\n"))
  627. total_lines.extend("\n")
  628. if total_lines:
  629. state_machine.insert_input(total_lines, source=source_file_name)
  630. # copy image files to builder's output directory, if necessary
  631. Path(dest_dir).mkdir(parents=True, exist_ok=True)
  632. for code_piece, images in results:
  633. for img in images:
  634. for fn in img.filenames():
  635. destimg = os.path.join(dest_dir, os.path.basename(fn))
  636. if fn != destimg:
  637. shutil.copyfile(fn, destimg)
  638. # copy script (if necessary)
  639. Path(dest_dir, output_base + source_ext).write_text(
  640. unescape_doctest(code) if source_file_name == rst_file else code,
  641. encoding='utf-8')
  642. return errors