
    Mh\                         d dl Z d dlZd dl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 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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# d dl$m%Z% d dl&m'Z' ddl(m)Z) defdZ* G d de!          Z+ G d de          Z,defdZ-defdZ.defdZ/defdZ0defdZ1defdZ2defdZ3defdZ4defd Z5defd!Z6defd"Z7defd#Z8defd$Z9defd%Z:e	ee,df         Z;ded&e,d'efd(Z<defd)Z=defd*Z>dS )+    N)StringIO)CallableListOptionalUnion	GeneratorTupleClassVarAny)Buffer)KeyPressEvent)named_commands)AutoSuggestFromHistory
Suggestion)Document)History)PromptSession)	ProcessorTransformationTransformationInput)get_ipython)generate_tokens   )pass_throughdocumentc                 &    | j         | j                 S N)linescursor_position_row)r   s    g/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/terminal/shortcuts/auto_suggest.py
_get_queryr!      s    >(677    c                   P    e Zd ZU dZdZee         ed<   ddeddfdZ	d	e
defd
ZdS )AppendAutoSuggestionInAnyLinea  
    Append the auto suggestion to lines other than the last (appending to the
    last line is natively supported by the prompt toolkit).

    This has a private `_debug` attribute that can be set to True to display
    debug information as virtual suggestion on the end of any line. You can do
    so with:

        >>> from IPython.terminal.shortcuts.auto_suggest import AppendAutoSuggestionInAnyLine
        >>> AppendAutoSuggestionInAnyLine._debug = True

    F_debugclass:auto-suggestionstylereturnNc                     || _         d S r   )r'   )selfr'   s     r    __init__z&AppendAutoSuggestionInAnyLine.__init__0   s    


r"   tic                 &    j         j        dz
  }j        |k    } fd}j         j        dk    r |d          S j         j        |k    r|r |d          S j        j         j        k     r |d          S j        j        }|j        rj         j        s |d          S j        j         j        z
  }|j        j        	                                }t          |          dk    r |d          S t          j        d	k     rt          |          dk    rSt          j        d	k     rCj        j         j        k    rt          j        d
gz             S t          j                  S t          |          dk    r;j        j         j        k    r&t          j         j        |d         fgz             S t          j                  S |dk    r(|d         }t          j         j        |fgz             S |r&|t          |          k     r-dt          |          |z
   d}t           j        |fg          S t          |          }	t!          t          |                    D ]T}
                    ||
z
            }d                    d |D                                                       }|r n|	dz  }	U|	rt           j        d|	 dfg          S t                              |t          |          z
  dz              j        r
 j        dfgng z             S |t          |          k     r||         }t           j        |fg          S j        t          |          z
  dz   }t                              |                    S )a  
         Apply transformation to the line that is currently being edited.

         This is a variation of the original implementation in prompt toolkit
         that allows to not only append suggestions to any line, but also to show
         multi-line suggestions.

         As transformation are applied on a line-by-line basis; we need to trick
         a bit, and elide any line that is after the line we are currently
         editing, until we run out of completions. We cannot shift the existing
         lines

         There are multiple cases to handle:

         The completions ends before the end of the buffer:
             We can resume showing the normal line, and say that some code may
             be hidden.

        The completions ends at the end of the buffer
             We can just say that some code may be hidden.

         And separately:

         The completions ends beyond the end of the buffer
             We need to both say that some code may be hidden, and that some
             lines are not shown.

        r   c                 \    t          j        j        j        rd| z   ndfgz             S )N  	fragments)r   r2   r'   r%   )textr*   r,   s    r    <lambda>zDAppendAutoSuggestionInAnyLine.apply_transformation.<locals>.<lambda>S   s:    Nltz3T3::RT&U%VV
 
 
 r"   znoop:onelineznoop:last line and cursorznoop:before cursorznoop:not eolr   znoop: no suggestions)   r   1   )redzD(Cannot show multiline suggestion; requires prompt_toolkit > 3.0.49)r1   u   … rest of suggestion (z lines) and code hiddenr0   c              3   &   K   | ]}|d          V  dS )r   N ).0ls     r    	<genexpr>zEAppendAutoSuggestionInAnyLine.apply_transformation.<locals>.<genexpr>   s&      ..aQqT......r"   u   … z line(s) hiddenzshift-last-line)r   
line_countlinenor   buffer_controlbuffer
suggestionis_cursor_at_the_end_of_liner3   
splitlineslenprompt_toolkitVERSIONr   r2   r'   rangeget_linejoinstripr%   )r*   r,   last_line_numberis_last_linenoopr@   deltasuggestionsrA   n_elidedillelshifts   ``            r    apply_transformationz2AppendAutoSuggestionInAnyLine.apply_transformation3   s   : ;1A5y$44
 
 
 
 
 ;!Q&&4''';*.>>><>43444 9r{6664,---")  	((P 	(4'''	BK;;',7799{q  4.///!J..;!##(>(K(K9 ???)"$,#    *BLAAAA[!!Q&&9 ???)"$,4:{1~2N1O"O    "BL9999A::$QJ!BLTZ<T;U,UVVVV 	6s;''''iK8H8H58Piii
%
J'?&@AAA;''H3{++,, " "[[!1A!566WW..2.....4466 "EMHH %
4T84T4T4T'U&VWWW%KK 03{3C3C Ca GHH<@KO%6788RQ  
 S%%%%$U+J!DJ
#;"<===IK 0 0014E!"++e"4"4555r"   )r&   )__name__
__module____qualname____doc__r%   r
   bool__annotations__strr+   r   r   rU   r9   r"   r    r$   r$       s           #FHTN""" c     i6': i6~ i6 i6 i6 i6 i6 i6r"   r$   c                       e Zd ZU dZeed<   ee         ed<   dZe	j
        dz  ed<   edz  ed<   edz  ed<   d Zeed	<    fd
ZdeddfdZd#dZdeddfdZdededee         fdZd#dZdededededeeeef         ddf         f
dZdedededeeeef         ddf         fdZdededefdZ dedededdfdZ!dedededdfdZ"d#dZ#e$d              Z%d#d!Z&defd"Z' xZ(S )$NavigableAutoSuggestFromHistoryz
    A subclass of AutoSuggestFromHistory that allow navigation to next/previous
    suggestion from history. To do so it remembers the current position, but it
    state need to carefully be cleared on the right events.
    
skip_lines_connected_appsN	_llm_task_init_llm_provider_llm_provider_instancec                     dS )Nwrongr9   )r*   xs     r    r4   z(NavigableAutoSuggestFromHistory.<lambda>   s    g r"   _llm_prefixerc                     t                                                       d| _        g | _        d | _        d | _        d| _        d S Nr   )superr+   r_   r`   rc   rb   _request_number)r*   	__class__s    r    r+   z(NavigableAutoSuggestFromHistory.__init__   sF    !&*#"& r"   _r(   c                     d| _         d S ri   )r_   )r*   rm   s     r    reset_history_positionz6NavigableAutoSuggestFromHistory.reset_history_position   s    r"   c                     |                                   | j        D ](}|j        j        }|                    | j                   )d S r   )_cancel_running_llm_taskr`   default_bufferon_text_insertremove_handlerro   )r*   pt_apptext_insert_events      r    
disconnectz*NavigableAutoSuggestFromHistory.disconnect   sZ    %%'''* 	J 	JF & 5 D,,T-HIIII	J 	Jr"   ru   c                     | j                             |           |j        j                            | j                   |j        j                            | j                   d S r   )r`   appendrr   rs   add_handlerro   on_cursor_position_changed_dismiss)r*   ru   s     r    connectz'NavigableAutoSuggestFromHistory.connect   sZ    ##F+++ 	,889TUUU8DDT]SSSSSr"   r@   r   c                     t          |          }|                                r7|                     || j        |j                  D ]\  }}t          |          c S d S r   )r!   rJ   _find_next_matchr_   historyr   )r*   r@   r   r3   rA   rm   s         r    get_suggestionz.NavigableAutoSuggestFromHistory.get_suggestion   sj     (##::<< 	.!%!6!6dov~" " . .
A "*-----tr"   c                 <    |                                   d |_        d S r   )rq   rA   )r*   r@   argskwargss       r    r|   z(NavigableAutoSuggestFromHistory._dismiss   s"    %%''' r"   r3   r   previousc              #     K   d}t          t          |                                                    D ]}t          |                                          D ]l}|dz  }|s||k     r|                    |          r;t          |          t          |          k    r|t          |          d         |fV  |r
||k    r  dS mdS )ac  
        text : str
            Text content to find a match for, the user cursor is most of the
            time at the end of this text.
        skip_lines : float
            number of items to skip in the search, this is used to indicate how
            far in the list the user has navigated by pressing up or down.
            The float type is used as the base value is +inf
        history : History
            prompt_toolkit History instance to fetch previous entries from.
        previous : bool
            Direction of the search, whether we are looking previous match
            (True), or next match (False).

        Yields
        ------
        Tuple with:
        str:
            current suggestion.
        float:
            will actually yield only ints, which is passed back via skip_lines,
            which may be a +inf (float)


        r   N)reversedlistget_stringsrC   
startswithrD   )r*   r3   r_   r   r   line_numberstringlines           r    _find_matchz+NavigableAutoSuggestFromHistory._find_match   s      8 tG$7$7$9$9::;; 
	 
	F !2!2!4!455 	 	q  K*$<$< ??4(( 9SYYT-B-Bs4yy{{+[8888 z 9 9FFF	
	 
	r"   c                 4    |                      |||d          S )NFr   )r   r*   r3   r_   r   s       r    r   z0NavigableAutoSuggestFromHistory._find_next_match  s!     j'EJJJr"   c           
      h    t          t          |                     |||d                              S )NTr   )r   r   r   r   s       r    _find_previous_matchz4NavigableAutoSuggestFromHistory._find_previous_match  s6    !!$
Gd!KKLL
 
 	
r"   query
other_thanc                     |                                   |                     || j        |          D ]\  }}||z   |k    r
|| _         d S d| _        d S ri   )rq   r   r_   r*   r   r   r   rA   r   s         r    upz"NavigableAutoSuggestFromHistory.up  ss    %%''''+'<'<4?G(
 (
 	  	 #J z!Z//"- 0
  DOOOr"   c                    |                                   |                     || j        |          D ]\  }}||z   |k    r
|| _         d S |                     |t          d          |          D ]\  }}||z   |k    r
|| _         d S d S )NInf)rq   r   r_   floatr   s         r    downz$NavigableAutoSuggestFromHistory.down"  s    %%''''+'@'@4?G(
 (
 	 	#J z!Z//"- 0
 ,0+D+DuU||W, ,  '
K :%33&1DOEE 4 r"   c                     | j         \| j                                         r	d| _         dS | j                                         }|rd| _         |st          j        d           dS dS dS )z]
        Try to cancel the currently running llm_task if exists, and set it to None.
        Nz@LLM task not cancelled, does your provider support cancellation?)ra   donecancelwarningswarn)r*   	cancelleds     r    rq   z8NavigableAutoSuggestFromHistory._cancel_running_llm_task3  s     >%~""$$ !%--//I &!% V     &% r"   c                 ^    | j          | j        r|                                 | _         | j         S )zLazy-initialized instance of the LLM provider.

        Do not use in the constructor, as `_init_llm_provider` can trigger slow side-effects.
        )rc   rb   )r*   s    r    _llm_providerz-NavigableAutoSuggestFromHistory._llm_providerC  s2     &.43J.*.*A*A*C*CD'**r"   c                 2   K   	 ddl }n# t          $ r d}Y nw xY w j        st          j        d           dS |t          j        d                                              fd}t          j         ||                     _         j         d{V  dS )z
        This will ask the current llm provider a suggestion for the current buffer.

        If there is a currently running llm task, it will cancel it.
        r   N5No LLM provider found, cannot trigger LLM completionsz;LLM Completion requires `jupyter_ai_magics` to be installedc                    K   	                      |            d{V  dS # t          $ r-}t                      j                            d|            d}~ww xY w)z
            This catches and log any errors, as otherwise this is just
            lost in the void of the future running task.
            Nzerror %s)_trigger_llm_core	Exceptionr   logerror)r@   er*   s     r    error_catcherzCNavigableAutoSuggestFromHistory._trigger_llm.<locals>.error_catcher`  sw      
,,V44444444444   !''
A666s   " 
A(AA)	jupyter_ai_magicsModuleNotFoundErrorr   r   r   rq   asynciocreate_taskra   )r*   r@   r   r   s   `   r    _trigger_llmz,NavigableAutoSuggestFromHistory._trigger_llmM  s      	%$$$$$" 	% 	% 	% $	%! 	MQRRRF$MWXXX%%'''		 		 		 		 		 !,]]6-B-BCCns   
 c           
        K   	 ddl mc m} n# t          $ r d}Y nw xY w|st	          d          | j        st	          d          |j        j        j        }| 	                    |          }t                      j                            d|           | xj        dz  c_        | j        }|                    |||j        j        z   |j        j        dddd	d
          }| j                            |          2 3 d{V }| j        |k    r dS t'          ||j                  rot+          |j        j                  dk    rt	          d          t1          |j        j        d         j                  |_        |j                                         t'          ||j                  r7t1          |j        j                  |_        |j                                         6 dS )aF  
        This is the core of the current llm request.

        Here we build a compatible `InlineCompletionRequest` and ask the llm
        provider to stream it's response back to us iteratively setting it as
        the suggestion on the current buffer.

        Unlike with JupyterAi, as we do not have multiple cells, the cell id
        is always set to `None`.

        We set the prefix to the current cell content, but could also insert the
        rest of the history or even just the non-fail history.

        In the same way, we do not have cell id.

        LLM provider may return multiple suggestion stream, but for the time
        being we only support one.

        Here we make the assumption that the provider will have
        stream_inline_completions, I'm not sure it is the case for all
        providers.
        r   Nzjupyter-ai is not installedr   z
prefix: %sr   ztext/x-pythonTpython)numberprefixsuffixmimestreampathlanguagecell_idzBTerminal IPython cannot deal with multiple LLM suggestions at once)jupyter_ai.completions.modelscompletionsmodelsr   
ValueErrorr   r   shellhistory_managerrg   r   r   debugrk   InlineCompletionRequestr   text_before_cursortext_after_cursorstream_inline_completions
isinstanceInlineCompletionReplyrD   r   itemsr   
insertTextrA   on_suggestion_setfireInlineCompletionStreamChunkresponse)r*   r@   
jai_modelshmr   request_numberrequestreply_and_chunkss           r    r   z1NavigableAutoSuggestFromHistory._trigger_llm_coreo  sF     .	>>>>>>>>>>" 	 	 	JJJ	  	<:;;;! 	VTUUU^!1##B''f555!-44!FO>>?4  5 	
 	
 '+&8&R&R'
 '
 	0 	0 	0 	0 	0 	0 	0" #~55*J,LMM 0',233a77$\   %/$)/2=% %! (--////,j.TUU 0$./?/H/S$T$T!(--///#'
$ 	s   	 9G)r(   N))rV   rW   rX   rY   intr[   r   r   ra   r   Taskr   r   rg   r+   r   ro   rw   r}   r   r   r   r   r|   r\   r   r   rZ   r   r	   r   r   r   r   r   rq   propertyr   r   r   __classcell__)rl   s   @r    r^   r^      s          OOO-((((
 &*Iw|d"))) !4'''$J&&&55M8555! ! ! ! ! 4    J J J JTm T T T T T(0	*	   ! ! ! !''%*'5<'HL'	5e$dD0	1' ' ' 'RKK%*K5<K	5e$dD0	1K K K K

 
% 
' 
 
 
 

     w  4        "# 3  T    "     + + X+       DFf F F F F F F F Fr"   r^   eventc                 X  K   d}t                      j        }t          |t                    sdS | j        j        }t          d||j        z
  |j        z             }t          |          D ]}| j        
                    ddd            |                    | j                   d{V  dS )a  
    Ask the AutoSuggester from history to delegate to ask an LLM for completion

    This will first make sure that the current buffer have _MIN_LINES (7)
    available lines to insert the LLM completion

    Provisional as of 8.32, may change without warnings

       Nr   
F)move_cursor
fire_event)r   auto_suggestr   r^   current_bufferr   maxr=   r   rG   insert_textr   )r   
_MIN_LINESproviderdoclines_to_insertrm   s         r    llm_autosuggestionr     s       J}})Hh ?@@ 


'C!Z#.83;RRSSO?## T T((5U(SSSS


 4
5
5555555555r"   c                 4   | j         }|j        }|j        |j        d         }|                    d          }|d                                         }|j        }|)|j        r"|dk    r|                    |j                   dS t          j	        |            dS )z,Apply autosuggestion or jump to end of line.Nr   r   r0   )
r   r   r3   cursor_positionsplitrJ   rA   r   ncend_of_line)r   r@   dafter_cursorr   end_of_current_linerA   s          r    accept_or_jump_to_endr     s    !FA6!+--.Lt$$E(..**"JZ_;NRT;T;T:?+++++
ur"   c                     | j         }|j        }|r|                    |j                   dS t	          j        |            dS )zAccept autosuggestionN)r   rA   r   r3   r   forward_char)r   r@   rA   s      r    acceptr     sL    !F"J :?+++++
r"   c                 "    | j         }d|_        dS )zDiscard autosuggestionN)r   rA   )r   r@   s     r    discardr     s    !FFr"   c                     | j         }|j        }|rIt          j        d|j                  }|                    t          d |D             d                     dS t          j        |            dS )z#Fill partial autosuggestion by wordz(\S+\s+)c              3      K   | ]}||V  	d S r   r9   )r:   rf   s     r    r<   zaccept_word.<locals>.<genexpr>  s'       3 3q 3 3 3 3 3 3 3r"   r0   N)	r   rA   rer   r3   r   nextr   forward_word)r   r@   rA   ts       r    accept_wordr     sv    !F"J H[*/224 3 3A 3 3 3R8899999
r"   c                 |    | j         }|j        }|r)|j        r$|                    |j        d                    dS dS dS )z(Fill partial autosuggestion by characterr   N)r   rA   r3   r   )r   brA   s      r    accept_characterr     sU    AJ *jo *	joa()))))* * * *r"   c                 z    | j         }|j        }|j        }|r#|                    |j                   ||_        dS dS )z.Accept autosuggestion and keep cursor in placeN)r   r   rA   r   r3   )r   r@   old_positionrA   s       r    accept_and_keep_cursorr    sP    !F)L"J .:?+++!-. .r"   c                 L    t          |            t          j        |            dS )z3Accept autosuggestion and move cursor left in placeN)r  r   backward_charr   s    r    accept_and_move_cursor_leftr  	  s'    5!!!Ur"   r@   c                 f    | j         r)| j                             | | j                  }|| _        d S d S r   )r   r   r   rA   )r@   rA   s     r    _update_hintr	    s?     '(77PP
&' 'r"   c                 V    t          j        |            t          | j                   dS )z4Resume autosuggestions after deleting last characterN)r   backward_delete_charr	  r   r  s    r    backspace_and_resume_hintr    s*    E"""%&&&&&r"   c                 V    t          j        |            t          | j                   dS )zResume autosuggestionsN)r   replyr	  r   r  s    r    resume_hintingr    s,    u %&&&&&r"   c                 h    | j         }|                    | j                   t          |           dS )zGo up and update hintcountN)r   auto_upargr	  r   r   s     r    up_and_update_hintr  #  s7    )N+++     r"   c                 h    | j         }|                    | j                   t          |           dS )zGo down and update hintr  N)r   	auto_downr  r	  r  s     r    down_and_update_hintr  +  s7    )N59---     r"   c                    | j         }|j        }|rt          |j                  }||j        z   }g d}dg}d}t          t          |          j                  D ]}|j        t          j
        k    rt          |          }	n/|                    |d         t          |d                             }	|                    |d|	                    |d         }
|
                    |          rr|dk    rTt          |
          t          |          k    r4|
t          |          d         |d<   |                    |
           |dz  }|d         ||<   |dk    r n|dz  }|d         r_|d         }|d         r!t          |d                   dk    r|d         }|t          |          d         }|                    |           dS t!          j        |            dS )	z$Fill partial autosuggestion by token)NNNr0   r   r   r   N   )r   rA   r!   r   r3   r   r   readlinetypetokenizeNEWLINErD   indexry   r   r   r   r   )r   r   rA   r   r3   tokens
substringsrQ   tokenr!  tokenized_so_farr   	to_inserts                r    accept_tokenr'  3  s   AJ  AJ''
'&8&8&8T
$Xd^^%<== 	 	EzX---D		

58SB-@-@AAd6E6l+++)"~**622 66c"233c&kkAA 0V ?F1I%%&6777FA!!Hq	66EQ!9 	$R.Kay -S^^q00(n#CKKMM2IMM)$$$FOEr"   r   direction_methodc                     | j         }|sdS t          | j                  }||j        z   } |||| j                   |                    | | j                  }|| _         dS )a  
    We skip most recent history entry (in either direction) if it equals the
    current autosuggestion because if user cycles when auto-suggestion is shown
    they most likely want something else than what was suggested (otherwise
    they would have accepted the suggestion).
    N)r   r   r   )rA   r!   r   r3   r   r   )r@   r   r(  rA   r   currentnew_suggestions          r    _swap_autosuggestionr,  `  ss     "J v''Ejo%G5WfnMMMM,,VV_EEN&Fr"   c                     t                      }|j        }t          |t                    sdS t	          | j        ||j                  S )z%Get next autosuggestion from history.Nr@   r   r(  )r   r   r   r^   r,  r   r   r   r   r   s      r    swap_autosuggestion_upr0  x  sN    MME!Hh ?@@ #h   r"   c                     t                      }|j        }t          |t                    sdS t	          | j        ||j                  S )z)Get previous autosuggestion from history.Nr.  )r   r   r   r^   r,  r   r   r/  s      r    swap_autosuggestion_downr2    sP    MME!Hh ?@@ #!   r"   )?r   r   r  ior   typingr   r   r   r   r   r	   r
   r   r   rE   prompt_toolkit.bufferr   prompt_toolkit.key_bindingr   #prompt_toolkit.key_binding.bindingsr   r   prompt_toolkit.auto_suggestr   r   prompt_toolkit.documentr   prompt_toolkit.historyr   prompt_toolkit.shortcutsr    prompt_toolkit.layout.processorsr   r   r   IPython.core.getipythonr   IPython.utils.tokenutilr   filtersr   r!   r$   r^   r   r   r   r   r   r   r  r  r	  r  r  r  r  r'  Providerr,  r0  r2  r9   r"   r    <module>rA     s   				         S S S S S S S S S S S S S S S S S S S S      ( ( ( ( ( ( 4 4 4 4 4 4 D D D D D D J J J J J J J J , , , , , , * * * * * * 2 2 2 2 2 2          0 / / / / / 3 3 3 3 3 3 ! ! ! ! ! !8 8 8 8 8|6 |6 |6 |6 |6I |6 |6 |6~V V V V V&< V V Vr6M 6 6 6 6,    -    =    }    *M * * * *.- . . . .}    ' ' ' ' ''] ' ' ' ''- ' ' ' '!m ! ! ! !! ! ! ! !' ' ' ' 'T ')H$NO''-' ' ' ' '0
- 
 
 
 
M      r"   