Format: application/x-python-code
⬇ Download File (21.2 KB)
   1  o
   2  
   3  ��h�p�@s�UdZddlZddlZddlZddlmZmZddlmZddlm	Z	ddl
   4  mZddlm
   5  Z
   6  mZd	d
   7  lmZd	dlmZd	dlmZdd
   8  lmZmZmZmZddlm
   9  Z
  10  ddlZeiid�Zejed<dZ dZ!ee
  11  ed�Z"Gdd�d�Z#dd�Z$dd�Z%dd�Z&dd�Z'dd�Z(dd�Z)d Z*d!d"�Z+d#d$�Z,d%Z-d&Z.d'd(�Z/d)d*�Z0e+d+�Z1e+d,�Z2e+d-�Z3e,d+�Z4e,d,�Z5e,d-�Z6Gd.d/�d/e�Z7Gd0d1�d1e�Z8Gd2d3�d3e9�Z:dS)4z&Magic functions for InteractiveShell.
  12  �N)�getopt�GetoptError)�Configurable�)�oinspect)�
  13  UsageError)�	ESC_MAGIC�
  14  ESC_MAGIC2�)�Struct)�	arg_split)�dedent)�Bool�Dict�Instance�observe)�error��line�cell�magics)rr�	line_cellc@seZdZdS)�BunchN)�__name__�
  15  __module__�__qualname__�rr�Hc:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/core/magic.pyr3srcCsddg|S)zAReturn an ON/OFF string for a 1/0 input. Simple utility function.ZOFF�ONr)�tagrrr�on_off6�r cCsT|dd�|dd�}}g}t�}|D]}||vrq|�|�|�|�q||S)z�Compress a directory history into a new one with at most 20 entries.
  16  
  17      Return a new list made from the first and last 10 elements of dhist after
  18      removal of duplicates.
  19      Ni����)�set�append�add)Zdh�head�tailZnewhead�done�hrrr�compress_dhist;s
  20  r)cCs
  21  d|_|S)zCDecorator to mark magic functions which need to local scope to run.T)�needs_local_scope)�funcrrrr*Nsr*cCs0d|_ttdtdd�|_itd<itd<|S)a�Class decorator for all subclasses of the main Magics class.
  22  
  23      Any class that subclasses Magics *must* also apply this decorator, to
  24      ensure that all the methods that have been decorated as line/cell magics
  25      get correctly registered in the class instance.  This is necessary because
  26      when method decorators run, the class does not exist yet, so they
  27      temporarily store their information into a module global.  Application of
  28      this class decorator copies that global data to the class instance and
  29      clears the global.
  30  
  31      Obviously, this mechanism is not thread-safe, which means that the
  32      *creation* of subclasses of Magic should only be done in a single-thread
  33      context.  Instantiation of the classes has no restrictions.  Given that
  34      these classes are typically created at IPython startup time and before user
  35      application code becomes active, in practice this should not pose any
  36      problems.
  37      Trrr)�
  38  registered�dictr)�clsrrr�magics_classWs�r/cCs4|dkr||d|<|d|<dS||||<dS)aSUtility function to store a function as a magic of a specific kind.
  39  
  40      Parameters
  41      ----------
  42      dct : dict
  43          A dictionary with 'line' and 'cell' subdicts.
  44      magic_kind : str
  45          Kind of magic to be stored.
  46      magic_name : str
  47          Key to store the magic as.
  48      func : function
  49          Callable object to store.
  50      rrrNr)�dct�
  51  magic_kind�
  52  magic_namer+rrr�record_magicqsr3cCs|tvrtdt|��dS)z�Ensure that the given magic_kind is valid.
  53  
  54      Check that the given magic_kind is one of the accepted spec types (stored
  55      in the global `magic_spec`), raise ValueError otherwise.
  56      �&magic_kind must be one of %s, %s givenN)�
  57  magic_spec�
  58  ValueError�magic_kinds�r1rrr�
  59  validate_type�s���r9a�Decorate the given {0} as {1} magic.
  60  
  61  The decorator can be used with or without arguments, as follows.
  62  
  63  i) without arguments: it will create a {1} magic named as the {0} being
  64  decorated::
  65  
  66      @deco
  67      def foo(...)
  68  
  69  will create a {1} magic named `foo`.
  70  
  71  ii) with one string argument: which will be used as the actual name of the
  72  resulting magic::
  73  
  74      @deco('bar')
  75      def foo(...)
  76  
  77  will create a {1} magic named `bar`.
  78  
  79  To register a class magic use ``Interactiveshell.register_magic(class or instance)``.
  80  cs&t���fdd�}t�d��|_|S)z8Decorator factory for methods in Magics subclasses.
  81      csTt|�r|}|j�|}tt����|St|t�r&|���fdd�}|}|Std��)Ncstt��|j�|S�N)r3rr�r+�a�kw)r1�namerr�mark�sz6_method_magic_marker.<locals>.magic_deco.<locals>.mark�4Decorator can only be called with string or function)�callablerr3r�
  82  isinstance�str�	TypeError)�argr+�retvalr?r8)r>r�
  83  magic_deco�s
  84  ��z(_method_magic_marker.<locals>.magic_deco�method)r9�_docstring_template�format�__doc__)r1rGrr8r�_method_magic_marker�srLcs6t���fdd�}t�d��}|td�7}||_|S)z0Decorator factory for standalone functions.
  85      cs�t�d�}dD]}t||��d�}|durnqtd��|��t|�r3|}|j���|���|}|St|t	�rF|����fdd�}|}|St
  86  d��)Nr)�f_locals�	f_globals�
  87  f_builtins�get_ipythonz<Decorator can only run in context where `get_ipython` existscs��|���|Sr:)�register_magic_functionr;)�ipr1r>rrr?�sz8_function_magic_marker.<locals>.magic_deco.<locals>.markr@)�sys�	_getframe�getattr�get�	NameErrorrArrQrBrCrD)rE�caller�nsrPr+rFr?r8)rRr>rrG�s(
  88  �
  89  ��z*_function_magic_marker.<locals>.magic_deco�functiona�
  90      Note: this decorator can only be used in a context where IPython is already
  91      active, so that the `get_ipython()` call succeeds.  You can therefore use
  92      it in your startup files loaded after IPython initializes, but *not* in the
  93      IPython configuration file itself, which is executed before IPython is
  94      fully up and running.  Any file located in the `startup` subdirectory of
  95      your configuration profile will be OK in this sense.
  96      )r9rIrJr
  97  rK)r1rGZdsrr8r�_function_magic_marker�s 	r[Z_ipython_magic_no_var_expandZ%_ipython_magic_output_can_be_silencedcC�t|td�|S)a�Mark a magic function as not needing variable expansion
  98  
  99      By default, IPython interprets `{a}` or `$a` in the line passed to magics
 100      as variables that should be interpolated from the interactive namespace
 101      before passing the line to the magic function.
 102      This is not always desirable, e.g. when the magic executes Python code
 103      (%timeit, %time, etc.).
 104      Decorate magics with `@no_var_expand` to opt-out of variable expansion.
 105  
 106      .. versionadded:: 7.3
 107      T)�setattr�MAGIC_NO_VAR_EXPAND_ATTR�Z
 108  magic_funcrrr�
 109  no_var_expand
 110  sr`cCr\)z�Mark a magic function so its output may be silenced.
 111  
 112      The output is silenced if the Python code used as a parameter of
 113      the magic ends in a semicolon, not counting a Python comment that can
 114      follow it.
 115      T)r]�MAGIC_OUTPUT_CAN_BE_SILENCEDr_rrr�output_can_be_silencedsrbrrrcs�eZdZdZe�Zedd�jdd�Ze�Ze	ddd�Z
 116  eddd�jdd�Ze
 117  d	�d
 118  d��Zdd
 119  gZe	ddd�Zd%�fdd�	Zdd�Zdd�Zd&dd�Zdedefdd�Zdd�Zd'd!d"�Zd'd#d$�Z�ZS)(�
 120  MagicsManagerzEObject that handles all magic-related functionality for IPython.
 121      aM
 122      Mapping from magic names to modules to load.
 123  
 124      This can be used in IPython/IPykernel configuration to declare lazy magics
 125      that will only be imported/registered on first use.
 126  
 127      For example::
 128  
 129          c.MagicsManager.lazy_magics = {
 130            "my_magic": "slow.to.import",
 131            "my_other_magic": "also.slow",
 132          }
 133  
 134      On first invocation of `%my_magic`, `%%my_magic`, `%%my_other_magic` or
 135      `%%my_other_magic`, the corresponding module will be loaded as an ipython
 136      extensions as if you had previously done `%load_ext ipython`.
 137  
 138      Magics names should be without percent(s) as magics can be both cell
 139      and line magics.
 140  
 141      Lazy loading happen relatively late in execution process, and
 142      complex extensions that manipulate Python/IPython internal state or global state
 143      might not support lazy loading.
 144      )�helpT)�configz1IPython.core.interactiveshell.InteractiveShellABC)�
 145  allow_nonezBAutomatically call line magics without requiring explicit % prefix�
 146  auto_magiccCs|d|j_dS)N�new)�shellZ	automagic)�selfZchangerrr�_auto_magic_changedcsz!MagicsManager._auto_magic_changedz5Automagic is OFF, % prefix IS needed for line magics.z8Automagic is ON, % prefix IS NOT needed for line magics.zIPython.core.magics.UserMagicsNcs>tt|�jd|||d�|��tiid�|_||j|jj<dS)N)rire�user_magicsrr)�superrc�__init__r-r�registry�	__class__r)rjrirerlZtraits�rprrrnms��zMagicsManager.__init__cCs|j|jS)z0Return descriptive string with automagic status.)�_auto_statusrg�rjrrr�auto_statusvr!zMagicsManager.auto_statuscCs|jS)z�Return a dict of currently available magic functions.
 147  
 148          The return dict has the keys 'line' and 'cell', corresponding to the
 149          two types of magics we support.  Each value is a list of names.
 150          )rrsrrr�lsmagiczszMagicsManager.lsmagicF�cCsri}|jD]1}i}|j|��D]!\}}|jr-|r%|j�dd�d||<q|j��||<q|||<q|||<q|S)a�Return dict of documentation of magic functions.
 151  
 152          The return dict has the keys 'line' and 'cell', corresponding to the
 153          two types of magics we support. Each value is a dict keyed by magic
 154          name whose value is the function docstring. If a docstring is
 155          unavailable, the value of `missing` is used instead.
 156  
 157          If brief is True, only the first line of each docstring will be returned.
 158          �
 159  rr)r�itemsrK�split�rstrip)rjZbrief�missing�docsZm_typeZm_docsZm_nameZm_funcrrr�lsmagic_docs�s
 160  
 161  
 162  
 163  zMagicsManager.lsmagic_docsr>�fully_qualified_namecCs||j|<dS)a�
 164          Lazily register a magic via an extension.
 165  
 166  
 167          Parameters
 168          ----------
 169          name : str
 170              Name of the magic you wish to register.
 171          fully_qualified_name :
 172              Fully qualified name of the module/submodule that should be loaded
 173              as an extensions when the magic is first called.
 174              It is assumed that loading this extensions will register the given
 175              magic.
 176          N)�lazy_magics)rjr>r~rrr�
 177  register_lazy�szMagicsManager.register_lazycGs`|D]+}|jstd��t|t�r||jd�}||j|jj<tD]
 178  }|j	|�
 179  |j	|�qqdS)aJRegister one or more instances of Magics.
 180  
 181          Take one or more classes or instances of classes that subclass the main
 182          `core.Magic` class, and register them with IPython to use the magic
 183          functions they provide.  The registration process will then ensure that
 184          any methods that have decorated to provide line and/or cell magics will
 185          be recognized with the `%x`/`%%x` syntax as a line/cell magic
 186          respectively.
 187  
 188          If classes are given, they will be instantiated with the default
 189          constructor.  If your classes need a custom constructor, you should
 190          instanitate them first and pass the instance.
 191  
 192          The provided arguments can be an arbitrary mix of classes and instances.
 193  
 194          Parameters
 195          ----------
 196          *magic_objects : one or more classes or instances
 197          zOClass of magics %r was constructed without the @register_magics class decorator)riN)r,r6rB�typerirorprr7r�update)rjZ
 198  magic_objects�m�mtyperrr�register�s
 199  ��zMagicsManager.registerrcCs<t|�|dur|jn|}t|j||�t|j|||�dS)a�Expose a standalone function as magic function for IPython.
 200  
 201          This will create an IPython magic (line, cell or both) from a
 202          standalone function.  The functions should have the following
 203          signatures:
 204  
 205          * For line magics: `def f(line)`
 206          * For cell magics: `def f(line, cell)`
 207          * For a function that does both: `def f(line, cell=None)`
 208  
 209          In the latter case, the function will be called with `cell==None` when
 210          invoked as `%f`, and with cell as a string when invoked as `%%f`.
 211  
 212          Parameters
 213          ----------
 214          func : callable
 215              Function to be registered as a magic.
 216          magic_kind : str
 217              Kind of magic, one of 'line', 'cell' or 'line_cell'
 218          magic_name : optional str
 219              If given, the name the magic will have in the IPython namespace.  By
 220              default, the name of the function itself is used.
 221          N)r9rr]rlr3r)rjr+r1r2rrr�register_function�szMagicsManager.register_functioncCsH|tvrtdt|��t|j|||�}t|j||�t|j|||�dS)a3Register an alias to a magic function.
 222  
 223          The alias is an instance of :class:`MagicAlias`, which holds the
 224          name and kind of the magic it should call. Binding is done at
 225          call time, so if the underlying magic function is changed the alias
 226          will call the new function.
 227  
 228          Parameters
 229          ----------
 230          alias_name : str
 231              The name of the magic to be registered.
 232          magic_name : str
 233              The name of an existing magic.
 234          magic_kind : str
 235              Kind of magic, one of 'line' or 'cell'
 236          r4N)r7r6�
 237  MagicAliasrir]rlr3r)rjZ
 238  alias_namer2r1�magic_params�aliasrrr�register_alias�s��zMagicsManager.register_alias)NNN)Frv)rN)rrrrKrrrrrorrirrgrrkrrrlrnrtrur}rCr�r�r�r��
 239  __classcell__rrrqrrc5s<����
 240  �	
 241  
 242  $ rccsReZdZdZdZdZdZdZd�fdd�	Zdd�Z	dd	�Z
 243  d
 244  d�Zdd
 245  �Z�Z
 246  S)�Magicsa�Base class for implementing magic functions.
 247  
 248      Shell functions which can be reached as %function_name. All magic
 249      functions should accept a string, which they can parse for their own
 250      needs. This can make some functions easier to type, eg `%cd ../`
 251      vs. `%cd("../")`
 252  
 253      Classes providing magic functions need to subclass this class, and they
 254      MUST:
 255  
 256      - Use the method decorators `@line_magic` and `@cell_magic` to decorate
 257        individual methods as magic functions, AND
 258  
 259      - Use the class decorator `@magics_class` to ensure that the magic
 260        methods are properly registered at the instance level upon instance
 261        initialization.
 262  
 263      See :mod:`magic_functions` for examples of actual implementation classes.
 264      NFc	s�|jjstd��|dur"t|d�r|j�|�t|d�r"|�d|�||_i|_|j	}i|_	t
 265  D]'}i}|j	|<||}|��D]\}}t|t
 266  �rRt||�||<qA|||<qAq0tt|�jdi|��dS)NzMMagics subclass without registration - did you forget to apply @magics_class?�
 267  configurablesre�parentr)rpr,r6�hasattrr�r#�
 268  setdefaultri�
 269  options_tablerr7rxrBrCrUrmr�rn)	rjri�kwargsZclass_magicsr��tabZcls_tabr2�	meth_namerqrrrn,s(
 270  
 271  
 272  
 273  �	zMagics.__init__cCstd�tt�|��dS)z2Print docstring if incorrect arguments were passedzError in arguments:N)�printr�getdoc)rjr+rrr�arg_errNszMagics.arg_errcCs�t�dtj�}t�dttj�}t�dttj�}t�dtj�}t�d�}|�d|�}|�d|�}|�d|�}|�d	|�}|�d
 274  |�}|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)rjZstrngZ	escape_reZcmd_name_reZcmd_reZpar_reZ
 275  newline_rerrr�format_latexSs"
 276  �
 277  �
 278  �zMagics.format_latexc
 279  Os�t�d�jj}d|j�|d�|f}|�dd�}|dvr"td|��|�dd	�}|�d
 280  tjd
 281  k�}|�dd�}	|�d
 282  d�}
 283  |}i}|�	�}
 284  t
 285  |
 286  �dkr�t|||	�}z
 287  t|||�\}}
 288  Wnt
 289  yu}ztd|j|d�|�f�|�d}~ww|D]V\}}|dkr�|
 290  r�|�|dd��|dd�}|�d�r�|dd�}n|dd�}z	||�|�Wqxty�|||g||<Yqxty�|r�|g||<n|||<Yqxwt|�}|dkr�|
 291  r�|��}
 292  ||
 293  fSd�|
 294  �}
 295  ||
 296  fS)alParse options passed to an argument string.
 297  
 298          The interface is similar to that of :func:`getopt.getopt`, but it
 299          returns a :class:`~IPython.utils.struct.Struct` with the options as keys
 300          and the stripped argument string still as a string.
 301  
 302          arg_str is quoted as a true sys.argv vector by using shlex.split.
 303          This allows us to easily expand variables, glob files, quote
 304          arguments, etc.
 305  
 306          Parameters
 307          ----------
 308          arg_str : str
 309              The arguments to parse.
 310          opt_str : str
 311              The options specification.
 312          mode : str, default 'string'
 313              If given as 'list', the argument string is returned as a list (split
 314              on whitespace) instead of a string.
 315          list_all : bool, default False
 316              Put all option values in lists. Normally only options
 317              appearing more than once are put in a list.
 318          posix : bool, default True
 319              Whether to split the input line in POSIX mode or not, as per the
 320              conventions outlined in the :mod:`shlex` module from the standard
 321              library.
 322          rz%s %srv�mode�string)r��listzincorrect mode given: %s�list_allr�posix�strictT�preserve_non_optsFz%s ( allowed: "%s" %s)� Nz--r
 323  )rSrT�f_code�co_namer�rVr6�osr>ry�lenrrrr�msg�join�replace�
 324  startswithr#�AttributeError�KeyErrorr�lstrip)rjZarg_str�opt_str�	long_optsr=rXr�r�r�r�r�Zremainder_arg_strZodict�args�argv�opts�e�or<rrr�
 325  parse_optionsnsb�����
 326  ��
 327  �zMagics.parse_optionscCs&||��vrtd|�||j|<dS)z<Make an entry in the options_table for fn, with value optstrz%s is not a magic functionN)rurr�)rj�fnZoptstrrrr�default_option�szMagics.default_optionr:)rrrrKr�rr,rirnr�r�r�r�r�rrrqrr�s"Zr�c@s"eZdZdZddd�Zdd�ZdS)r�aZAn alias to another magic function.
 328  
 329      An alias is determined by its magic name and magic kind. Lookup
 330      is done at call time, so if the underlying magic changes the alias
 331      will call the new function.
 332  
 333      Use the :meth:`MagicsManager.register_alias` method or the
 334      `%alias_magic` magic function to create and register a new alias.
 335      NcCsD||_||_||_||_dt|j|jf|_d|j|_d|_dS)Nz%s%szAlias for `%s`.F)rir2r�r1�
 336  magic_escapes�
 337  pretty_targetrK�_in_call)rjrir2r1r�rrrrn�s
 338  zMagicAlias.__init__cOs�|j�|j|j�}|durtd|j��|jrtd��d|_z!|jr5t|�}|jd|d|d<t	|�}||i|��Wd|_Sd|_w)zCall the magic alias.NzMagic `%s` not found.zBInfinite recursion detected; magic aliases cannot call themselves.Tr�rF)
 339  riZ
 340  find_magicr2r1rr�r�r�r��tuple)rjr�r�r�Z	args_listrrr�__call__�szMagicAlias.__call__r:)rrrrKrnr�rrrrr��s
 341  	r�);rKr�r�rSrrZtraitlets.config.configurablerrvrrrZinputtransformer2rr	Zutils.ipstructrZ
 342  utils.processrZ
 343  utils.textr
 344  Z	traitletsrrrr�logging�typing�tr-r�__annotations__r7r5r�rr r)r*r/r3r9rIrLr[r^rar`rbZ
 345  line_magicZ
 346  cell_magicZline_cell_magicZregister_line_magicZregister_cell_magicZregister_line_cell_magicrcr��objectr�rrrr�<module>sZ	� 6
 347  [B