
    fm                        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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mZmZ ddlmZ dd	lmZmZ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$ ddl%m&Z& ddl'm(Z( ddl)m*Z*  G d de+      Z, ejZ                  d      Z. ejZ                  dej^                        Z0d Z1d Z2d Z3 G d de4      Z5e G d de             Z6y)z3Implementation of code management magic functions.
    N)chain)Requesturlopen)	urlencode)Path)TryNextStdinNotImplementedError
UsageError)Macro)Magicsmagics_class
line_magic)	find_filefind_source_lines)version)skip_doctest)preserve_keys)get_py_filename)warn)error)get_text_listc                       e Zd Zy)MacroToEditN__name__
__module____qualname__     S/var/www/cvtools/html/venv/lib/python3.12/site-packages/IPython/core/magics/code.pyr   r   -       r   r   z!<ipython\-input\-(\d+)-[a-z\d]+>$z3
(?P<start>\d+)?
((?P<sep>[\-:])
 (?P<end>\d+)?)?
$c              #     K   | j                         D ]  }t        j                  |      }|s|j                  d      }|j                  d      }|j                  d      }|dk(  r"|rt	        |      dz
  nd}|rt	        |      nd}nC|dk(  r%|rt	        |      dz
  nd}|rt	        |      dz
  nd}nt	        |      }t	        |      dz
  }||f  yw)zTurn a string of range for %%load into 2-tuples of (start, stop)
    ready to use as a slice of the content split by lines.

    Examples
    --------
    list(extract_input_ranges("5-10 2"))
    [(4, 10), (1, 2)]
    sepstartend-   N:)splitrange_rematchgroupint)
ranges_str	range_strrmatchr#   r$   r%   s         r    extract_code_rangesr1   9   s       %%' 		*ll5!W%ll5!#:&+CJNE!#c(tCCZ&+CJNE"%#c(Q,4Ce*CJNEcl#s   CCc                 F   |j                  d      }t        j                  |       }|j                  D cg c]  }t	        |dd      |j
                  f }}| j                  d      } i }t        |       }t        |      D ]H  \  }}| |dz
     j                         s|dz  }| |dz
     j                         s|r
|dz
  |f||<   |dz
  }J g }	g }
|D ]F  }||v r/||   \  }}|	j                  dj                  | ||       dz          6|
j                  |       H |	|
fS c c}w )a  
    Return a tuple  (blocks, not_found)
    where ``blocks`` is a list of code fragments
    for each symbol parsed from code, and ``not_found`` are
    symbols not found in the code.

    For example::

        In [1]: code = '''a = 10
           ...: def b(): return 42
           ...: class A: pass'''

        In [2]: extract_symbols(code, 'A,b,z')
        Out[2]: (['class A: pass\n', 'def b(): return 42\n'], ['z'])
    ,nameN
r'   )r)   astparsebodygetattrlinenolenreversedstripappendjoin)codesymbolspy_codesmarkssymbols_linesr%   r4   r$   blocks	not_foundsymbols               r    extract_symbolsrI   V   sC     mmC G iioG;B<<Haga&1HEH::dDM
 d)C esQw-%%'1HC sQw-%%'#(19c"2M$ai FI %]"&v.JE3MM$))DsO4t;<V$% 9; Is    Dc              #   D  K   t        j                  d      }t        |       }t        |      }|j	                  |      }|rO|j                         }|t        |      d  |D ])  }|j                  |      r|t        |      d  %|  n n| |D ]  }|  yw)z}For %load, strip indent from lines until finding an unindented line.

    https://github.com/ipython/ipython/issues/9775
    z\s+N)recompileiternextr+   r,   r;   
startswith)lines	indent_reit
first_lineindent_matchindentlines          r    strip_initial_indentrW      s     
 

6"I	eBbJ??:.L##%V&& 	Dv&3v;<(( 
	   
s   BB c                       e Zd ZdZd Zy)InteractivelyDefinedz:Exception for interactively defined variable in magic_editc                     || _         y N)index)selfr\   s     r    __init__zInteractivelyDefined.__init__   s	    
r   N)r   r   r   __doc__r^   r   r   r    rY   rY      s
    Dr   rY   c                        e Zd ZdZ fdZedd       Zedd       Zed        Zed        Z	e
d        Zd	 Zeedddgfd
              Z xZS )
CodeMagicszBMagics related to code management (loading, saving, editing, ...).c                 J    t               | _        t        t        |   |i | y r[   )set_knowntempssuperra   r^   )r]   argskwargs	__class__s      r    r^   zCodeMagics.__init__   s!    5j$($9&9r    c                    | j                  |dd      \  }}|st        d      d|v }d|v }d|v }|rdnd}|rd	nd
}|d   dj                  |dd       }
}	|	j                  d      s|	|z  }	t        j
                  j                  |	      }	t        j
                  j                  |	      }|r3|s1|s/	 | j                  j                  d|	z  d      }|st        d       y	 | j                  j                  |
|      }t!        j"                  |	|d      5 }|r|s|j%                  d       |j%                  |       |j                  d      s|j%                  d       ddd       t        d|	z         t        |       y# t        $ r t        d|	d|d       Y yw xY w# t        t        f$ r"}t        |j                  d          Y d}~yd}~ww xY w# 1 sw Y   xxY w)a  Save a set of lines or a macro to a given filename.

        Usage:\
          %save [options] filename [history]

        Options:

          -r: use 'raw' input.  By default, the 'processed' history is used,
          so that magics are loaded in their transformed version to valid
          Python.  If this option is given, the raw input as typed as the
          command line is used instead.
          
          -f: force overwrite.  If file exists, %save will prompt for overwrite
          unless -f is given.

          -a: append to the file instead of overwriting it.

        The history argument uses the same syntax as %history for input ranges,
        then saves the lines to the filename you specify.

        If no ranges are specified, saves history of the current session up to
        this point.

        It adds a '.py' extension to the file if you don't do so yourself, and
        it asks for confirmation before overwriting existing files.

        If `-r` option is used, the default extension is `.ipy`.
        fralist)modezMissing filename.rfaw.ipy.pyr    r'   N)rs   rr   z%File `%s` exists. Overwrite (y/[N])? ndefaultzFile `z` exists. Use `%save -f z` to force overwriteOperation cancelled.utf-8encodingz# coding: utf-8
r5   z1The following commands were written to file `%s`:)parse_optionsr
   r?   endswithospath
expanduserisfileshell
ask_yes_nor	   printfind_user_code	TypeError
ValueErrorrf   ioopenwrite)r]   parameter_soptsrf   rawforcer>   rm   extfnamecodefromfile_exists	overwritecmdsero   s                   r    savezCodeMagics.save   s   > &&{5f&E	T011Tkts#fq'388DH#5x~~n-SLE""5)ggnnU+uV JJ112Y\a2akn1o	 ,-	::,,Xc:D WWUD73 	qf+,GGDM==&	 	AEIJd' , SXZefg :& 	!&&)		 	s7   1 E?  F  A	G?FF G/GGGc                    | j                  |d      \  }}	 | j                  j                  |      }d}	 t        |j                  dd            }|dk  s|dkD  rt        d       yt        |j                  d	d
      d||d      j                  d      }t        dddj                  t              i      }t        ||      }	|	j                   j                  d      S # t        t        f$ r"}t        |j                  d          Y d}~yd}~ww xY w# t        $ r0}t        |j                  d   j                                Y d}~yd}~ww xY w)a+  Upload code to dpaste.com, returning the URL.

        Usage:\
          %pastebin [-d "Custom description"][-e 24] 1-7

        The argument can be an input history range, a filename, or the name of a
        string or macro.

        If no arguments are given, uploads the history of this session up to
        this point.

        Options:

          -d: Pass a custom description. The default will say
              "Pasted from IPython".
          -e: Pass number of days for the link to be expired.
              The default will be 7 days.
        zd:e:r   N   r   r'   im  z*Expiry days should be in range of 1 to 365dzPasted from IPythonpython)titlesyntaxcontentexpiry_daysry   zhttps://dpaste.com/api/v2/z
User-AgentzIPython v{})headersLocation)r|   r   r   r   r   r   rf   r-   get
capitalizer   encoder   formatr   r   r   )
r]   r   r   rf   r@   r   r   	post_datarequestresponses
             r    pastebinzCodeMagics.pastebin   sC   ( ''V<
d	::,,T2D
 	dhhsA./K ?kC/>?#'<="*	
 &/ 	 (!=#7#7#@A
 7I.##J//9 I& 	!&&)	  	!&&)&&()	s.   C D D-D

D	E&EEc                 &    | j                  |       y)zAlias of `%load`

        `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
        extension. So it has been renamed simply into %load. You can look at
        `%load`'s docstring for more info.
        N)load)r]   arg_ss     r    loadpyzCodeMagics.loadpy1  s     			%r   c                    | j                  |d      \  }}d|v }| j                  j                  ||      }d|v rk	 t        ||d         \  }}t        |      dk(  rt        d|d	   z         n't        |      dkD  rt        d
t        |d      z         dj                  |      }d|v rv|d   j                  dd      }|j                  d      }	t        |      }
|
D cg c]  }|	t        |     }}dj                  t        t        j                   |                  }t        |      }|dkD  r5d|vr1	 | j                  j#                  d|z  d      }|du rt'        d       ydj)                  |      |z   }| j                  j+                  |d       y# t        $ r t        d       Y yw xY wc c}w # t$        $ r d}Y nw xY w)a  Load code into the current frontend.

        Usage:\
          %load [options] source

          where source can be a filename, URL, input history range, macro, or
          element in the user namespace

        If no arguments are given, loads the history of this session up to this
        point.

        Options:

          -r <lines>: Specify lines or ranges of lines to load from the source.
          Ranges could be specified as x-y (x..y) or in python-style x:y 
          (x..(y-1)). Both limits x and y can be left blank (meaning the 
          beginning and end of the file, respectively).

          -s <symbols>: Specify function or classes to load from python source. 

          -y : Don't ask confirmation for loading source above 200 000 characters.

          -n : Include the user's namespace when searching for source code.

        This magic command can either take a local filename, a URL, an history
        range (see %history) or a macro as argument, it will prompt for
        confirmation before loading source with more than 200 000 characters, unless
        -y flag is passed or if the frontend does not support raw_input::

        %load
        %load myscript.py
        %load 7-27
        %load myMacro
        %load http://www.example.com/myscript.py
        %load -r 5-10 myscript.py
        %load -r 10-20,30,40: foo.py
        %load -s MyClass,wonder_function myscript.py
        %load -n MyClass
        %load -n my_module.wonder_function
        zyns:r:ru   )	search_nsrC   z.Unable to parse the input as valid Python codeNr'   zThe symbol `%s` was not foundr   zThe symbols %s were not found`)wrap_item_withr5   rn   r3   rt   i@ yzSThe text you're trying to load seems pretty big (%d characters). Continue (y/[N]) ?rv   TFrx   z# %load {}
)replace)r|   r   r   rI   SyntaxErrorr   r;   r   r   r?   r   r)   r1   slicerW   r   from_iterabler   r	   r   r   set_next_input)r]   r   r   rf   r   contentsrF   rG   rangesrP   slicesslclanss                 r    r   zCodeMagics.load;  s   T &&uX6	T4K	::,,TY,G$;$3Hd3i$H!	 9~"4y|CDY!#4}YTW8Y Y  yy(H$;#Y&&sC0FNN4(E(0F6<=seSk*=H=yy!5e6I6I(6S!TUHM v:#T/jj++ .79:.;EH , K e|,-!((/(:

!!(D!9O  FG$ > , s)   F F15 F6 F.-F.6GGc                    d }d|v }d|v } G d dt               }|j                  dd      }|rd|d	   z  }|| j                  vr|d
   }d}	d}
 ||      }|rd}	n@|r>| j                  ||      }
|
s*	 t	        || j                        }
t        |
t              s|	 |	r| j9                  |
      }t;        d|       	 | j<                  j>                  |d	<   |s||d
<   |||	fS # t        t        f$ r  ||      }|t        d|z         Y yd}	Y r|$ rp}t        |
t              rt        |
      |t        |
      }|rd|j                         v r~t        j                  |
      rit!        |
      D cg c]  }t#        |
|       nc c}w }}|D ]<  }t        j$                  |      st        |      }|s'd|j                         vs:|}
 n t&        j)                  t*        j,                  j/                  |            }|r&t1        t3        |j5                         d	               |d
}| ||      }d
}|t        d|d|d       r,|t7        |
      }| ||      }|t        d|
z         Y d}~yd}	Y d}~d}~ww xY w#  Y xY w)z7Utility method used by magic_edit to find what to edit.c                 n    	 t        |       }|S # t        $ r | j                  d      r| }Y |S d}Y |S w xY w)z#Make a filename from the given argsrs   N)r   IOErrorr}   )argfilenames     r    make_filenamez3CodeMagics._find_edit_target.<locals>.make_filename  sO    $*3/ O  $ <<&"H O  $HO$s    444prn   c                       e Zd Zy)2CodeMagics._find_edit_target.<locals>.DataIsObjectNr   r   r   r    DataIsObjectr     r!   r   r   ru   Nz_%sr   r'   Tri   FzBArgument given (%s) can't be found as a variable or as a filename.)NNN
fakemodulezCould not find file where `z$` is defined.
Opening a file named `r   z8The file where `%s` was defined cannot be read or found.z)IPython will make a temporary file named:) 	Exceptionr   user_nsextract_input_lineseval
isinstancestr	NameErrorr   r   r   r   r   lowerinspectisclassdirr9   ismethodipython_input_patr+   r~   r   basenamerY   r-   groupsr   
mktempfiler   displayhookprompt_count)r   rf   r   	last_callr   	opts_prevopts_rawr   r:   use_tempdatar   r   anameattrsattrmdatafiles                     r    _find_edit_targetzCodeMagics._find_edit_target  s   	 4K	$; 	,9+ #d#9Q<'D5==( |  !&H,,T8<DB%
  emm4D%dC0** 1| ''-H=hG	 ,,99IaL#	!
 ))S "+. %,T2H' 1378 91$H# 0%!$.)$/Q6  )H'8>>+;;#OOD1 HK4y$QeWT5%9$Q$QE$Q(- 	*'.'7'7'=$,+4T?#+".hnn6F"F ,0D$)	* .33BGG4D4DX4NO"6s188:a=7I"JPQQ#$'#0#6#$#/ <@("L M  !>%6t%<F!>'4T':H'/ $ &@BF&G !H'9$Ha0%x	sP   2(C  ; J  'J	JJAI=/F0I=3I=B*I=5I==JJ
c                    | j                   j                  |j                        }| j                   j                  j	                  |       t        |      j                  d      }t        |      | j                   j                  |<   y)z,open an editor with the macro data in a filery   rz   N)	r   r   valuehookseditorr   	read_textr   r   )r]   mnamemacror   mvalues        r    _edit_macrozCodeMagics._edit_macro  sc    ::((5

) h))7);$)&M

5!r   c                 P   | j                  |d      \  }}	 | j                  | j                  |||      \  }}}|y|r| j                  j                  |       n|| j                  v rd}t        dd       t        j                  j                          t        |      }		 t        |	j!                               x}
}d|
v rd	|
z  }
| j                  j"                  j%                  |
|       |j+                         dk(  r)|	j-                  d      | j                  j.                  d<   d|v rt                nt        d       t1        | j                  j.                  d      5  |s|| j                  j.                  d<   d|v r0|	j-                  d      }| j                  j3                  |d       nE| j                  j5                  || j                  j.                  | j                  j.                         ddd       |r	 |	j-                  d      S y# t        $ r)}| j	                  ||j
                  d          Y d}~yd}~wt        $ rZ}t        d|j                  z         t        |j                        }| j                  | j                  |||      \  }}}Y d}~id}~ww xY w# t&        $ r t)        d
       Y yw xY w# 1 sw Y   xY w# t6        $ rL}t        |j8                        |	k(  rt)        d       Y d}~y| j                  j;                          Y d}~yd}~ww xY w)a  Bring up an editor and execute the resulting code.

        Usage:
          %edit [options] [args]

        %edit runs IPython's editor hook. The default version of this hook is
        set to call the editor specified by your $EDITOR environment variable.
        If this isn't found, it will default to vi under Linux/Unix and to
        notepad under Windows. See the end of this docstring for how to change
        the editor hook.

        You can also set the value of this editor via the
        ``TerminalInteractiveShell.editor`` option in your configuration file.
        This is useful if you wish to use a different editor from your typical
        default with IPython (and for Windows users who typically don't set
        environment variables).

        This command allows you to conveniently edit multi-line code right in
        your IPython session.

        If called without arguments, %edit opens up an empty editor with a
        temporary file and will execute the contents of this file when you
        close it (don't forget to save it!).


        Options:

        -n <number>: open the editor at a specified line number.  By default,
        the IPython editor hook uses the unix syntax 'editor +N filename', but
        you can configure this by providing your own modified hook if your
        favorite editor supports line-number specifications with a different
        syntax.

        -p: this will call the editor with the same data as the previous time
        it was used, regardless of how long ago (in your current session) it
        was.

        -r: use 'raw' input.  This option only applies to input taken from the
        user's history.  By default, the 'processed' history is used, so that
        magics are loaded in their transformed version to valid Python.  If
        this option is given, the raw input as typed as the command line is
        used instead.  When you exit the editor, it will be executed by
        IPython's own processor.

        -x: do not execute the edited code immediately upon exit. This is
        mainly useful if you are editing programs which need to be called with
        command line arguments, which you can then do using %run.


        Arguments:

        If arguments are given, the following possibilities exist:

        - If the argument is a filename, IPython will load that into the
          editor. It will execute its contents with execfile() when you exit,
          loading any code in the file into your interactive namespace.

        - The arguments are ranges of input history,  e.g. "7 ~1/4-6".
          The syntax is the same as in the %history magic.

        - If the argument is a string variable, its contents are loaded
          into the editor. You can thus edit any string which contains
          python code (including the result of previous edits).

        - If the argument is the name of an object (other than a string),
          IPython will try to locate the file where it was defined and open the
          editor at the point where it is defined. You can use `%edit function`
          to load an editor exactly at the point where 'function' is defined,
          edit it and have the file be executed automatically.

        - If the object is a macro (see %macro for details), this opens up your
          specified editor with a temporary file containing the macro's data.
          Upon exit, the macro is reloaded with the contents of the file.

        Note: opening at an exact line is only supported under Unix, and some
        editors (like kedit and gedit up to Gnome 2.8) do not understand the
        '+NUMBER' parameter necessary for this feature. Good editors like
        (X)Emacs, vi, jed, pico and joe all do.

        After executing your code, %edit will return as output the code you
        typed in the editor (except when it was an existing file). This way
        you can reload the code in further invocations of %edit as a variable,
        via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
        the output.

        Note that %edit is also available through the alias %ed.

        This is an example of creating a simple function inside the editor and
        then modifying it. First, start up the editor::

          In [1]: edit
          Editing... done. Executing edited code...
          Out[1]: 'def foo():\n    print "foo() was defined in an editing
          session"\n'

        We can then call the function foo()::

          In [2]: foo()
          foo() was defined in an editing session

        Now we edit foo.  IPython automatically loads the editor with the
        (temporary) file where foo() was previously defined::

          In [3]: edit foo
          Editing... done. Executing edited code...

        And if we call foo() again we get the modified version::

          In [4]: foo()
          foo() has now been changed!

        Here is an example of how to edit a code snippet successive
        times. First we call the editor::

          In [5]: edit
          Editing... done. Executing edited code...
          hello
          Out[5]: "print 'hello'\n"

        Now we call it again with the previous output (stored in _)::

          In [6]: edit _
          Editing... done. Executing edited code...
          hello world
          Out[6]: "print 'hello world'\n"

        Now we call it with the output #8 (stored in _8, also as Out[8])::

          In [7]: edit _8
          Editing... done. Executing edited code...
          hello again
          Out[7]: "print 'hello again'\n"


        Changing the default editor hook:

        If you wish to write your own editor hook, you can put it in a
        configuration file which you load at startup time.  The default hook
        is defined in the IPython.core.hooks module, and you can use that as a
        starting example for further modifications.  That file also has
        general instructions on how to set a new hook for use once you've
        defined it.zprxn:r   NzEditing In[%i]Tz
Editing...rt   )r%   z'%s'zCould not open editorpasted_blockry   rz   xzdone. Executing edited code...__file__rn   F)store_historyz'File not found. Did you forget to save?)r|   r   r   r   r   rf   rY   r   r\   r   rd   addsysstdoutflushr   absoluter   r   r   r   r=   r   r   r   run_cellsafe_execfiler   r   showtraceback)r]   r   r   r   rf   r   r:   is_tempr   filepathquotedsourcemsgs                r    editzCodeMagics.edit   s   b &&{7;	T
	N(,(>(>tzz7;T9)N%Hfg    *$***G 	l$

>		 !$H$5$5$7 88FXf}&JJ##FF3 ::<>)191C1CW1C1UDJJ~.$;G23tzz11:> A5=DJJ&&z2$;%///AFJJ''e'DJJ,,Xtzz7I7I-1ZZ-?-?AA /))7);; k  	T166!9-# 	N"QWW,-qww<D(,(>(>tzz7;T9)N%Hfg	N6  	()	A A  /%1BCJJ,,../sb   "H !A
J* !BKK 	J'IJ'AJ""J'*K KK	L%#L L  L%)ri   )r   r   r   r_   r^   r   r   r   r   r   staticmethodr   r   r   r   __classcell__)rh   s   @r    ra   ra      s    L: A AF 30 30j   W: W:r * *B2 !RG Q/  Q/r   ra   )7r_   r   r   r~   rK   r   r6   	itertoolsr   urllib.requestr   r   urllib.parser   pathlibr   IPython.core.errorr   r	   r
   IPython.core.macror   IPython.core.magicr   r   r   IPython.core.oinspectr   r   IPython.core.releaser   IPython.testing.skipdoctestr   IPython.utils.contextsr   IPython.utils.pathr   warningsr   loggingr   IPython.utils.textr   r   r   rL   r   VERBOSEr*   r1   rI   rW   r   rY   ra   r   r   r    <module>r     s     	 	 	 
 
  + "  M L $ ? ? > ( 4 0 .   , $* #BJJCD  2::  	jj	:2h>9  C	/ C	/ C	/r   