
    Mh_              	          d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	 ddl
mZ ddl
mZ g dZ G d d	e          Zd
 Z G d d          Z G d de          Z G d de          Z G d dee          Z G d d          Z G d dee          Z G d dee          Z	 	 d=dZedk    rddlZ ej        d !          Ze                    d"d#d$d%&           e                    d'd(d$d)&           e                    d*d+dd,-           e                    d.d/d0d1-           e                    d2d3d$d4&           e                    d5d6dd7-           e                    d8d9d:;           e                                Z eej         d         ej!        ej"        ej#        ej$        ej%        ej&        <           dS dS )>a  Module for interactive demos using IPython.

This module implements a few classes for running Python scripts interactively
in IPython for demonstrations.  With very simple markup (a few tags in
comments), you can control points where the script stops executing and returns
control to IPython.


Provided classes
----------------

The classes are (see their docstrings for further details):

 - Demo: pure python demos

 - IPythonDemo: demos with input to be processed by IPython as if it had been
   typed interactively (so magics work, as well as any other special syntax you
   may have added via input prefilters).

 - LineDemo: single-line version of the Demo class.  These demos are executed
   one line at a time, and require no markup.

 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
   executed a line at a time, but processed via IPython).

 - ClearMixin: mixin to make Demo classes with less visual clutter.  It
   declares an empty marquee and a pre_cmd that clears the screen before each
   block (see Subclassing below).

 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
   classes.

Inheritance diagram:

.. inheritance-diagram:: IPython.lib.demo
   :parts: 3

Subclassing
-----------

The classes here all include a few methods meant to make customization by
subclassing more convenient.  Their docstrings below have some more details:

  - highlight(): format every block and optionally highlight comments and
    docstring content.

  - marquee(): generates a marquee to provide visible on-screen markers at each
    block start and end.

  - pre_cmd(): run right before the execution of each block.

  - post_cmd(): run right after the execution of each block.  If the block
    raises an exception, this is NOT called.


Operation
---------

The file is run in its own empty namespace (though you can pass it a string of
arguments as if in a command line environment, and it will see those as
sys.argv).  But at each stop, the global IPython namespace is updated with the
current internal demo namespace, so you can work interactively with the data
accumulated so far.

By default, each block of code is printed (with syntax highlighting) before
executing it and you have to confirm execution.  This is intended to show the
code to an audience first so you can discuss it, and only proceed with
execution once you agree.  There are a few tags which allow you to modify this
behavior.

The supported tags are:

# <demo> stop

  Defines block boundaries, the points where IPython stops execution of the
  file and returns to the interactive prompt.

  You can optionally mark the stop tag with extra dashes before and after the
  word 'stop', to help visually distinguish the blocks in a text editor:

  # <demo> --- stop ---


# <demo> silent

  Make a block execute silently (and hence automatically).  Typically used in
  cases where you have some boilerplate or initialization code which you need
  executed but do not want to be seen in the demo.

# <demo> auto

  Make a block execute automatically, but still being printed.  Useful for
  simple code which does not warrant discussion, since it avoids the extra
  manual confirmation.

# <demo> auto_all

  This tag can _only_ be in the first block, and if given it overrides the
  individual auto tags to make the whole demo fully automatic (no block asks
  for confirmation).  It can also be given at creation time (or the attribute
  set later) to override what's in the file.

While _any_ python file can be run as a Demo instance, if there are no stop
tags the whole file will run in a single block (no different that calling
first %pycat and then %run).  The minimal markup to make this useful is to
place a set of stop tags; the other tags are only there to let you fine-tune
the execution.

This is probably best explained with the simple example file below.  You can
copy this into a file named ex_demo.py, and try running it via::

    from IPython.lib.demo import Demo
    d = Demo('ex_demo.py')
    d()

Each time you call the demo object, it runs the next block.  The demo object
has a few useful methods for navigation, like again(), edit(), jump(), seek()
and back().  It can be reset for a new run via reset() or reloaded from disk
(in case you've edited the source) via reload().  See their docstrings below.

Note: To make this simpler to explore, a file called "demo-exercizer.py" has
been added to the "docs/examples/core" directory.  Just cd to this directory in
an IPython session, and type::

  %run demo-exercizer.py

and then follow the directions.

Example
-------

The following is a very simple example of a valid demo file.

::

    #################### EXAMPLE DEMO <ex_demo.py> ###############################
    '''A simple interactive demo to illustrate the use of IPython's Demo class.'''

    print('Hello, welcome to an interactive IPython demo.')

    # The mark below defines a block boundary, which is a point where IPython will
    # stop execution and return to the interactive prompt. The dashes are actually
    # optional and used only as a visual aid to clearly separate blocks while
    # editing the demo code.
    # <demo> stop

    x = 1
    y = 2

    # <demo> stop

    # the mark below makes this block as silent
    # <demo> silent

    print('This is a silent block, which gets executed but not printed.')

    # <demo> stop
    # <demo> auto
    print('This is an automatic block.')
    print('It is executed without asking for confirmation, but printed.')
    z = x + y

    print('z =', x)

    # <demo> stop
    # This is just another normal block.
    print('z is now:', z)

    print('bye!')
    ################### END EXAMPLE DEMO <ex_demo.py> ############################
    N)Pathmarquee)openpy)	py3compat)DemoIPythonDemoLineDemoIPythonLineDemo	DemoErrorc                       e Zd ZdS )r   N__name__
__module____qualname__     P/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/lib/demo.pyr   r      s          r   r   c                 F    t          j        d| z  t           j                  S )Nz^\s*#\s+<demo>\s+%s\s*$)recompile	MULTILINE)marks    r   re_markr      s    :047EEEr   c                       e Zd Z ed          Z ed          Z ed          Z ed          Z	 	 d d
Zd Z	d Z
d Zd Zd Zd Zd!dZd!dZd Zd"dZd"dZd Zd Zd"dZd#dZd Zd Zd ZdS )$r   z-*\s?stop\s?-*silentautoauto_all NFterminaldefaultc                     t          |d          rd| _        |dk    rd| _        nF|| _        n>|| _        |dk    r*t          j                            |          \  }}	|	| _        n|| _        |gt          j        |          z   | _        || _        || _	        	 t                      }
d| _        n# t          $ r
 d| _        Y nw xY w| j        r7|
j        | _        |
j        | _        |
j        | _        |
j        | _        |
| _        t,          j                            ||          | _        t,          j                            d          | _        || _        |r$t,          j                            d          | _        |                                  d	S )
a  Make a new demo object.  To run the demo, simply call the object.

        See the module docstring for full details and an example (you can use
        IPython.Demo? in IPython to see it).

        Inputs:

          - src is either a file, or file-like object, or a
              string that can be resolved to a filename.

        Optional inputs:

          - title: a string to use as the demo name.  Of most use when the demo
            you are making comes from an object that has no filename, or if you
            want an alternate denotation distinct from the filename.

          - arg_str(''): a string of arguments, internally converted to a list
            just like sys.argv, so the demo script can see a similar
            environment.

          - auto_all(None): global flag to run all blocks automatically without
            confirmation.  This attribute overrides the block-level tags and
            applies to the whole demo.  It is an attribute of the object, and
            can be changed at runtime simply by reassigning it to a boolean
            value.

          - format_rst(False): a bool to enable comments and doc strings
            formatting with pygments rst lexer

          - formatter('terminal'): a string of pygments formatter name to be
            used. Useful values for terminals: terminal, terminal256,
            terminal16m

          - style('default'): a string of pygments style name to be used.
        readzfrom a file-like objectr   TF)stylepy3rstN) hasattrfnametitleospathsplitshlexsys_argvr   srcget_ipythoninside_ipython	NameErroruser_nsip_ns
pycolorizeip_colorizeshowtraceback	ip_showtbrun_cellip_run_cellshellpygments
formattersget_formatter_by_name	formatterlexersget_lexer_by_namepython_lexer
format_rst	rst_lexerreload)selfr/   r)   arg_strr   rC   r?   r$   filepathfilenameips              r   __init__zDemo.__init__   s   J 3 	#2DJ{{6

"

 DJ{{')w}}S'9'9$8%

"
G 4 44 	(B"&D 	( 	( 	("'D	(  		"
  "zDJ!}D!/DN!{D!DJ!,BB9IN C P P$O==eDD$ 	F%_>>uEEDN 	s   B. .CCc                     t          | d          r | j        | j                                         t          | j        d          r| j        | _        dS t	          j        | j                  | _        dS )zLoad file object.fobjNr#   )r'   rM   closer/   r   openr(   rF   s    r   floadz
Demo.fload!  si     4   	TY%:9??48V$$ 	0DIII DJ//DIIIr   c                                                        d                    t          j         j                             _        d  j                             j                  D             } fd|D              _         fd|D              _	         j
        3t           j                            |d                              _
        nt           j
                   _
        g } fd}t          |          D ]F\  }} j	        |         r|                     ||                     1|                    |           G j                            d|d                   |d<   t#          |           _        | _        t)          t+           j         j                             _                                          dS )-Reload source from disk and initialize state.r   c                 :    g | ]}||                                 S r   strip).0bs     r   
<listcomp>zDemo.reload.<locals>.<listcomp>2  s%    MMMa1M		MMMr   c                 ^    g | ])}t          j                            |                    *S r   )bool	re_silentfindallrW   rX   rF   s     r   rY   zDemo.reload.<locals>.<listcomp>3  s1    GGGAT^33A6677GGGr   c                 ^    g | ])}t          j                            |                    *S r   )r[   re_autor]   r^   s     r   rY   zDemo.reload.<locals>.<listcomp>4  s1    EEE!T\11!4455EEEr   Nr   c                 :    j                             d|           S )Nr   )r`   sub)srF   s    r   <lambda>zDemo.reload.<locals>.<lambda>?  s    t|//155 r   )rQ   joinr   strip_encoding_cookierM   r/   re_stopr,   _silent_autor   r[   re_auto_allr]   	enumerateappendrb   lennblocks
src_blockslistmap	highlightsrc_blocks_coloredreset)rF   src_bro   
auto_stripirX   s   `     r   rE   zDemo.reload-  s   

wwv;DIFFGGMM4<+=+=dh+G+GMMMGGGGGGGEEEEuEEE
 =  !1!9!9%(!C!CDDDMM //DM 
5555
U## 	% 	%CAaz!} %!!**Q--0000!!!$$$$(,,R
1>>
1:$ #'s4>$/'J'J"K"K 	

r   c                 0    i | _         d| _        d| _        dS )z8Reset the namespace and seek pointer to restart the demoFr   N)r3   finishedblock_indexrP   s    r   rt   z
Demo.resetQ  s     r   c                 L    |dk     s|| j         k    rt          d|z            d S )Nr   zinvalid block index %s)rn   
ValueErrorrF   indexs     r   _validate_indexzDemo._validate_indexW  s3    77eT\))5=>>> *)r   c                 t    | | j         rt          d           dS | j        }n|                     |           |S )zjGet the current block index, validating and checking status.

        Returns None if the demo is finishedNz@Demo finished.  Use <demo_name>.reset() if you want to rerun it.)ry   printrz   r   r}   s     r   
_get_indexzDemo._get_index[  sJ    
 =} XYYYt$EE  '''r   c                 l    |dk     r
| j         |z   }|                     |           || _        d| _        dS )zMove the current seek pointer to the given block.

        You can use negative indices to seek from the end, with identical
        semantics to those of Python lists.r   FN)rn   r   rz   ry   r}   s     r   seekz	Demo.seeki  s@    
 77L5(EU### r      c                 @    |                      | j        |z
             dS )z5Move the seek pointer back num blocks (default is 1).Nr   rz   rF   nums     r   backz	Demo.backt  s"    		$"3&'''''r   c                 @    |                      | j        |z              dS )zzJump a given number of blocks relative to the current one.

        The offset can be positive or negative, defaults to 1.Nr   r   s     r   jumpz	Demo.jumpx  s$     			$"3&'''''r   c                 D    |                      d            |              dS )z4Move the seek pointer back one block and re-execute.r   N)r   rP   s    r   againz
Demo.again~  s     		!r   c                    |                      |          }|dS |dk    r|dz  }| j                            | j        |                   }| j        j                            |d           t          t          |          dd          5 }|                                }ddd           n# 1 swxY w Y   || j        |<   | 	                    |          | j
        |<   || _         |              dS )a  Edit a block.

        If no number is given, use the last block executed.

        This edits the in-memory copy of the demo, it does NOT modify the
        original source file.  If you want to do that, simply open the file in
        an editor and use reload() when you make changes to the file.  This
        method is meant to let you change a block during a demonstration for
        explanatory purposes, without damaging your original script.Nr   r   rzutf-8)encoding)r   r;   
mktempfilero   hookseditorrO   r   r#   rr   rs   rz   )rF   r~   rI   f	new_blocks        r   editz	Demo.edit  s"    &&=F 77QJE:(()?@@
!,,,$x..#888 	!AI	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! "+)-	)B)B& s   	B**B.1B.c                     |                      |          }|dS t          |                     d| j        d|d| j        |z
  dz
  d                     t          | j        |                    t          j                                         dS )zShow a single block on screenN<
> block #  (r    remaining))	r   r   r   r)   rn   rs   sysstdoutflushr}   s     r   showz	Demo.show  s     &&=Fdlll JJJuuuT\%-?-A-A-AC D D 	E 	E 	Ed%e,---
r   c                    | j         }| j         }| j        }| j        }| j        }t	          | j                  D ]o\  }}||         r)t           |d|d|d||z
  dz
  d                     n(t           |d|d|d||z
  dz
  d                     t          |d           pt          j        	                                 d	S )
z*Show entire demo on screen, block by blockr   z> SILENT block # r   r   r   r    endN)
r)   rn   rh   r   rk   rs   r   r   r   r   )rF   r(   r)   rn   r   r   r~   blocks           r   show_allzDemo.show_all  s    

,,$T%<== 	" 	"KE%e} >ggg$uuUUU75=???< = = > > > > ggg$uuUUU75=???< = = > > >%S!!!!!
r   c                 0    t          || j                   dS z/Execute a string with one or more lines of codeN)execr3   rF   sources     r   r9   zDemo.run_cell  s     	VT\"""""r   c           	         |                      |          }|dS 	 | j        }| j        |         }| xj        dz  c_        | j        |         r+t           |d|d| j        |z
  dz
  d                     n|                                  |                     |           | j	        s| j
        |         rt           |d                     n[t           |d          d	           t          j                                                    }|rt           |d
                     dS 	 t          j        }| j        t          _        |                     |           |                                  |t          _        n# |t          _        w xY w	 | j        r| j                            | j                   n)#  | j        r|                     | j                   Y nxY w| j        | j        k    r_|                     d          }|r?t                       t          |           t          |                     d                     d| _        dS dS )ab  run a block of the demo.

        If index is given, it should be an integer >=1 and <= nblocks.  This
        means that the calling convention is one off from typical Python
        lists.  The reason for the inconsistency is that the demo always
        prints 'Block n/N, and N is the total, so it would be very odd to use
        zero-indexing here.Nr   zExecuting silent block # r   r   zoutput:z(Press <q> to quit, <Enter> to execute...r   r   zBlock NOT executed)rI   zEND OF DEMOz0Use <demo_name>.reset() if you want to rerun it.T)r   r   ro   rz   rh   r   rn   pre_cmdr   r   ri   r   inputrV   r   argvr.   r9   post_cmdr1   r4   updater3   r8   r(   ry   )rF   r~   r   
next_blockans	save_argvmq1s          r   __call__zDemo.__call__  se    &&=F	0lG/J!|E" ggg$uuT\%%7%9%9%9; < < = = = = 		%   = DJu$5 ''),,----''"LMMSVWWWW#/++1133C gg&:;;<<<%H	=j)))$9$$$$ " 0
!!$,///	4" 4
333
 t|++,,}--C Xc


dll#UVVWWW DMMM ,+s%   DF5 )AE< /F5 <F

F5 5$GN   *c                 $    t          |||          S )z0Return the input string centered in a 'marquee'.r   rF   txtwidthr   s       r   r   zDemo.marquee  s    s5&&&r   c                     dS )z*Method called before executing each block.Nr   rP   s    r   r   zDemo.pre_cmd       r   c                     dS )z)Method called after executing each block.Nr   rP   s    r   r   zDemo.post_cmd  r   r   c           	      2   t          j        || j                  }| j        r\ddlm} g }|D ]N}|d         |j        j        k    rt          |d                   dk    r|t          j        |d         dd         | j                  z  }|t          j        |d         dd         | j	                  z  }|t          j        |d         dd         | j                  z  }|d         |j
        j        k    ro|                    |j
        j        |d         d         f           |t          t          j        |d         dd         | j	                            dd         z  }9|                    |           P|}t          j        || j                  S )	z3Method called on each block to highlight it contentr   )Tokenr      N   )r<   lexrB   rC   pygments.tokenr   StringDocrm   rD   CommentSinglerl   rp   formatr?   )rF   r   tokensr   tokstokens         r   rr   zDemo.highlight  s}   eT%677? 	,,,,,,D ' '8u|///CaMMA4E4EHLq"1"t7HIIIDHLq!B$HHHDHLq"##8IJJJDD1X!555KK!5uQx{ CDDD DeAhqrrlDN!K!KLLSbSQQDDKK&&&&Fvt~666r   )r   r   NFr    r!   )r   )Nr   r   r   )r   r   r   r   rg   r\   r`   rj   rK   rQ   rE   rt   r   r   r   r   r   r   r   r   r   r9   r   r   r   r   rr   r   r   r   r   r      s       '+,,G'(##I'&//G'*%%KHM-6Q Q Q Qf
0 
0 
0" " "H  ? ? ?  	 	 	( ( ( (( ( ( (  
   <
 
 
 
  $# # #
4! 4! 4! 4!p' ' ' '    7 7 7 7 7r   r   c                       e Zd ZdZd ZdS )r	   aD  Class for interactive demos with IPython's input processing applied.

    This subclasses Demo, but instead of executing each block by the Python
    interpreter (via exec), it actually calls IPython on it, so that any input
    filters which may be in place are applied to the input block.

    If you have an interactive environment which exposes special input
    processing, you can use this class instead to write demo scripts which
    operate exactly as if you had typed them interactively.  The default Demo
    class requires the input to be valid, pure Python code.
    c                 :    | j                             |           dS r   )r;   r9   r   s     r   r9   zIPythonDemo.run_cell,  s      	
F#####r   N)r   r   r   __doc__r9   r   r   r   r	   r	     s-        
 
$ $ $ $ $r   r	   c                       e Zd ZdZd ZdS )r
   a  Demo where each line is executed as a separate block.

    The input script should be valid Python code.

    This class doesn't require any markup at all, and it's meant for simple
    scripts (with no nesting or any kind of indentation) which consist of
    multiple lines of input to be executed, one at a time, as if they had been
    typed in the interactive prompt.

    Note: the input can not have *any* indentation, which means that only
    single-lines of input are accepted, not even function definitions are
    valid.c                    |                                   | j                                        }d |D             }t          |          }d                    |          | _        dg|z  | _        dg|z  | _        d| _        || _	        || _
        t          t          | j        | j
                            | _        |                                  dS )rS   c                 :    g | ]}|                                 |S r   rU   )rW   ls     r   rY   z#LineDemo.reload.<locals>.<listcomp>D  s%    999qwwyy91999r   r   FTN)rQ   rM   	readlinesrm   re   r/   rh   ri   r   rn   ro   rp   rq   rr   rs   rt   )rF   linesru   rn   s       r   rE   zLineDemo.reload?  s     	

)--//99e999e**''%.. ''/&.
! #'s4>$/'J'J"K"K 	

r   N)r   r   r   r   rE   r   r   r   r
   r
   1  s-             r   r
   c                       e Zd ZdZdS )r   zBVariant of the LineDemo class whose input is processed by IPython.N)r   r   r   r   r   r   r   r   r   T  s        LLDr   r   c                        e Zd ZdZddZd ZdS )	
ClearMixina  Use this mixin to make Demo classes with less visual clutter.

    Demos using this mixin will clear the screen before every block and use
    blank marquees.

    Note that in order for the methods defined here to actually override those
    of the classes it's mixed with, it must go /first/ in the inheritance
    tree.  For example:

        class ClearIPDemo(ClearMixin,IPythonDemo): pass

    will provide an IPythonDemo class with the mixin's features.
    r   r   r   c                     dS )z7Blank marquee that returns '' no matter what the input.r   r   r   s       r   r   zClearMixin.marqueeh  s    rr   c                 &    ddl m}  |             dS )zVMethod called before executing each block.

        This one simply clears the screen.r   )_term_clearN)IPython.utils.terminalr   )rF   r   s     r   r   zClearMixin.pre_cmdl  s%     	766666r   Nr   )r   r   r   r   r   r   r   r   r   r   r   Y  sA                r   r   c                       e Zd ZdS )	ClearDemoNr   r   r   r   r   r   s          Dr   r   c                       e Zd ZdS )ClearIPDemoNr   r   r   r   r   r   w  r   r   r   FTr    native...c                     |rt           }nt          } || ||||          }|j        sK |             	 t          j        d|z              n# t
          $ r t          d           Y nw xY w|j        Id S d S )N)rC   r?   r$   r   
r   )r   r   ry   r   r   KeyboardInterruptexit)		file_pathnoclearrC   r?   r$   r   	delimiter
demo_classdemos	            r   slider   {  s     


:iJ)!H6 6 6Dm 	OD9,----  	 	 	GGGGG		 m     s   A A('A(__main__zRun python demos)descriptionz	--noclearz-C
store_truez#Do not clear terminal on each slide)actionhelpz--rstz-rz'Highlight comments and dostrings as rstz--formatterz-fzDpygments formatter name could be: terminal, terminal256, terminal16m)r!   r   z--stylez-sr!   zpygments style namez--autoz-az0Run all blocks automatically withoutconfirmationz--delimiterz-dz+slides delimiter added after each slide runfiler   zpython demo file)nargsr   )r   rC   r?   r$   r   r   )FTr    r   Fr   )'r   r*   r   r-   r   r<   pathlibr   IPython.utils.textr   IPython.utilsr   r   __all__	Exceptionr   r   r   r	   r
   r   r   r   r   r   r   argparseArgumentParserparseradd_argument
parse_argsargsr   r   r&   r?   r$   r   r   r   r   r   <module>r     s  j jj 
			 				  



        & & & & & &             # # # # # #
I
I
I          	      F F FU7 U7 U7 U7 U7 U7 U7 U7p
$ $ $ $ $$ $ $ $$         t      F	 	 	 	 	k( 	 	 	
       4	 	 	 	 	
4 	 	 		 	 	 	 	*[ 	 	 	 @J49    zOOO$X$1CDDDF
T,B  D D D
lF  H H H
tZ3  4 4 4 	42  4 4 4
$|'  ( ( ( tUJ  L L L
a/  1 1 1D	E$)A,N$*tyN$ $ $ $ $ $) r   