
    f                        d Z ddlZddlZddlmZ ddlZddlZddl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mZmZmZmZmZmZmZmZmZmZ e G d	 d
e             Ze
d        ZdZe
d        Z G d de	      Z  G d de       Z! G d de!      Z" G d dejF                        Z$ ejJ                  dejL                        Z'd Z(d Z)y)z* History related magics and functionality     N)Path)LoggingConfigurable)	decorator)undoc)locate_profile)AnyBoolDictInstanceIntegerListUnicodeUnion
TraitErrordefaultobservec                   (    e Zd ZdZd Zd Zd Zd Zy)DummyDBz[Dummy DB that will act as a black hole for history.

    Only used in the absence of sqlitec                      g S N )argskwargss     O/var/www/cvtools/html/venv/lib/python3.12/site-packages/IPython/core/history.pyexecutezDummyDB.execute)   s    	    c                      y r   r   selfr   r   s      r   commitzDummyDB.commit,       r   c                      y r   r   r   s      r   	__enter__zDummyDB.__enter__/   r!   r   c                      y r   r   r   s      r   __exit__zDummyDB.__exit__2   r!   r   N)__name__
__module____qualname____doc__r   r    r#   r%   r   r   r   r   r   $   s    *r   r   c                 6    |j                   sg S  | |g|i |S )z9Decorator: return an empty list in the absence of sqlite.)enabled)fr   akws       r   only_when_enabledr/   6   s%     <<	  R  r   i @  c                 d   	  | |g|i |S # t         j                  t         j                  f$ r}|xj                  dz  c_        |j                  j                  d|j                  |       |j                  dk7  r|j                  |j                  kD  r$d|_        |j                  j                  d       nW|j                  j                         r<t        |j                  j                  |j                  j                  z        }|j                  j                  }|j                  j                         j                  }|t        k\  rt         j                   j#                         j%                         j'                  dd      }|dz   |z   |z   }	t)        d      D ].  }
t+        |	      j-                         s n|dz   |z   d	|
z  z   |z   }	0 n|d
z   |z   }	|j                  j/                  |	       |j                  j                  d|	       |j1                          g cY d}~S  d}~ww xY w)a,  A decorator which wraps HistoryAccessor method calls to catch errors from
    a corrupt SQLite database, move the old database out of the way, and create
    a new one.

    We avoid clobbering larger databases because this may be triggered due to filesystem issues,
    not just a corrupt file.
       z&Failed to open SQLite history %s (%s).:memory:zAFailed to load history too many times, history will not be saved.:.z	-corrupt-d   z-%iz-corruptz4History file was moved to %s and a new file created.N)sqlite3DatabaseErrorOperationalError_corrupt_db_counterlogerror	hist_file_corrupt_db_limitis_filestrparentstemsuffixstatst_size_SAVE_DB_SIZEdatetimenow	isoformatreplaceranger   existsrenameinit_db)r,   r   r-   r.   ebaseextsizerG   newpathis              r   catch_corrupt_dbrT   C   s   "  R  !!7#;#;<    A% ?QRS>>Z'''$*@*@@!+bc'')4>>004>>3F3FFGnn++~~**,44=("++//1;;=EEc3OC"[036<G"3Z T#G}335!&*[&83&>&1*&MPS&SG	T #Z/#5G%%g.UW^_LLNI A s!    $H/G1H*#H/)H**H/c                   4    e Zd ZdZddZ	 	 ddZd	dZd
dZy)HistoryAccessorBasez(An abstract class for History Accessors c                     t         r   NotImplementedError)r   nrawoutputinclude_latests        r   get_tailzHistoryAccessorBase.get_tailt       !!r   Nc                     t         r   rX   )r   patternr[   
search_rawr\   rZ   uniques          r   searchzHistoryAccessorBase.searchw   s    !!r   c                     t         r   rX   )r   sessionstartstopr[   r\   s         r   	get_rangezHistoryAccessorBase.get_range{   r_   r   c                     t         r   rX   )r   rangestrr[   r\   s       r   get_range_by_strz$HistoryAccessorBase.get_range_by_str~   r_   r   
   TFF*TTFNFr1   NTFTF)r&   r'   r(   r)   r^   rd   ri   rl   r   r   r   rV   rV   q   s!    2" 8<,1"""r   rV   c                       e Zd ZdZdZdZ e ee       e	       gd      j                  d      Z edd      j                  d      Z ed	      j                  d      Z e       Z ed
      d        Zd fd	ZddZed        Zd ZddZeed               Zed        Zedd       Ze	 	 dd       Zedd       ZddZ  xZ!S )HistoryAccessorzAccess the history database without adding to it.

    This is intended for use by standalone history tools. IPython shells use
    HistoryManager, below, which is a subclass of this.r      a  Path to file to use for SQLite history database.

        By default, IPython will put the history database in the IPython
        profile directory.  If you would rather share one history among
        profiles, you can set this value in each, so that they are consistent.

        Due to an issue with fcntl, SQLite is known to misbehave on some NFS
        mounts.  If you see IPython hanging, try setting this to something on a
        local disk, e.g::

            ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite

        you can also use the specific value `:memory:` (including the colon
        at both end but not the back ticks), to avoid creating an history file.

        helpTconfiga*  enable the SQLite history

        set enabled=False to disable the SQLite history,
        in which case there will be no stored history, no SQLite connection,
        and no background saving thread.  This may be necessary in some
        threaded environments where IPython is embedded.
        zOptions for configuring the SQLite connection

        These options are passed as keyword args to sqlite3.connect
        when establishing database connections.
        dbc                     |d   }t         t        j                  f}t        ||      s&| j                  j
                  d|}t        |      y)zCvalidate the db, since it can be an Instance of two different typesnewz/.db must be sqlite3 Connection or DummyDB, not N)r   r6   
Connection
isinstance	__class__r&   r   )r   changer|   connection_typesmsgs        r   _db_changedzHistoryAccessor._db_changed   sN     Um#W%7%78#/0^^,,c3CS/! 1r   c                     t        t        | 
  di | |r|| _        	 | j                   | j                          y# t        $ r | j                  |      | _        Y 2w xY w)a  Create a new history accessor.

        Parameters
        ----------
        profile : str
            The name of the profile from which to open history.
        hist_file : str
            Path to an SQLite history database stored by IPython. If specified,
            hist_file overrides profile.
        config : :class:`~traitlets.config.loader.Config`
            Config object. hist_file can also be set through this.
        Nr   )superrt   __init__r<   r   _get_hist_file_namerM   )r   profiler<   traitsr   s       r   r   zHistoryAccessor.__init__   s]     	ot-77 &DN	?NN
 		  	?!55g>DN	?s   < AAc                 0    t        t        |            dz  S )a  Find the history file for the given profile name.

        This is overridden by the HistoryManager subclass, to use the shell's
        active profile.

        Parameters
        ----------
        profile : str
            The name of a profile which has a history file.
        history.sqlite)r   r   )r   r   s     r   r   z#HistoryAccessor._get_hist_file_name   s     N7+,/???r   c                 $   | j                   st               | _        yt        t        j
                  t        j                  z        }|j                  | j                         t	        j                  t        | j                        fi || _        | j                  5  | j                  j                  d       | j                  j                  d       | j                  j                  d       ddd       d| _        y# 1 sw Y   d| _        yxY w)z8Connect to the database, and create tables if necessary.N)detect_typeszCREATE TABLE IF NOT EXISTS sessions (session integer
                            primary key autoincrement, start timestamp,
                            end timestamp, num_cmds integer, remark text)zCREATE TABLE IF NOT EXISTS history
                    (session integer, line integer, source text, source_raw text,
                    PRIMARY KEY (session, line))zCREATE TABLE IF NOT EXISTS output_history
                            (session integer, line integer, output text,
                            PRIMARY KEY (session, line))r   )r+   r   rz   dictr6   PARSE_DECLTYPESPARSE_COLNAMESupdateconnection_optionsconnectr?   r<   r   r9   )r   r   s     r   rM   zHistoryAccessor.init_db   s     ||iDG 7#:#:7;Q;Q#QRd--.//#dnn"5@@WW 	GGOOM
 GGOO4 GGOO<	& $% '	& $% s   AC??Dc                      y)zWOverridden by HistoryManager to dump the cache before certain
        database lookups.Nr   r   s    r   writeout_cachezHistoryAccessor.writeout_cache	  s     	r   c                     |rdnd}d}|rd}d|z  }|r|dz  }d|d|d	|z   }| j                   j                  ||      }	|r	d
 |	D        }	|r	d |	D        S |	S )a  Prepares and runs an SQL query for the history database.

        Parameters
        ----------
        sql : str
            Any filtering expressions to go after SELECT ... FROM ...
        params : tuple
            Parameters passed to the SQL query (to replace "?")
        raw, output : bool
            See :meth:`get_range`
        latest : bool
            Select rows with max (session, line)

        Returns
        -------
        Tuples as :meth:`get_range`
        
source_rawsourcehistoryz6history LEFT JOIN output_history USING (session, line)z!history.%s, output_history.outputz", MAX(session * 128 * 1024 + line)zSELECT session, line, z FROM  c              3   &   K   | ]	  }|d d   y w)Nr   ).0rows     r   	<genexpr>z+HistoryAccessor._run_sql.<locals>.<genexpr>-  s     +3s8+s   c              3   4   K   | ]  \  }}}}||||ff  y wr   r   )r   seslininpouts        r   r   z+HistoryAccessor._run_sql.<locals>.<genexpr>/  s$     I/AsCcS#Sz*Is   )rz   r   )
r   sqlparamsr[   r\   latesttogetsqlfromthis_querrycurs
             r   _run_sqlzHistoryAccessor._run_sql  sv    $ !$NG7%?E99E=BGLsRggook62+s+CISII
r   c                 \    d}| j                   j                  ||f      j                         S )a)  Get info about a session.

        Parameters
        ----------
        session : int
            Session number to retrieve.

        Returns
        -------
        session_id : int
            Session ID number
        start : datetime
            Timestamp for the start of the session.
        end : datetime
            Timestamp for the end of the session, or None if IPython crashed.
        num_cmds : int
            Number of commands run, or None if IPython crashed.
        remark : unicode
            A manually set description.
        z)SELECT * from sessions where session == ?)rz   r   fetchone)r   rf   querys      r   get_session_infoz HistoryAccessor.get_session_info2  s)    . <wwuwj1::<<r   c                 @    | j                  dd      D ]  }|d   c S  y)zGet the last session ID currently in the database.

        Within IPython, this should be the same as the value stored in
        :attr:`HistoryManager.session_number`.
        r1   T)rZ   r]   r   N)r^   )r   records     r   get_last_session_idz#HistoryAccessor.get_last_session_idL  s*     mmam= 	F!9	r   c                     | j                          |s|dz  }| j                  d|f||      }|st        t        |      dd       S t        t        |            S )a  Get the last n lines from the history database.

        Parameters
        ----------
        n : int
            The number of lines to get
        raw, output : bool
            See :meth:`get_range`
        include_latest : bool
            If False (default), n+1 lines are fetched, and the latest one
            is discarded. This is intended to be used where the function
            is called by a user command, which it should not return.

        Returns
        -------
        Tuples as :meth:`get_range`
        r1   z(ORDER BY session DESC, line DESC LIMIT ?r[   r\   N)r   r   reversedlist)r   rZ   r[   r\   r]   r   s         r   r^   zHistoryAccessor.get_tailV  sc    & 	FAmm6#f  
 DIabM**S	""r   c                     |rdnd}|rd|z   }| j                          d|z  }|f}	|r|dj                  |      z  }||dz  }|	|fz  }	n|r|dz  }| j                  ||	|||      }
|t        t	        |
            S |
S )	at  Search the database using unix glob-style matching (wildcards
        * and ?).

        Parameters
        ----------
        pattern : str
            The wildcarded pattern to match when searching
        search_raw : bool
            If True, search the raw input, otherwise, the parsed input
        raw, output : bool
            See :meth:`get_range`
        n : None or int
            If an integer is given, it defines the limit of
            returned entries.
        unique : bool
            When it is true, return only unique entries.

        Returns
        -------
        Tuples as :meth:`get_range`
        r   r   zhistory.zWHERE %s GLOB ?z GROUP BY {0}z) ORDER BY session DESC, line DESC LIMIT ?z ORDER BY session, line)r[   r\   r   )r   formatr   r   r   )r   ra   r[   rb   r\   rZ   rc   tosearchsqlformr   r   s              r   rd   zHistoryAccessor.searchs  s    0 $.<8!H,H#h.--h77G=BBGqdNF00GmmGVVFmS=DI&&
r   c                 R    |rd}|||f}nd}||f}| j                  d|z  |||      S )a  Retrieve input by session.

        Parameters
        ----------
        session : int
            Session number to retrieve.
        start : int
            First line to retrieve.
        stop : int
            End of line range (excluded from output itself). If None, retrieve
            to the end of the session.
        raw : bool
            If True, return untranslated input
        output : bool
            If True, attempt to include output. This will be 'real' Python
            objects for the current session, or text reprs from previous
            sessions if db_log_output was enabled at the time. Where no output
            is found, None is used.

        Returns
        -------
        entries
            An iterator over the desired lines. Each line is a 3-tuple, either
            (session, line, input) if output is False, or
            (session, line, (input, output)) if output is True.
        zline >= ? AND line < ?zline>=?zWHERE session==? AND %sr   )r   )r   rf   rg   rh   r[   r\   
lineclauser   s           r   ri   zHistoryAccessor.get_range  sN    8 1Jud+F"Ju%F}}6C$*F  D 	Dr   c              #   r   K   t        |      D ]%  \  }}}| j                  |||||      D ]  }|  ' yw)a  Get lines of history from a string of ranges, as used by magic
        commands %hist, %save, %macro, etc.

        Parameters
        ----------
        rangestr : str
            A string specifying ranges, e.g. "5 ~2/1-4". If empty string is used,
            this will return everything from current session's history.

            See the documentation of :func:`%history` for the full details.

        raw, output : bool
            As :meth:`get_range`

        Returns
        -------
        Tuples as :meth:`get_range`
        r   N)extract_hist_rangesri   )r   rk   r[   r\   sesssrN   lines           r   rl   z HistoryAccessor.get_range_by_str  sI     & .h7 	JD!QtQs6J 
	s   57)r    )r   )TFFrm   ro   rq   rr   )"r&   r'   r(   r)   r9   r=   r   r   r   r   tagr<   r	   r+   r
   r   r   rz   r   r   r   r   rT   rM   r   r   r/   r   r   r^   rd   ri   rl   __classcell__r   s   @r   rt   rt      sP   ;  	$#$ 
cc% ( 4 
cc   
cc  
BT]" "8@ % %>B =  =0   # #8 7;,1' 'R #D #DJr   rt   c                   `    e Zd ZdZ edd      Z edg      Z edg      Z e       Z	 e
d      d        Z e       Z e       Z e       Z edd	
      j%                  d      Z edd
      j%                  d      Z e       Z e       Z edd      Z eej2                  d      Z ed      Z ed      Z ed      Z ed      Z e jB                  d      Z"d fd	Z#d dZ$e%d d       Z&d Z'd Z(d!dZ)d" fd	Z*e+d#d       Z,d$dZ-d% fd	Z.d dZ/d Z0d Z1d Z2e%d d       Z3 xZ4S )&HistoryManagerzHA class to organize all history-related functionality in one place.
    z1IPython.core.interactiveshell.InteractiveShellABCT)
allow_noner   dir_histc                 P    	 t        j                         gS # t        $ r g cY S w xY wr   )r   cwdOSErrorr   s    r   _dir_hist_defaultz HistoryManager._dir_hist_default  s)    	HHJ< 	I	s    %%Fz9Should the history database include output? (default: no)rv   rx   r   z}Write to database every x commands (higher values save disk access & power).
Values of 1 or less effectively disable caching.z(IPython.core.history.HistorySavingThreadz(exit|quit)(\s*\(.*\))?$c                    t        t        | 
  d||d| t        j                         | _        t        j                         | _        t        j                         | _        	 | j                          | j                  r;| j                  dk7  r+t!        |       | _        | j"                  j%                          yyy# t        j                  $ r2 | j                  j                  d| j                  d       d| _        Y w xY w)zGCreate a new history manager associated with a shell instance.
        )shellry   zBFailed to create history session in %s. History will not be saved.T)exc_infor2   Nr   )r   r   r   	threadingEvent	save_flagLockdb_input_cache_lockdb_output_cache_locknew_sessionr6   r8   r:   r;   r<   r+   HistorySavingThreadsave_threadrg   )r   r   ry   r   r   s       r   r   zHistoryManager.__init__  s     	nd, 	5 		"*#,>>#3 $-NN$4!	( <<DNNj8248D""$ 9< '' 	(HHNN_  /'DN	(s   $B< <AD Dc                 ^    | j                   j                  j                  }t        |      dz  S )zGet default history file name based on the Shell's profile.

        The profile parameter is ignored, but must exist for compatibility with
        the parent class.r   )r   profile_dirlocationr   )r   r   r   s      r   r   z"HistoryManager._get_hist_file_name+  s*    
 jj,,55K #333r   c                     || j                   }|5  |j                  dt        j                  j                         f      }|j                  | _        ddd       y# 1 sw Y   yxY w)zGet a new session number.NzRINSERT INTO sessions VALUES (NULL, ?, NULL,
                            NULL, '') )rz   r   rF   rG   	lastrowidsession_number)r   connr   s      r   r   zHistoryManager.new_session3  s`     <77D 	0,,*""&&(*C
 #&--D	0 	0 	0s   AAA$c                 8   | j                          | j                  5  | j                  j                  dt        j                  j	                         t        | j                        dz
  | j                  f       ddd       d| _        y# 1 sw Y   d| _        yxY w)zCClose the database session, filling in the end time and line count.zRUPDATE sessions SET end=?, num_cmds=? WHERE
                            session==?r1   Nr   )r   rz   r   rF   rG   leninput_hist_parsedr   r   s    r   end_sessionzHistoryManager.end_sessionA  s    WW 	QGGOO *,4,=,=,A,A,C 6 6794;N;N,PQ	Q  		Q  s   AB		Bc                     | j                   5  | j                   j                  d|| j                  f       ddd       y# 1 sw Y   yxY w)z8Give the current session a name in the history database.z-UPDATE sessions SET remark=? WHERE session==?N)rz   r   r   )r   names     r   name_sessionzHistoryManager.name_sessionJ  s?    WW 	9GGOOK!4#6#679	9 	9 	9s	   )?Ac                    | j                   j                          t        j                         g| j                  dd |rM| j
                  r| j                          dg| j                  dd dg| j                  dd | j                          yy)zfClear the session history, releasing all object references, and
        optionally open a new session.Nr   )
output_histclearr   r   r   r   r   r   input_hist_rawr   )r   r   s     r   resetzHistoryManager.resetP  sy     	  HHJ<a""  ")+D""1%&(TD" r   c                 T    |dk  r|| j                   z  }t        t        |   |      S )a  Get info about a session.

        Parameters
        ----------
        session : int
            Session number to retrieve. The current session is 0, and negative
            numbers count back from current session, so -1 is the previous session.

        Returns
        -------
        session_id : int
            Session ID number
        start : datetime
            Timestamp for the start of the session.
        end : datetime
            Timestamp for the end of the session, or None if IPython crashed.
        num_cmds : int
            Number of commands run, or None if IPython crashed.
        remark : unicode
            A manually set description.
        r   )rf   )r   r   r   r   )r   rf   r   s     r   r   zHistoryManager.get_session_infoa  s1    , a<t***G^T;G;LLr   c                 4   | j                          |s|dz  }t        | j                  d| j                  |f||            }t        | j                  d| j                  |f||            }||z   }|d| }|st        |      ddd   S t        |      ddd   S )a  Get the last n lines from the history database.

        Most recent entry last.

        Completion will be reordered so that that the last ones are when
        possible from current session.

        Parameters
        ----------
        n : int
            The number of lines to get
        raw, output : bool
            See :meth:`get_range`
        include_latest : bool
            If False (default), n+1 lines are fetched, and the latest one
            is discarded. This is intended to be used where the function
            is called by a user command, which it should not return.

        Returns
        -------
        Tuples as :meth:`get_range`
        r1   z/WHERE session == ? ORDER BY line DESC LIMIT ?  r   z;WHERE session != ? ORDER BY session DESC, line DESC LIMIT ?Nr   r   )r   r   r   r   )r   rZ   r[   r\   r]   this_cur	other_cur
everythings           r   r^   zHistoryManager.get_tail|  s    0 	FAMMA$$a(	  
 MMM$$a(	  
	 	)
^

#EQrE**J"%%r   c              #     K   |r| j                   n| j                  }t        |      }|dk  r||z  }|r||kD  r|}n
|dk  r||z  }t        ||      D ]1  }|r!||   | j                  j                  |      f}n||   }d||f 3 yw)zqGet input and output history from the current session. Called by
        get_range, and takes similar parameters.r   N)r   r   r   rJ   output_hist_reprsget)	r   rg   rh   r[   r\   
input_histrZ   rS   r   s	            r   _get_range_sessionz!HistoryManager._get_range_session  s      -0T((T5K5K

O19QJEqDAXAIDud# 	A"1t'='='A'A!'DE!!}a,	s   BBc                     |dk  r|| j                   z  }|| j                   k(  r| j                  ||||      S t        t        |   |||||      S )a  Retrieve input by session.

        Parameters
        ----------
        session : int
            Session number to retrieve. The current session is 0, and negative
            numbers count back from current session, so -1 is previous session.
        start : int
            First line to retrieve.
        stop : int
            End of line range (excluded from output itself). If None, retrieve
            to the end of the session.
        raw : bool
            If True, return untranslated input
        output : bool
            If True, attempt to include output. This will be 'real' Python
            objects for the current session, or text reprs from previous
            sessions if db_log_output was enabled at the time. Where no output
            is found, None is used.

        Returns
        -------
        entries
            An iterator over the desired lines. Each line is a 3-tuple, either
            (session, line, input) if output is False, or
            (session, line, (input, output)) if output is True.
        r   )r   r   r   r   ri   )r   rf   rg   rh   r[   r\   r   s         r   ri   zHistoryManager.get_range  s`    8 a<t***GD'''**5$VDD^T4WeT35;= 	=r   c                 <   ||}|j                  d      }|j                  d      }| j                  j                  |j                               ry| j                  j                  |       | j                  j                  |       | j                  5  | j                  j                  |||f       t        | j                        | j                  k\  r| j                  j                          ddd       | j                  | _        | j                  | _        | j                   | _        || _        d|z  }d| j                  d| j                  d| j                  || j                   i}| j"                  | j"                  j%                  |d       yy# 1 sw Y   xY w)	a  Store source and raw input in history and create input cache
        variables ``_i*``.

        Parameters
        ----------
        line_num : int
            The prompt number of this input.
        source : str
            Python input.
        source_raw : str, optional
            If given, this is the raw input without any IPython transformations
            applied to it.  If not given, ``source`` is used.
        N
z_i%s_i_ii_iiiF)interactive)rstrip_exit_rematchstripr   appendr   r   db_input_cacher   db_cache_sizer   setr   r   r   _i00r   push)r   line_numr   r   new_ito_mains         r   store_inputszHistoryManager.store_inputs  s]    Jt$&&t,
 ==z//12%%f-"":.%% 	%&&&*'EF4&&'4+=+==""$		% HH	77))	 !$((499499'
 ::!JJOOGO7 "'	% 	%s   AFFc                 (   | j                   r|| j                  vry| j                  |   }| j                  5  | j                  j	                  ||f       ddd       | j
                  dk  r| j                  j                          yy# 1 sw Y   4xY w)a7  If database output logging is enabled, this saves all the
        outputs from the indicated prompt number to the database. It's
        called by run_cell after code has been executed.

        Parameters
        ----------
        line_num : int
            The line number from which to save outputs
        Nr1   )db_log_outputr   r   db_output_cacher  r  r   r  )r   r
  r\   s      r   store_outputzHistoryManager.store_output  s     ""8N8N(N''1&& 	<  ''6(:;	<"NN  #	< 	<s   BBc                     |5  | j                   D ]"  }|j                  d| j                  f|z          $ 	 d d d        y # 1 sw Y   y xY w)Nz'INSERT INTO history VALUES (?, ?, ?, ?))r  r   r   r   r   r   s      r   _writeout_input_cachez$HistoryManager._writeout_input_cache.  sO     	=++ =F!%!4!4 6t ;==	= 	= 	=	   2?Ac                     |5  | j                   D ]"  }|j                  d| j                  f|z          $ 	 d d d        y # 1 sw Y   y xY w)Nz+INSERT INTO output_history VALUES (?, ?, ?))r  r   r   r  s      r   _writeout_output_cachez%HistoryManager._writeout_output_cache4  sO     	=,, =J!%!4!4 6t ;==	= 	= 	=r  c                 `   || j                   }| j                  5  	 | j                  |       g | _        	 ddd       | j                  5  	 | j                  |       g | _        	 ddd       y# t        j                  $ rW | j                  |       t        dd| j                         	 | j                  |       n# t        j                  $ r Y nw xY wY w xY w# g | _        w xY w# 1 sw Y   xY w# t        j                  $ r t        dd       Y w xY w# g | _        w xY w# 1 sw Y   yxY w)z/Write any entries in the cache to the database.Nz,ERROR! Session/line number was not unique inz.database. History logging moved to new sessionz0!! Session/line number for output was not uniquez'in database. Output will not be stored.)rz   r   r  r6   IntegrityErrorr   printr   r  r   r  r  )r   r   s     r   r   zHistoryManager.writeout_cache:  s6    <77D%% 	))**40 ')#	)" && 	**++D1
 (*$	* 	* )) 
  &DF040C0CE ..t4-- 
 ')#	) 	)( )) AH?AA (*$	* 	*s   C'A.C'
D$C3D$.;C*B<;C<CCCCCCC	C$$C''C03DDDD	D!!D$$D-)NNr   )T)r   rm   rq   )r   r1   NTF)5r&   r'   r(   r)   r   r   r   r   r   r   r   r   r
   r   r   r   r   r	   r   r  r  r  r  r   r   r   r   r   r  r   r   r   recompiler  r   r   r/   r   r   r   r   r   rT   r^   r   ri   r  r  r  r  r   r   r   s   @r   r   r     s   
 H $&E bT
2$ZNvHZ  &K YNH	cc  A; 
cc 
 VNfO E&*,KT:I 3<D	B
#,C3<D
 rzz56H%(4 0 0 9"M6 2& 2&h(!=L.8`!&== * *r   r   c                   D     e Zd ZdZdZdZdZ fdZed        Z	d Z
 xZS )r   a;  This thread takes care of writing history to the database, so that
    the UI isn't held up while that happens.

    It waits for the HistoryManager's save_flag to be set, then writes out
    the history cache. The main thread is responsible for setting the flag when
    the cache size reaches a defined threshold.TFc                     t         t        |   d       || _        |j                  | _        t        j                  | j                         y )NIPythonHistorySavingThread)r   )r   r   r   history_managerr+   atexitregisterrh   )r   r   r   s     r   r   zHistorySavingThread.__init__e  s<    !417S1T.&..		"r   c                 "   	 t        j                  t        | j                  j                        fi | j                  j
                  | _        	 | j                  j                  j                          | j                  r| j                  j                          y | j                  j                  j                          | j                  j                  | j                         # t        $ r!}t        dt        |      z         Y d }~y d }~ww xY w)NzcThe history saving thread hit an unexpected error (%s).History will not be written to the database.)r6   r   r?   r   r<   r   rz   r   waitstop_nowcloser   r   	Exceptionr  repr)r   rN   s     r   runzHistorySavingThread.runk  s    	NooD((223&&99DG $$..335==GGMMO$$..446$$33DGG<   	N BEI!WM N N	Ns   BC$ A
C$ $	D-D		Dc                 z    d| _         | j                  j                  j                          | j	                          y)zThis can be called from the main thread to safely stop this thread.

        Note that it does not attempt to write out remaining history before
        exiting. That should be done by calling the HistoryManager's
        end_session method.TN)r%  r   r   r  joinr   s    r   rh   zHistorySavingThread.stop~  s,     &&**,		r   )r&   r'   r(   r)   daemonr%  r+   r   r/   r)  rh   r   r   s   @r   r   r   [  s9    3 FHG# N N$r   r   zc
((?P<startsess>~?\d+)/)?
(?P<start>\d+)?
((?P<sep>[\-:])
 ((?P<endsess>~?\d+)/)?
 (?P<end>\d+))?
$c              #     K   | dk(  rd y| j                         D ]/  }t        j                  |      }|s|j                  d      }|r/t	        |      }|j                  d      }|rt	        |      n|dz   }n|j                  d      spd}d}|j                  d      d	k(  r|dz  }|j                  d      xs d
}|j                  d      xs |}t	        |j                  dd	            }t	        |j                  dd	            }||k\  sJ d       ||k(  r	|||f ||df t        |dz   |      D ]	  }|ddf  |d|f 2 yw)a!  Turn a string of history ranges into 3-tuples of (session, start, stop).

    Empty string results in a `[(0, 1, None)]`, i.e. "everything from current
    session".

    Examples
    --------
    >>> list(extract_hist_ranges("~8/5-~7/4 2"))
    [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
    r   )r   r1   NNrg   endr1   	startsesssep-0endsess~z.start session must be earlier than end session)splitrange_rer  groupintrI   rJ   )
ranges_str	range_strrmatchrg   r.  r/  r3  r   s           r   r   r     so     R%%'  		*W%JE,,u%C!#c(uqyC<<,EC<<#%1HCLL-4	,,y)6Y	))#c23	gooc#./)#U%UU#ieS))%&&)A+w/ 	"DD/!	"3? s   EEc                 0    | dk(  rt        |      S | d|S )z0Helper function to format line numbers properly.r   #)r?   )rf   r   s     r   _format_linenor>    s    !|4yt$$r   )*r)   r!  rF   pathlibr   r  r6   r   traitlets.config.configurabler   r   IPython.utils.decoratorsr   IPython.pathsr   	traitletsr   r	   r
   r   r   r   r   r   r   r   r   objectr   r/   rE   rT   rV   rt   r   Threadr   r  VERBOSEr6  r   r>  r   r   r   <module>rG     s    0    	   =  * (   $ f  " ! ! 
* *Z"- ""V) Vr
}*_ }*@+)** +^ 2::  	jj. b%r   