7171 If specified, the code block will be run, but no figures will be
7272 inserted. This is usually useful with the ``:context:`` option.
7373
74+ caption : str
75+ If specified, the option's argument will be used as a caption for the
76+ figure. This overwrites the caption given in the content, when the plot
77+ is generated from a file.
78+
7479Additionally, this directive supports all of the options of the `image`
7580directive, except for *target* (since plot will add its own target). These
7681include *alt*, *height*, *width*, *scale*, *align* and *class*.
@@ -240,12 +245,16 @@ class PlotDirective(Directive):
240245 'context' : _option_context ,
241246 'nofigs' : directives .flag ,
242247 'encoding' : directives .encoding ,
248+ 'caption' : directives .unchanged ,
243249 }
244250
245251 def run (self ):
246252 """Run the plot directive."""
247- return run (self .arguments , self .content , self .options ,
248- self .state_machine , self .state , self .lineno )
253+ try :
254+ return run (self .arguments , self .content , self .options ,
255+ self .state_machine , self .state , self .lineno )
256+ except Exception as e :
257+ raise self .error (str (e ))
249258
250259
251260def setup (app ):
@@ -636,6 +645,16 @@ def run(arguments, content, options, state_machine, state, lineno):
636645 # If there is content, it will be passed as a caption.
637646 caption = '\n ' .join (content )
638647
648+ # Enforce unambiguous use of captions.
649+ if "caption" in options :
650+ if caption :
651+ raise ValueError (
652+ 'Caption specified in both content and options.'
653+ ' Please remove ambiguity.'
654+ )
655+ # Use caption option
656+ caption = options ["caption" ]
657+
639658 # If the optional function name is provided, use it
640659 if len (arguments ) == 2 :
641660 function_name = arguments [1 ]
@@ -652,7 +671,7 @@ def run(arguments, content, options, state_machine, state, lineno):
652671 base , ext = os .path .splitext (os .path .basename (source_file_name ))
653672 output_base = '%s-%d.py' % (base , counter )
654673 function_name = None
655- caption = ''
674+ caption = options . get ( 'caption' , '' )
656675
657676 base , source_ext = os .path .splitext (output_base )
658677 if source_ext in ('.py' , '.rst' , '.txt' ):
0 commit comments