
    fZ                        d Z ddlmZ ddlZddlZddlmZ ddl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mZmZmZ dd
lmZmZmZ ddlmZ ddlmZ  G d de      Ze G d de             Z e G d de              Z!y)z(Implementation of basic magic functions.    )errorN)pformat)warn)import_item)magic_argumentspage)
UsageError)Magicsmagics_class
line_magicmagic_escapes)format_screendedentindent)skip_doctest)Structc                   2    e Zd ZddZd Zd Zd Zd Zd Zy)	MagicsDisplayNc                 (    |r|ng | _         || _        y N)ignoremagics_manager)selfr   r   s      T/var/www/cvtools/html/venv/lib/python3.12/site-packages/IPython/core/magics/basic.py__init__zMagicsDisplay.__init__   s     &fB,    c                 
   t         d   }t         d   }| j                  }|j                         }d|d|z   j                  t	        |d   j                         D cg c]  \  }}|| j                  vs| c}}            z   dd|d|z   j                  t	        |d   j                         D cg c]  \  }}|| j                  vs| c}}            z   d|j                         g}dj                  |      S c c}}w c c}}w )z'The main implementation of the %lsmagiclinecellzAvailable line magics:z   zAvailable cell magics:
)r   r   lsmagicjoinsorteditemsr   auto_status)r   mesccescmmanmagicsmvouts           r   _lsmagiczMagicsDisplay._lsmagic   s    V$V$""'tDy&&vF6N<P<P<R.mSQqWX`d`k`kWkq.m'noo'tDy&&vF6N<P<P<R.mSQqWX`d`k`kWkq.m'noo!# yy~ /n /ns   C91C9.C?C?c                 B    |j                  | j                                y r   )textr.   )r   pcycles      r   _repr_pretty_zMagicsDisplay._repr_pretty_(   s    	t}}r   c                 "    | j                         S r   )r.   r   s    r   __str__zMagicsDisplay.__str__+   s    }}r   c                    i }| j                   }|j                         }|j                         D ]J  \  }}i }|||<   |j                         D ]+  \  }}	 |j                  j                  j
                  }	|	||<   - L |S # t        $ r d}	Y w xY w)zturn magics dict into jsonable dict of the same structure

        replaces object instances with their class names as strings
        Other)r   r"   r%   __self__	__class____name__AttributeError)
r   
magic_dictr)   r*   keysubdictdnameobj	classnames
             r   	_jsonablezMagicsDisplay._jsonable.   s    
 
"""LLN 		$LCAJsO$]]_ $	c( # 6 6 ? ?I $$$		$ 	 & ( 'I(s    A>>BBc                 "    | j                         S r   )rD   r5   s    r   _repr_json_zMagicsDisplay._repr_json_B   s    ~~r   r   )	r;   
__module____qualname__r   r.   r3   r6   rD   rF    r   r   r   r      s     - ( r   r   c                   r   e Zd ZdZe ej
                          ej                  dddd       ej                  dddd	       ej                  d
d       ej                  dd       ej                  dddd      ed$d                                                        Zed$d       Z	d%dZ
ed$d       Zed$d       Zed$d       Zed$d       Zed$d       Zed        Zed$d       Zed$d       Zeed$d              Z ej
                          ej                  d ed!"      ed#                      Zy)&BasicMagicszMagics that provide central IPython functionality.

    These are various magics that don't fit into specific categories but that
    are all part of the base 'IPython experience'.z-lz--line
store_truezCreate a line magic alias.)actionhelpz-cz--cellzCreate a cell magic alias.rA   z Name of the magic to be created.)rN   targetz(Name of the existing line or cell magic.z-pz--paramsNz(Parameters passed to the magic function.)defaultrN   c           
         t        j                  | j                  |      }| j                  }| j                  j                  }dj                  t        j                               }|j                  j                  |      }|j                  j                  |      }|j                  }|rI|j                  d      r|j                  d      s"|j                  d      r|j                  d      r|dd }|j                  |d      }	|j                  |d      }
|j                  r|	t!        d	t        d   |d
      |j"                  r|
t!        dt        d   |d
      |j                  s>|j"                  s2|	s|
st!        d|z        t%        |	      |_        t%        |
      |_        |dnd|z   }|j                  r:|j'                  ||d|       t)        dt        d   |dt        d   ||d       |j"                  r;|j'                  ||d|       t)        dt        d   |dt        d   ||d       yy)aH  Create an alias for an existing line or cell magic.

        Examples
        --------
        ::

          In [1]: %alias_magic t timeit
          Created `%t` as an alias for `%timeit`.
          Created `%%t` as an alias for `%%timeit`.

          In [2]: %t -n1 pass
          1 loops, best of 3: 954 ns per loop

          In [3]: %%t -n1
             ...: pass
             ...:
          1 loops, best of 3: 954 ns per loop

          In [4]: %alias_magic --cell whereami pwd
          UsageError: Cell magic function `%%pwd` not found.
          In [5]: %alias_magic --line whereami pwd
          Created `%whereami` as an alias for `%pwd`.

          In [6]: %whereami
          Out[6]: u'/home/testuser'

          In [7]: %alias_magic h history "-p -l 30" --line
          Created `%h` as an alias for `%history -l 30`.
        r    "'   r   r   NzLine magic function `z` not found.zCell magic function `z+No line or cell magic with name `%s` found. z	Created `z` as an alias for `z`.)r   parse_argstringalias_magicshellr   r#   r   valuesrO   lstriprA   params
startswithendswith
find_magicr   r	   r   boolregister_aliasprint)r   r   argsrY   r)   escsrO   rA   r\   m_linem_cell
params_strs               r   rX   zBasicMagics.alias_magicM   s   l ..t/?/?F

zz((ww}++-.##D)yy%##C(V__S-A%%c*vs/CAb\F !!&&1!!&&199+F3V= > >99+F3V= > >
 yy& AFJ  VDIVDI!>RsV|
99fff=f%tf%vz; < 99fff=f%tf%vz; < r   c                 D    t        | j                  j                  g       S )z)List currently available magic functions.)r   )r   rY   r   )r   parameter_ss     r   r"   zBasicMagics.lsmagic   s     TZZ66rBBr   c                    | j                   j                  }|j                  |d      }|rd}nd}dj                  t	        |d   j                               D cg c]&  \  }}|t        d   |t        t        |            fz  ( c}}t	        |d   j                               D cg c]&  \  }}|t        d   |t        t        |            fz  ( c}}z         S c c}}w c c}}w )z'Return docstrings from magic functions.zNo documentation)missingz**%s%s**::

%s

z	%s%s:
%s
r    r   r   )	rY   r   lsmagic_docsr#   r$   r%   r   r   r   )r   briefrestr)   docsformat_stringfnamefndocs           r   _magic_docszBasicMagics._magic_docs   s    zz((  0B C2M)Mww "(V(:(:(<!=? mF3U$VE]35 5 ? "(V(:(:(<!=? mF3U$VE]35 5 ?	?
 	
??s   +C
(+C#c                 x   d}	 |j                         d   dd }|dk(  }|dk(  }| j                  ||      }|dk(  rt        | j	                  |             yt        |      }d|d	t        d
   z  t        | j                               g}t        j                  dj                  |             y# t        $ r Y w xY w)zmPrint information about the magic function system.

        Supported formats: -latex, -brief, -rest
        r    r   rT   Nrm   rn   latexa  
IPython's 'magic' functions
===========================

The magic function system provides a series of functions which allow you to
control the behavior of IPython itself, plus a lot of system-type
features. There are two kinds of magics, line-oriented and cell-oriented.

Line magics are prefixed with the % character and work much like OS
command-line calls: they get as an argument the rest of the line, where
arguments are passed without parentheses or quotes.  For example, this will
time the given statement::

        %timeit range(1000)

Cell magics are prefixed with a double %%, and they are functions that get as
an argument not only the rest of the line, but also the lines below it in a
separate argument.  These magics are called with two arguments: the rest of the
call line and the body of the cell, consisting of the lines below the first.
For example::

        %%timeit x = numpy.random.randn((100, 100))
        numpy.linalg.svd(x)

will time the execution of the numpy svd routine, running the assignment of x
as part of the setup phase, which is not timed.

In a line-oriented client (the terminal or Qt console IPython), starting a new
input with %% will automatically enter cell mode, and IPython will continue
reading input until a blank line is given.  In the notebook, simply type the
whole cell as one entity, but keep in mind that the %% escape can only be at
the very start of the cell.

NOTE: If you have 'automagic' enabled (via the command line option or with the
%automagic function), you don't need to type in the % explicitly for line
magics; cell magics always require an explicit '%%' escape.  By default,
IPython ships with automagic on, so you should only rarely need the % escape.

Example: typing '%cd mydir' (without the quotes) changes your working directory
to 'mydir', if it exists.

For a list of the available magic functions, use %lsmagic. For a description
of any of them, type %magic_name?, e.g. '%cd?'.

Currently the magic system has the following functions:z,Summary of magic functions (from %slsmagic):r   r!   )split
IndexErrorrs   rb   format_latexr   r   strr"   r   r#   )r   ri   moderm   rn   
magic_docsr-   s          r   magiczBasicMagics.magic   s     	$$&q)!"-D %%eT2
7?$##J/0&z2J,;Z 5f8MM
4<<>_0	b 			$))C.!}  		s   B- -	B98B9c                 :   | j                  |d      \  }}d|v }|xr |xs d}| j                  j                  |      }|j                  rC|rt	        |j
                        }nt        |j
                        }t        j                  |       yt        d|z         y)zPretty print the object and display it through a pager.

        %page [options] OBJECT

        If no object is given, use _ (last output).

        Options:

          -r: page str(object), don't pretty-print it.r_zObject `%s` not foundN)	parse_optionsrY   _ofindfoundry   rB   r   r   rb   )r   ri   optsrc   rawonameinfotxts           r   r   zBasicMagics.page  s     ''S9
dTk$zz  '::$((mdhh'IIcN)E12r   c                     | j                   j                  j                  d   }t        d|j                  z
        |_        t        dddg|j                            y)zToggle pretty printing on/off.
text/plainrT   zPretty printing has been turnedOFFONN)rY   display_formatter
formattersr`   pprintrb   )r   ri   ptformatters      r   r   zBasicMagics.pprint4  sS     jj22==lK!!k&8&8"89/Tl;--.	0r   c                    d }|j                         }|st        d      | j                  }	 ||_        |j	                          	 |j
                  j                  |       |j                  j                  |       |j                  r	 |j                  j                  |       y|j                  j                  d       y#   |d       Y xY w#   |d       Y `xY w#   |d       Y yxY w)	a2  Switch color scheme for prompts, info system and exception handlers.

        Currently implemented schemes: NoColor, Linux, LightBG.

        Color scheme names are not case-sensitive.

        Examples
        --------
        To get a plain black and white terminal::

          %colors nocolor
        c                 T    t        d| dt        j                         d   d       y )NError changing z color schemes.
rT      )
stacklevelr   sysexc_inforA   s    r   color_switch_errz,BasicMagics.colors.<locals>.color_switch_errJ  s"    q)+78:r   z8%colors: you must specify a color scheme. See '%colors?'rY   )scheme	exceptionzobject inspectorNoColorN)stripr	   rY   colorsrefresh_styleInteractiveTB
set_colorsSyntaxTB
color_info	inspectorset_active_scheme)r   ri   r   
new_schemerY   s        r   r   zBasicMagics.colors<  s    	:
 !&&(
JL L 

	&%EL!
	***J*?NN%%z%:
 511*= OO--i8#	&W%	*[)5 !34s#   C 8C C! 
C
C!
C-c                    d }| j                   }|j                         dk(  rd|j                  _        y|j                         dk(  rd|j                  _        y|j                         j	                         }	 |j                  j                  |       t        d|j                  j                         y#   |d	       Y yxY w)
aJ  Switch modes for the exception handlers.

        Valid modes: Plain, Context, Verbose, and Minimal.

        If called without arguments, acts as a toggle.

        When in verbose mode the value `--show` (and `--hide`)
        will respectively show (or hide) frames with ``__tracebackhide__ =
        True`` value set.
        c                 P    t        d| dt        j                         d          y )Nr   z exception modes.
rT   r   r   s    r   xmode_switch_errz+BasicMagics.xmode.<locals>.xmode_switch_errz  s    s||~a(* +r   z--showFNz--hideT)rz   zException reporting mode:user)rY   r   r   skip_hidden
capitalizeset_moderb   rz   )r   ri   r   rY   new_modes        r   xmodezBasicMagics.xmodem  s    	+ 

(*.3E+(*.2E+$$&113	%((h(7-e.A.A.F.FG	%V$s   9<B6 6
Cc                 d    ddl m} || j                  d      z   }t        j                  |       y)z Show a quick reference sheet r   )quick_referenceT)rm   N)IPython.core.usager   rs   r   )r   argr   qrs       r   quickrefzBasicMagics.quickref  s*     	7t//d/;;		"r   c                    | j                   }|j                  }| j                   j                  }|j                  d   }|j	                  dt                     }|j                  } |dd      } |d|j                          |d|j                  j                          |d|j                          |d|j                          |d	|j                          |d
|j                         |s6d|_        d|_	        d|_
        d|_        dg|_        |j                  d       ns|j                  |_        |j                  |_	        |j                   |_
        |j"                  |_        |j$                  |_        |j                  d|j&                  z          |j)                  |        t+        |       |_        ddg|j                     }	t-        d|	       y)a  Toggle doctest mode on and off.

        This mode is intended to make IPython behave as much as possible like a
        plain Python shell, from the perspective of how its prompts, exceptions
        and output look.  This makes it easy to copy and paste parts of a
        session into doctests.  It does so by:

        - Changing the prompts to the classic ``>>>`` ones.
        - Changing the exception reporting mode to 'Plain'.
        - Disabling pretty-printing of output.

        Note that IPython also supports the pasting of code snippets that have
        leading '>>>' and '...' prompts in them.  This means that you can paste
        doctests from files or docstrings (even if they have leading
        whitespace), and the code will execute correctly.  You can then use
        '%history -t' to see the translated history; this will give you the
        input after removal of all the leading prompts and whitespace, which
        can be pasted back into an editor.

        With these features, you can switch into this mode easily whenever you
        need to do testing and changes to doctests, without having to leave
        your existing IPython session.
        r   doctest_moderz   F	rc_pprintr   rc_separate_outrc_separate_out2rc_separate_inrc_active_typesr    zxmode Plainzxmode r   r   zDoctest mode is:N)rY   metar   r   
setdefaultr   r   r   rz   separate_outseparate_out2separate_inactive_typesr|   r   r   r   r   r   r   switch_doctest_moder`   rb   )
r   ri   rY   r   disp_formatterr   dstoresave_dstorerz   
mode_labels
             r   r   zBasicMagics.doctest_mode  s   6 

zz55$//= 9'' 6%(K 2 23GE//445%e&8&89&u':':;$U%6%67%n&A&AB !#E!#E"$E "'K+7.N'KK& !' 5 5E!'!7!7E"("9"9E!'!1!1K*0*@*@N'KK6<</0 	!!d(+ t8nD\&++.
 *-r   c                     | j                  |d      \  }}|dk(  rd}	 | j                  j                  |      S # t        $ r}t	        t        |             Y d}~yd}~ww xY w)ak  Enable or disable IPython GUI event loop integration.

        %gui [GUINAME]

        This magic replaces IPython's threaded shells that were activated
        using the (pylab/wthread/etc.) command line flags.  GUI toolkits
        can now be enabled at runtime and keyboard
        interrupts should work without any problems.  The following toolkits
        are supported:  wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::

            %gui wx      # enable wxPython event loop integration
            %gui qt      # enable PyQt/PySide event loop integration
                         # with the latest version available.
            %gui qt6     # enable PyQt6/PySide6 event loop integration
            %gui qt5     # enable PyQt5/PySide2 event loop integration
            %gui gtk     # enable PyGTK event loop integration
            %gui gtk3    # enable Gtk3 event loop integration
            %gui gtk4    # enable Gtk4 event loop integration
            %gui tk      # enable Tk event loop integration
            %gui osx     # enable Cocoa event loop integration
                         # (requires %matplotlib 1.1)
            %gui         # disable all event loop integration

        WARNING:  after any of these has been called you can simply create
        an application object, but DO NOT start the event loop yourself, as
        we have already handled that.
        r    N)r   rY   
enable_gui	Exceptionr   ry   )r   ri   r   r   es        r   guizBasicMagics.gui  s^    : &&{B7	c7$C	::((-- 	 #a&MM	s   9 	A AA c                 n    | j                   j                  j                  d   }||_        |j                  S )am  Set floating point precision for pretty printing.

        Can set either integer precision or a format string.

        If numpy has been imported and precision is an int,
        numpy display precision will also be set, via ``numpy.set_printoptions``.

        If no argument is given, defaults will be restored.

        Examples
        --------
        ::

            In [1]: from math import pi

            In [2]: %precision 3
            Out[2]: u'%.3f'

            In [3]: pi
            Out[3]: 3.142

            In [4]: %precision %i
            Out[4]: u'%i'

            In [5]: pi
            Out[5]: 3

            In [6]: %precision %e
            Out[6]: u'%e'

            In [7]: pi**10
            Out[7]: 9.364805e+04

            In [8]: %precision
            Out[8]: u'%r'

            In [9]: pi**10
            Out[9]: 93648.047476082982
        r   )rY   r   r   float_precisionfloat_format)r   sr   s      r   	precisionzBasicMagics.precision	  s3    T jj22==lK&'#'''r   filenamezNotebook name or filename)typerN   c                 *   t        j                  | j                  |      }t        j                  j                  |j                        }ddlm}m	} g }t        | j                  j                  j                               }t        |      dk  rt        d      |dd D ](  \  }}	}
|j!                  |j#                  |	|
             * |j%                  |      }t'        j(                  |d	d
      5 } |||d       ddd       y# 1 sw Y   yxY w)zExport and convert IPython notebooks.

        This function can export the current IPython history to a notebook file.
        For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
        r   )writev4rT   zHistory is empty, cannot exportNrU   )execution_countsource)cellswzutf-8)encoding   )version)r   rW   notebookospath
expanduserr   nbformatr   r   listrY   history_manager	get_rangelen
ValueErrorappendnew_code_cellnew_notebookioopen)r   r   rc   outfnamer   r   r   histsessionr   r   nbfs                r   r   zBasicMagics.notebook7  s     ..t}}a@77%%dmm4&DJJ..88:;t9a<>??04Sb	 	,G_fLL)) / *  	
 __5_)WWXsW5 	$"a#	$ 	$ 	$s   4D		D)r    )FF)r;   rG   rH   __doc__r   r   argumentr   rX   r"   rs   r|   r   r   r   r   r   r   r   r   ry   r   rI   r   r   rK   rK   F   s   6
 $_$$&_h|- _h|- _3 _; _j$; M< 					 ' .M<^ C C
( G" G"T 3 38 0 0 .9 .9` % %>   L. L.\ # #J *(  *(X %_$$&_( $ 	 '$r   rK   c                       e Zd Zed        Zy)AsyncMagicsc                    |j                         }ddd}|sGt        dj                  || j                  j                     | j                  j
                               y|j                         dv rd| j                  _        y|j                         dv rd	| j                  _        y|| j                  j                  v r;| j                  j                  |   \  | j                  _        | j                  _        y|| j                  j                  v r:| j                  j                  |   | j                  _        d	| j                  _        yt        |      }|| j                  _        d	| j                  _        y)
aV  
        Allow to change the status of the autoawait option.

        This allow you to set a specific asynchronous code runner.

        If no value is passed, print the currently used asynchronous integration
        and whether it is activated.

        It can take a number of value evaluated in the following order:

        - False/false/off deactivate autoawait integration
        - True/true/on activate autoawait integration using configured default
          loop
        - asyncio/curio/trio activate autoawait integration and use integration
          with said library.

        - `sync` turn on the pseudo-sync integration (mostly used for
          `IPython.embed()` which does not run IPython with a real eventloop and
          deactivate running asynchronous code. Turning on Asynchronous code with
          the pseudo sync loop is undefined behavior and may lead IPython to crash.

        If the passed parameter does not match any of the above and is a python
        identifier, get said object from user namespace and set it as the
        runner, and activate autoawait.

        If the object is a fully qualified object name, attempt to import it and
        set it as the runner, and activate autoawait.

        The exact behavior of autoawait is experimental and subject to change
        across version of IPython and Python.
        onoff)TFz.IPython autoawait is `{}`, and set to use `{}`N)falser   F)truer   T)
r   rb   formatrY   	autoawaitloop_runnerlowerloop_runner_mapuser_nsr   )r   ri   paramr@   runners        r   r   zAsyncMagics.autoawaitX  s0   D !!#&BII$**&&'

&&  ;;=,,#(DJJ ;;=N*#'DJJ DJJ...;?::;U;UV[;\8DJJ"DJJ$8DJJ&&&%)ZZ%7%7%>DJJ"#'DJJ U#!'

#

r   N)r;   rG   rH   r   r   rI   r   r   r   r   U  s     >$ >$r   r   )"r   loggingr   r   r   r   r   r   warningsr   traitlets.utils.importstringr   IPython.corer   r   IPython.core.errorr	   IPython.core.magicr
   r   r   r   IPython.utils.textr   r   r   IPython.testing.skipdoctestr   IPython.utils.ipstructr   objectr   rK   r   rI   r   r   <module>r     s    .  	 	  
  4 . ) N N < < 4 )/ F / d L$& L$ L$\ A$+ A$ A$r   