
    }eT1                         d 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
mZmZ ddlmZmZmZ ddlmZ ddlmZ  e       Ze G d	 d
e
             Zy)z6Implementation of magic functions related to History.
    N)open)StdinNotImplementedError)Magicsmagics_class
line_magic)argumentmagic_argumentsparse_argstring)skip_doctest)ioc                   t   e Zd Z e        eddddd       eddddd	       ed
dddd       eddddd       eddd       eddddd       eddeded        ed!d"dd#$       ed%d&      eed*d'                                                                                    Z	ed(        Z
ed*d)       Zy)+HistoryMagicsz-n
print_nums
store_trueFz{
        print line numbers for each input.
        This feature is only available if numbered prompts are in use.
        )destactiondefaulthelpz-o
get_outputz"also print outputs for each input.z-p	pypromptsz
        print classic '>>>' python prompts before each input.
        This is useful for making documentation, and in conjunction
        with -o, for producing doctest-ready output.
        z-trawstore_falseTa  
        print the 'translated' history, as IPython understands it.
        IPython filters your input and converts it all into valid Python
        source before executing it (things like magics or aliases are turned
        into function calls, for example). With this option, you'll see the
        native history instead of the user-entered version: '%%cd /' will be
        seen as 'get_ipython().run_line_magic("cd", "/")' instead of '%%cd /'.
        z-ffilenamea  
        FILENAME: instead of printing the output to the screen, redirect
        it to the given file.  The file is always overwritten, though *when
        it can*, IPython asks for confirmation first. In particular, running
        the command 'history -f FILENAME' from the IPython Notebook
        interface will replace FILENAME even if it already exists *without*
        confirmation.
        )r   r   z-gpattern*Nac  
        treat the arg as a glob pattern to search for in (full) history.
        This includes the saved history (almost all commands ever written).
        The pattern may contain '?' to match one unknown character and '*'
        to match any number of unknown characters. Use '%%hist -g' to show
        full saved history (may be very long).
        )r   nargsr   r   z-llimit?z
        get the last n lines from all sessions. Specify n as a single
        arg, or the default is the last 10 lines.
        )r   typer   r   r   z-uuniquezN
        when searching history using `-g`, show only unique history.
        )r   r   r   range)r   c                 ,   t        | j                  |      }| j                  j                  fd}|j                  }|st
        j                  }d}nt        j                  j                  |      }t        j                  j                  |      r2	 t        j                  d|z        }|st        d       yt        d       t        |dd	
      }d}|j                   }|j"                  }	|j$                  }
|j&                  }d}|j(                  t*        u rdn|j(                  }d}|j,                  _|j.                  sS|j,                  r"ddj1                  |j,                        z   dz   }nd}j3                  |||	||j4                        }d}n|j(                  t*        ur|dn|}j7                  |||	      }n[|j,                  r#ddj1                  |j,                        z   dz   }d}j9                  dj1                  |j.                        ||	      }d}|D ]  \  }}}|	r|\  }}|rt;        j:                  ||      s'|j=                  d      j?                         }d|v }|rdnd}|r)t         |||      jA                  |      d||d       |
r2t        dd|       |r"dj1                  |jC                               dz   }t        ||       |	sst        ||        |r|jE                          yy# t        $ r d}Y gw xY w)a  Print input history (_i<n> variables), with most recent last.

        By default, input history is printed without line numbers so it can be
        directly pasted into an editor. Use -n to show them.

        By default, all input history from the current session is displayed.
        Ranges of history can be indicated using the syntax:

        ``4``
            Line 4, current session
        ``4-6``
            Lines 4-6, current session
        ``243/1-5``
            Lines 1-5, session 243
        ``~2/7``
            Line 7, session 2 before current
        ``~8/1-~6/5``
            From the first line of 8 sessions ago, to the fifth line of 6
            sessions ago.

        Multiple ranges can be entered, separated by spaces

        The same syntax is used by %macro, %save, %edit, %rerun

        Examples
        --------
        ::

          In [6]: %history -n 4-6
          4:a = 12
          5:print a**2
          6:%history -n 4-6

        c                 H    | dj                   fv rt        |      S | d|S )z0Helper function to format line numbers properly.r   /)session_numberstr)sessionlinehistory_managers     =/usr/lib/python3/dist-packages/IPython/core/magics/history.py_format_linenoz-HistoryMagics.history.<locals>._format_lineno   s+    1o<<==4y %t,,    FzFile %r exists. Overwrite?Tz	Aborting.NzOverwriting file.wzutf-8)encodingr    )r   outputnr    
   )r   r0      
: )fileendz>>> )r8   r7   z
... z
...)r7   )#r
   historyshellr)   r   sysstdoutospath
expanduserexistsr   
ask_yes_nor   printio_openr   r   r   r   r   _unspecifiedr   r!   joinsearchr    get_tailget_range_by_strfnmatch
expandtabsrstriprjust
splitlinesclose)selfparameter_sargsr+   outfnameoutfileclose_at_endansr   r   r   r   r   r   range_patternhistr1   widthr'   linenoinliner0   	multilineline_sepr)   s                           @r*   r9   zHistoryMagics.history(   s   @ t||[9 **44	- ==jjG Lww))(3Hww~~h'--(Dx(OPC +&)*hg>GL__
__
NN	hh

l2

<<#DJJ|| 66<"))'s:,1$++ * GDJZZ|+mA"++A3z+JD|| #chht||&< <s B!
"33$c:D '+ 	,#GVV
 !'v}=&&q)002FI(tcH.&"A"G"G"N ")0c;g3W5%]]6+<+<+>?'IF&w'ff7+/	,2 MMO G 0 Cs   L LLc                 <   |s<| j                   j                  t        | j                   j                  d                y| j                   j                  j                  |      }dj                  d |D              }|r*| j                   j                  |j                                y	 t        t        || j                   j                              }| j                   j                  |j                                y# t        $ r | j                   j                  j                  d|z   dz         }t        |D cg c]  }|d   	 nc c}w c}      D ]6  }d|v sd|v r| j                   j                  |j                                 Y y Y nw xY wt        d	|       y)
aI  Repeat a command, or get command to input line for editing.

        %recall and %rep are equivalent.

        - %recall (no arguments):

        Place a string version of last computation result (stored in the
        special '_' variable) to the next input prompt. Allows you to create
        elaborate command lines without using copy-paste::

             In[1]: l = ["hei", "vaan"]
             In[2]: "".join(l)
            Out[2]: heivaan
             In[3]: %recall
             In[4]: heivaan_ <== cursor blinking

        %recall 45

        Place history line 45 on the next input prompt. Use %hist to find
        out the number.

        %recall 1-4

        Combine the specified lines into one cell, and place it on the next
        input prompt. See %history for the slice syntax.

        %recall foo+bar

        If foo+bar can be evaluated in the user namespace, the result is
        placed at the next input prompt. Otherwise, the history is searched
        for lines which contain that substring, and the most recent one is
        placed at the next input prompt.
        _Nr4   c              3   &   K   | ]	  }|d      yw)   N ).0xs     r*   	<genexpr>z'HistoryMagics.recall.<locals>.<genexpr>  s     0!0s   r   r`   recallrepz%Couldn't evaluate or find in history:)r:   set_next_inputr&   user_nsr)   rH   rE   rK   eval	ExceptionrF   reversedrB   )rO   arg	histlinescmdrc   hs         r*   re   zHistoryMagics.recall   sK   F JJ%%c$***<*<S*A&BCJJ..??D	ii0i00JJ%%cjjl3	d3

 2 234C JJ%%cjjl3  	

2299#c'#+FIY7qt778 q=EQJ

))!((*5		 	5s;s%   ))C< <=F9E
AF
FFc                 t   | j                  |dd      \  }}d|v rW	 t        |d         }|dk(  rt        d       y|dk  rt        d	       y| j                  j
                  j                  |      }nd
|v rXd|d
   z   dz   }t        | j                  j
                  j                  |            }t        |      D ]  }d|d   vs|g} nQ g }nM|r&| j                  j
                  j                  |      }n%| j                  j
                  j                  d      }|D cg c]  }|d   	 }}|st        d       ydj                  |      }	t        d       t        |	       t        d       | j                  j                  dj                  |      d       y# t        $ r t        d       Y yw xY wc c}w )ao  Re-run previous input

        By default, you can specify ranges of input history to be repeated
        (as with %history). With no arguments, it will repeat the last line.

        Options:

          -l <n> : Repeat the last n lines of input, not including the
          current command.

          -g foo : Repeat the most recent line which contains foo
        zl:g:string)modelz"Number of lines must be an integerNr   z'Requested 0 last lines - nothing to runz+Number of lines to rerun cannot be negativegr   rerunr`      z'No lines in history match specificationr4   z=== Executing: ===z=== Output: ===F)store_history)parse_optionsint
ValueErrorrB   r:   r)   rG   listrF   rk   rH   rE   run_cell)
rO   rP   optsrQ   r1   rW   prs   rc   rm   s
             r*   ru   zHistoryMagics.rerun  s    ''V('K
d$;S	N
 Av?@QCD::--66q9DD[DIc!A

2299!<=Dd^ !A$&3D
 ::-->>tDD::--66q9D"#!##;<IIdO	"#i 

DIIdO5AC  :;2 $s   F  F5F21F2)r6   )__name__
__module____qualname__r	   r   ry   rD   r   r   r9   re   ru   ra   r,   r*   r   r   %   sI    <e <e13 ;|U 5	 :	 9C 7C 8L
 gS!~   "		3 x~@ 8< 8<t 2B 2Br,   r   )__doc__r=   r;   r   r   rC   rI   IPython.core.errorr   IPython.core.magicr   r   r   IPython.core.magic_argumentsr   r	   r
   IPython.testing.skipdoctestr   IPython.utilsobjectrD   r   ra   r,   r*   <module>r      s]    
 
   8 ? ?; ; 4  x lBF lB lBr,   