
    Mh'q                     @   U d Z ddlZddlZddlZddlmZmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZmZ d	d
lmZ d	dlmZ d	dlmZ ddlmZmZmZmZ ddlm
Z
 ddlZ ei i           Zej        ed<   dZ dZ! eee          Z" G d d          Z#d Z$d Z%d Z&d Z'd Z(d Z)dZ*d Z+d Z,dZ-dZ.d Z/d  Z0 e+d!          Z1 e+d"          Z2 e+d#          Z3 e,d!          Z4 e,d"          Z5 e,d#          Z6 G d$ d%e          Z7 G d& d'e          Z8 G d( d)          Z9dS )*z&Magic functions for InteractiveShell.
    N)getoptGetoptError)Configurable   )oinspect)
UsageError)	ESC_MAGIC
ESC_MAGIC2   )Struct)	arg_split)dedent)BoolDictInstanceobserve)errorlinecellmagics)r   r   	line_cellc                       e Zd ZdS )BunchN)__name__
__module____qualname__     R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/core/magic.pyr   r   3   s          r   r   c                     ddg|          S )zAReturn an ON/OFF string for a 1/0 input. Simple utility function.OFFONr   )tags    r    on_offr%   6   s    $<r   c                     | dd         | dd         }}g }t                      }|D ]1}||v r|                    |           |                    |           2||z   S )zCompress a directory history into a new one with at most 20 entries.

    Return a new list made from the first and last 10 elements of dhist after
    removal of duplicates.
    Ni)setappendadd)dhheadtailnewheaddonehs         r    compress_dhistr0   ;   ss     DSD2cdd8$DG55D  99qT>r   c                     d| _         | S )zCDecorator to mark magic functions which need to local scope to run.T)needs_local_scope)funcs    r    r2   r2   N   s    !DKr   c                     d| _         t          t          d         t          d                   | _        i t          d<   i t          d<   | S )a  Class decorator for all subclasses of the main Magics class.

    Any class that subclasses Magics *must* also apply this decorator, to
    ensure that all the methods that have been decorated as line/cell magics
    get correctly registered in the class instance.  This is necessary because
    when method decorators run, the class does not exist yet, so they
    temporarily store their information into a module global.  Application of
    this class decorator copies that global data to the class instance and
    clears the global.

    Obviously, this mechanism is not thread-safe, which means that the
    *creation* of subclasses of Magic should only be done in a single-thread
    context.  Instantiation of the classes has no restrictions.  Given that
    these classes are typically created at IPython startup time and before user
    application code becomes active, in practice this should not pose any
    problems.
    Tr   r   r   )
registereddictr   )clss    r    magics_classr8   W   sE    $ CNVF^#F^- - -CJF6NF6NJr   c                 X    |dk    r|x| d         |<   | d         |<   dS || |         |<   dS )aS  Utility function to store a function as a magic of a specific kind.

    Parameters
    ----------
    dct : dict
        A dictionary with 'line' and 'cell' subdicts.
    magic_kind : str
        Kind of magic to be stored.
    magic_name : str
        Key to store the magic as.
    func : function
        Callable object to store.
    r   r   r   Nr   )dct
magic_kind
magic_namer3   s       r    record_magicr=   q   sE     [  <@@FJ#f+j"9"9"9&*J
###r   c                 H    | t           vrt          dt          z  |           dS )zEnsure that the given magic_kind is valid.

    Check that the given magic_kind is one of the accepted spec types (stored
    in the global `magic_spec`), raise ValueError otherwise.
    &magic_kind must be one of %s, %s givenN)
magic_spec
ValueErrormagic_kinds)r;   s    r    validate_typerC      s7     ##A$%&02 2 	2 $#r   a  Decorate the given {0} as {1} magic.

The decorator can be used with or without arguments, as follows.

i) without arguments: it will create a {1} magic named as the {0} being
decorated::

    @deco
    def foo(...)

will create a {1} magic named `foo`.

ii) with one string argument: which will be used as the actual name of the
resulting magic::

    @deco('bar')
    def foo(...)

will create a {1} magic named `bar`.

To register a class magic use ``Interactiveshell.register_magic(class or instance)``.
c                 p     t                       fd}t                              d           |_        |S )z8Decorator factory for methods in Magics subclasses.
    c                     t          |           r#| }|j        | }t          t                     n/t	          | t
                    r| fd}|}nt          d          |S )Nc                 @    t          t          | j                   | S N)r=   r   r   )r3   akwr;   names      r    markz6_method_magic_marker.<locals>.magic_deco.<locals>.mark   s    VZt}EEEr   4Decorator can only be called with string or function)callabler   r=   r   
isinstancestr	TypeError)argr3   retvalrK   rJ   r;   s       @r    
magic_decoz(_method_magic_marker.<locals>.magic_deco   s    C== 	2D=DFT48888S!! 		2D      FF 1 2 2 2r   method)rC   _docstring_templateformat__doc__)r;   rS   s   ` r    _method_magic_markerrX      sL     *    ( -33HjIIJr   c                      t                       fd}t                              d           }|t          d          z  }||_        |S )z0Decorator factory for standalone functions.
    c                    t          j        d          }dD ])}t          ||                              d          }| n*t	          d           |            t          |           r#| }|j                            |	           | }n0t          | t                    r| 	fd}|}nt          d          |S )Nr   )f_locals	f_globals
f_builtinsget_ipythonz<Decorator can only run in context where `get_ipython` existsc                 6                         |            | S rG   )register_magic_function)r3   rH   rI   ipr;   rJ   s      r    rK   z8_function_magic_marker.<locals>.magic_deco.<locals>.mark   s     **4TBBBr   rL   )sys	_getframegetattrget	NameErrorrM   r   r`   rN   rO   rP   )
rQ   callernsr^   r3   rR   rK   ra   rJ   r;   s
          @@r    rS   z*_function_magic_marker.<locals>.magic_deco   s   q!!9 	4 	4B!&"--11-@@K& '  3 4 4 4 []]C== 	3D=D&&tZ>>>FFS!! 		3D       FF 2 3 3 3r   functiona  
    Note: this decorator can only be used in a context where IPython is already
    active, so that the `get_ipython()` call succeeds.  You can therefore use
    it in your startup files loaded after IPython initializes, but *not* in the
    IPython configuration file itself, which is executed before IPython is
    fully up and running.  Any file located in the `startup` subdirectory of
    your configuration profile will be OK in this sense.
    )rC   rU   rV   r   rW   )r;   rS   dss   `  r    _function_magic_markerrk      so     *    @ 
	#	#J
	;	;B&  	 	 	B Jr   _ipython_magic_no_var_expand%_ipython_magic_output_can_be_silencedc                 2    t          | t          d           | S )a  Mark a magic function as not needing variable expansion

    By default, IPython interprets `{a}` or `$a` in the line passed to magics
    as variables that should be interpolated from the interactive namespace
    before passing the line to the magic function.
    This is not always desirable, e.g. when the magic executes Python code
    (%timeit, %time, etc.).
    Decorate magics with `@no_var_expand` to opt-out of variable expansion.

    .. versionadded:: 7.3
    T)setattrMAGIC_NO_VAR_EXPAND_ATTR
magic_funcs    r    no_var_expandrs   
  s     J0$777r   c                 2    t          | t          d           | S )zMark a magic function so its output may be silenced.

    The output is silenced if the Python code used as a parameter of
    the magic ends in a semicolon, not counting a Python comment that can
    follow it.
    T)ro   MAGIC_OUTPUT_CAN_BE_SILENCEDrq   s    r    output_can_be_silencedrv     s     J4d;;;r   r   r   r   c                   l    e Zd ZdZ e            Z ed                              d          Z e            Z e	dd          Z
 edd                              d          Z ed	          d
             ZddgZ e	dd          Zd fd	Zd Zd ZddZdedefdZd ZddZddZ xZS )MagicsManagerzEObject that handles all magic-related functionality for IPython.
    aM  
    Mapping from magic names to modules to load.

    This can be used in IPython/IPykernel configuration to declare lazy magics
    that will only be imported/registered on first use.

    For example::

        c.MagicsManager.lazy_magics = {
          "my_magic": "slow.to.import",
          "my_other_magic": "also.slow",
        }

    On first invocation of `%my_magic`, `%%my_magic`, `%%my_other_magic` or
    `%%my_other_magic`, the corresponding module will be loaded as an ipython
    extensions as if you had previously done `%load_ext ipython`.

    Magics names should be without percent(s) as magics can be both cell
    and line magics.

    Lazy loading happen relatively late in execution process, and
    complex extensions that manipulate Python/IPython internal state or global state
    might not support lazy loading.
    )helpT)configz1IPython.core.interactiveshell.InteractiveShellABC)
allow_nonezBAutomatically call line magics without requiring explicit % prefix
auto_magicc                 *    |d         | j         _        d S )Nnew)shell	automagic)selfchanges     r    _auto_magic_changedz!MagicsManager._auto_magic_changedc  s    %e}
r   z5Automagic is OFF, % prefix IS needed for line magics.z8Automagic is ON, % prefix IS NOT needed for line magics.zIPython.core.magics.UserMagicsNc                      t          t          |           j        d|||d| t          i i           | _        || j        |j        j        <   d S )N)r   rz   user_magicsr   r   )superrx   __init__r6   r   registry	__class__r   )r   r   rz   r   traitsr   s        r    r   zMagicsManager.__init__m  sr    +mT""+ 	N%7B	N 	NFL	N 	N 	N,,, 9Dk+4555r   c                 &    | j         | j                 S )z0Return descriptive string with automagic status.)_auto_statusr|   r   s    r    auto_statuszMagicsManager.auto_statusv  s     11r   c                     | j         S )zReturn a dict of currently available magic functions.

        The return dict has the keys 'line' and 'cell', corresponding to the
        two types of magics we support.  Each value is a list of names.
        )r   r   s    r    lsmagiczMagicsManager.lsmagicz  s     {r   F c                    i }| j         D ]~}i }| j         |                                         D ]U\  }}|j        rD|r%|j                            dd          d         ||<   3|j                                        ||<   P|||<   V|||<   |S )a  Return dict of documentation of magic functions.

        The return dict has the keys 'line' and 'cell', corresponding to the
        two types of magics we support. Each value is a dict keyed by magic
        name whose value is the function docstring. If a docstring is
        unavailable, the value of `missing` is used instead.

        If brief is True, only the first line of each docstring will be returned.
        
r   r   )r   itemsrW   splitrstrip)r   briefmissingdocsm_typem_docsm_namem_funcs           r    lsmagic_docszMagicsManager.lsmagic_docs  s     k 
	" 
	"FF"&+f"5";";"="= - -> - A)/)=)=dA)F)Fq)Iv)/)>)>)@)@v%,F6NN!DLLr   rJ   fully_qualified_namec                     || j         |<   dS )a  
        Lazily register a magic via an extension.


        Parameters
        ----------
        name : str
            Name of the magic you wish to register.
        fully_qualified_name :
            Fully qualified name of the module/submodule that should be loaded
            as an extensions when the magic is first called.
            It is assumed that loading this extensions will register the given
            magic.
        N)lazy_magics)r   rJ   r   s      r    register_lazyzMagicsManager.register_lazy  s      "6r   c                    |D ]}|j         st          d          t          |t                    r || j                  }|| j        |j        j        <   t          D ]-}| j	        |         
                    |j	        |                    .dS )aJ  Register one or more instances of Magics.

        Take one or more classes or instances of classes that subclass the main
        `core.Magic` class, and register them with IPython to use the magic
        functions they provide.  The registration process will then ensure that
        any methods that have decorated to provide line and/or cell magics will
        be recognized with the `%x`/`%%x` syntax as a line/cell magic
        respectively.

        If classes are given, they will be instantiated with the default
        constructor.  If your classes need a custom constructor, you should
        instanitate them first and pass the instance.

        The provided arguments can be an arbitrary mix of classes and instances.

        Parameters
        ----------
        *magic_objects : one or more classes or instances
        zOClass of magics %r was constructed without the @register_magics class decorator)r   N)r5   rA   rN   typer   r   r   r   rB   r   update)r   magic_objectsmmtypes       r    registerzMagicsManager.register  s    ,  	; 	;A< I  "H I I I!T"" (ADJ''' 34DM!+./$ ; ;E"))!(5/::::;	; 	;r   r   c                     t          |           ||j        n|}t          | j        ||           t	          | j        |||           dS )a  Expose a standalone function as magic function for IPython.

        This will create an IPython magic (line, cell or both) from a
        standalone function.  The functions should have the following
        signatures:

        * For line magics: `def f(line)`
        * For cell magics: `def f(line, cell)`
        * For a function that does both: `def f(line, cell=None)`

        In the latter case, the function will be called with `cell==None` when
        invoked as `%f`, and with cell as a string when invoked as `%%f`.

        Parameters
        ----------
        func : callable
            Function to be registered as a magic.
        magic_kind : str
            Kind of magic, one of 'line', 'cell' or 'line_cell'
        magic_name : optional str
            If given, the name the magic will have in the IPython namespace.  By
            default, the name of the function itself is used.
        N)rC   r   ro   r   r=   r   )r   r3   r;   r<   s       r    register_functionzMagicsManager.register_function  sS    6 	j!!!&0&8T]]j
 *d333T[*j$?????r   c                     |t           vrt          dt           z  |          t          | j        |||          }t	          | j        ||           t          | j        |||           dS )a3  Register an alias to a magic function.

        The alias is an instance of :class:`MagicAlias`, which holds the
        name and kind of the magic it should call. Binding is done at
        call time, so if the underlying magic function is changed the alias
        will call the new function.

        Parameters
        ----------
        alias_name : str
            The name of the magic to be registered.
        magic_name : str
            The name of an existing magic.
        magic_kind : str
            Kind of magic, one of 'line' or 'cell'
        r?   N)rB   rA   
MagicAliasr   ro   r   r=   r   )r   
alias_namer<   r;   magic_paramsaliass         r    register_aliaszMagicsManager.register_alias  sw    ( [((E()*46 6 6 4:z:|LL *e444T[*j%@@@@@r   )NNN)Fr   )r   N)r   r   r   rW   r   r   r$   r   r   r   r   r   r|   r   r   r   r   r   r   r   r   rO   r   r   r   r   __classcell__r   s   @r    rx   rx   5  s         TVVF$  2 
c 
  3 < tvvHHHUYZZZEdL  	cc  W\- - - 	@BDL (;MMMKD D D D D D2 2 2     06# 6S 6 6 6 6$"; "; ";H@ @ @ @@A A A A A A A Ar   rx   c                   L     e Zd ZdZdZdZdZdZd	 fd	Zd Z	d Z
d Zd Z xZS )
Magicsa  Base class for implementing magic functions.

    Shell functions which can be reached as %function_name. All magic
    functions should accept a string, which they can parse for their own
    needs. This can make some functions easier to type, eg `%cd ../`
    vs. `%cd("../")`

    Classes providing magic functions need to subclass this class, and they
    MUST:

    - Use the method decorators `@line_magic` and `@cell_magic` to decorate
      individual methods as magic functions, AND

    - Use the class decorator `@magics_class` to ensure that the magic
      methods are properly registered at the instance level upon instance
      initialization.

    See :mod:`magic_functions` for examples of actual implementation classes.
    NFc                 &   | j         j        st          d          |Pt          |d          r|j                            |            t          |d          r|                    d|           || _        i | _        | j	        }i | _	        t          D ]^}i x}| j	        |<   ||         }|                                D ]3\  }}t          |t                    rt          | |          ||<   .|||<   4_ t          t           |           j        di | d S )NzMMagics subclass without registration - did you forget to apply @magics_class?configurablesrz   parentr   )r   r5   rA   hasattrr   r(   
setdefaultr   options_tabler   rB   r   rN   rO   rd   r   r   r   )
r   r   kwargsclass_magicsr   tabcls_tabr<   	meth_namer   s
            r    r   zMagics.__init__,  sL   ~( 	G F G G Guo.. 1#**4000uh'' 3!!(E222
 {  		0 		0E'))C$+e$"5)G)0 0 0%
Ii-- 0&-dI&>&>C
OO '0C
OO0 	%fd$..v.....r   c                 f    t          d           t          t          j        |                     dS )z2Print docstring if incorrect arguments were passedzError in arguments:N)printr   getdoc)r   r3   s     r    arg_errzMagics.arg_errN  s/    #$$$hod##$$$$$r   c                 "   t          j        dt           j                  }t          j        dt          z  t           j                  }t          j        dt          z  t           j                  }t          j        dt           j                  }t          j        d          }|                    d|          }|                    d|          }|                    d|          }|                    d	|          }|                    d
|          }|S )z$Format a string for latex inclusion.z(%|_|\$|#|&)z	^(%s.*?):z(?P<cmd>%s.+?\b)(?!\}\}:)z\\$z\\nz%\n\\bigskip\n\\texttt{\\textbf{ \1}}:z\\texttt{\g<cmd>}z\\\\z\\\1z\\textbackslash{}n)recompile	MULTILINEr	   sub)r   strng	escape_recmd_name_recmd_repar_re
newline_res          r    format_latexzMagics.format_latexS  s     Jr|<<	j	!9!#/ / 89DL* * F2<00 Z''
  H %' '

/66

75))ge,,4U;;r   c                    t          j        d          j        j        }| j                            |d          d|}|                    dd          }|dvrt          d|z            |                    dd	          }|                    d
t          j        d
k              }|                    dd          }	|                    dd          }
|}i }|	                                }t          |          dk    r)t          |||	          }	 t          |||          \  }}nJ# t          $ r=}t          |j        d|d|rd                    d|z             ndd          |d}~ww xY w|D ]\  }}|dk    r.|
r,|                    |dd                              |dd          }|                    d          r|dd         }n
|dd         }	 ||                             |           # t(          $ r ||         |g||<   Y t*          $ r |r|g||<   n|||<   Y w xY wt-          |          }|dk    r,|
r|                                }nd                    |          }||fS )al  Parse options passed to an argument string.

        The interface is similar to that of :func:`getopt.getopt`, but it
        returns a :class:`~IPython.utils.struct.Struct` with the options as keys
        and the stripped argument string still as a string.

        arg_str is quoted as a true sys.argv vector by using shlex.split.
        This allows us to easily expand variables, glob files, quote
        arguments, etc.

        Parameters
        ----------
        arg_str : str
            The arguments to parse.
        opt_str : str
            The options specification.
        mode : str, default 'string'
            If given as 'list', the argument string is returned as a list (split
            on whitespace) instead of a string.
        list_all : bool, default False
            Put all option values in lists. Normally only options
            appearing more than once are put in a list.
        posix : bool, default True
            Whether to split the input line in POSIX mode or not, as per the
            conventions outlined in the :mod:`shlex` module from the standard
            library.
        r   r    modestring)r   listzincorrect mode given: %slist_allr   posixstrictTpreserve_non_optsFz (allowed: "")r   )Nz--r   )rb   rc   f_codeco_namer   re   rA   osrJ   r   lenr   r   r   r   msgjoinreplace
startswithr(   AttributeErrorKeyErrorr   lstrip)r   arg_stropt_str	long_optsrI   rg   r   r   r   r   r   remainder_arg_strodictargsargvoptseorH   s                      r    parse_optionszMagics.parse_optionsn  s   < q!!(0!/33F2>>>>wwGvvfX&&(((7$>???66*Q''w7 233$''FF#6>># }}t99>> WeV44D#D'9==
dd    uuugggi'Wsxx	0A'B'B'BUW'W'WY  
  % %18##(9# ):(A(A!R(K(K(S(S2q) )% <<%% !""AA!""A%!HOOA&&&&% , , , %a|E!HHH % % % %$%3a#$a	% e}}8  &(//11xx~~Dys0   D$ $
E+.8E&&E+G00H#	H#"H#c                 j    ||                                  vrt          d|z             || j        |<   dS )z<Make an entry in the options_table for fn, with value optstrz%s is not a magic functionN)r   r   r   )r   fnoptstrs      r    default_optionzMagics.default_option  s>     T\\^^##.3444!'2r   rG   )r   r   r   rW   r   r   r5   r   r   r   r   r   r   r   r   s   @r    r   r     s         ( MFJE /  /  /  /  /  /D% % %
  6Y Y Yv( ( ( ( ( ( (r   r   c                        e Zd ZdZddZd ZdS )r   aZ  An alias to another magic function.

    An alias is determined by its magic name and magic kind. Lookup
    is done at call time, so if the underlying magic changes the alias
    will call the new function.

    Use the :meth:`MagicsManager.register_alias` method or the
    `%alias_magic` magic function to create and register a new alias.
    Nc                     || _         || _        || _        || _        t          | j                 | j        | _        d| j        z  | _        d| _        d S )NzAlias for `%s`.F)r   r<   r   r;   magic_escapespretty_targetrW   _in_call)r   r   r<   r;   r   s        r    r   zMagicAlias.__init__  sT    
$($'4T_'E'EtW(4+==r   c                 f   | j                             | j        | j                  }|t	          d| j        z            | j        rt	          d          d| _        	 | j        r4t          |          }| j        dz   |d         z   |d<   t          |          } ||i |d| _        S # d| _        w xY w)zCall the magic alias.NzMagic `%s` not found.zBInfinite recursion detected; magic aliases cannot call themselves.Tr   r   F)
r   
find_magicr<   r;   r   r   r   r   r   tuple)r   r   r   r   	args_lists        r    __call__zMagicAlias.__call__  s    Z""4?DODD:4t7IIJJJ = 	F E F F F	"  ( JJ	#036a@	!Y''2t&v&&!DMMEDM!!!!s   AB' '	B0rG   )r   r   r   rW   r   r   r   r   r    r   r     sA         	 	 	 	" " " " "r   r   ):rW   r   r   rb   r   r   traitlets.config.configurabler   r   r   r   r   inputtransformer2r	   r
   utils.ipstructr   utils.processr   
utils.textr   	traitletsr   r   r   r   loggingtypingtr6   r   __annotations__rB   r@   r   r   r%   r0   r2   r8   r=   rC   rU   rX   rk   rp   ru   rs   rv   
line_magic
cell_magicline_cell_magicregister_line_magicregister_cell_magicregister_line_cell_magicrx   r   r   r   r   r    <module>r     s!     
			 				 



 & & & & & & & & 6 6 6 6 6 6             4 4 4 4 4 4 4 4 # # # # # # % % % % % %       3 3 3 3 3 3 3 3 3 3 3 3           2B''' ' ' '*
)*555          
  &    4+ + +(2 2 2 :  @3 3 3l : F       "!&))
!!&))
&&{33 -,V44 ,,V44 11+>> UA UA UA UA UAL UA UA UAt( ( ( ( (\ ( ( (D'" '" '" '" '" '" '" '" '" '"r   