plot_directive.py 26 KB

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