
    Mh#             	         d Z ddlm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	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mZmZmZ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$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z< ddl=m>Z>m?Z? g dZ@ ejA        eB          ZC G d deD          ZE G d de          ZF G d d          ZG ejH        d          ZI G d d           ZJed!gdf         ZKed!geLf         ZM G d" d!          ZN ed#ed$eeedf         f         %          ZOd4d(ZP G d) d*eD          ZQd5d6d1ZRd5d6d2ZSd7d3ZTdS )8zU
Data structures for the Buffer.
It holds the text, cursor position, history, etc...
    )annotationsN)deque)Enum)wraps)AnyCallable	CoroutineIterableTypeVarcast   )get_app)run_in_terminal)AutoSuggest
Suggestion)FastDictCache)ClipboardData)CompleteEvent	Completer
CompletionDummyCompleterget_common_complete_suffix)Document)aclosing)FilterOrBool	to_filter)HistoryInMemoryHistory)SearchDirectionSearchState)	PasteModeSelectionStateSelectionType)Eventto_str)ValidationError	Validator)EditReadOnlyBufferBufferCompletionStateindentunindentreshape_textc                      e Zd ZdZdS )r(   z.Attempt editing of read-only :class:`.Buffer`.N__name__
__module____qualname____doc__     U/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/prompt_toolkit/buffer.pyr(   r(   6   s        4444r5   r(   c                      e Zd ZdZdZdZdZdS )ValidationStatezCThe validation state of a buffer. This is set after the validation.VALIDINVALIDUNKNOWNN)r0   r1   r2   r3   r9   r:   r;   r4   r5   r6   r8   r8   :   s#        IIEGGGGr5   r8   c                  P    e Zd ZdZ	 	 dddZddZddZddZedd            Z	dS )r*   z;
    Immutable class that contains a completion state.
    Noriginal_documentr   completionslist[Completion] | Nonecomplete_index
int | NonereturnNonec                4    || _         |pg | _        || _        d S N)r=   r>   r@   )selfr=   r>   r@   s       r6   __init__zCompletionState.__init__G   s+     "3 '," -r5   strc                j    | j         j         d| j        dt          | j                  d| j        dS )N(z, <z> completions, index=))	__class__r0   r=   lenr>   r@   rF   s    r6   __repr__zCompletionState.__repr__X   sb    .)  P  PD,B  P  PTM]I^I^  P  Pw{  xK  P  P  P  	Pr5   indexc                p    | j         r.|#d|cxk    rt          | j                   k     sn J || _        dS dS )z
        Create a new :class:`.CompletionState` object with the new index.

        When `index` is `None` deselect the completion.
        Nr   )r>   rM   r@   rF   rP   s     r6   go_to_indexzCompletionState.go_to_index[   s[      	(=A$F$F$F$FT5E1F1F$F$F$F$F$F$F"'D	( 	(r5   tuple[str, int]c                8   | j         | j        j        | j        j        fS | j        j        }| j        j        }| j        | j                  }|j        dk    r|}n|d|j                 }||j        z   |z   }t          |          t          |j                  z   }||fS )zM
        Return (new_text, new_cursor_position) for this completion.
        Nr   )	r@   r=   textcursor_positiontext_before_cursortext_after_cursorr>   start_positionrM   )rF   original_text_before_cursororiginal_text_after_cursorcbeforenew_textnew_cursor_positions          r6   new_text_and_positionz%CompletionState.new_text_and_positione   s     &).0F0VVV*.*@*S')-)?)Q& !45A1$$445Gq7G5GH)CCH"%f++AF";000r5   Completion | Nonec                8    | j         | j        | j                  S dS )zi
        Return the current completion, or return `None` when no completion is
        selected.
        N)r@   r>   rN   s    r6   current_completionz"CompletionState.current_completiony   s#     *#D$788tr5   )NN)r=   r   r>   r?   r@   rA   rB   rC   rB   rH   rP   rA   rB   rC   )rB   rT   )rB   rb   )
r0   r1   r2   r3   rG   rO   rS   ra   propertyrd   r4   r5   r6   r*   r*   B   s          04%)	- - - - -"P P P P( ( ( (1 1 1 1(    X  r5   r*   z(\s+|".*?"|'.*?')c                  &    e Zd ZdZ	 dddZddZdS )YankNthArgStatezT
    For yank-last-arg/yank-nth-arg: Keep track of where we are in the history.
    r    history_positionintnprevious_inserted_wordrH   rB   rC   c                0    || _         || _        || _        d S rE   )rl   ro   rn   )rF   rl   rn   ro   s       r6   rG   zYankNthArgState.__init__   s     !1&<#r5   c                P    | j         j         d| j        d| j        d| j        dS )Nz(history_position=z, n=z, previous_inserted_word=rK   )rL   r0   rl   rn   ro   rN   s    r6   rO   zYankNthArgState.__repr__   s_    .)  ^  ^T=R  ^  ^Z^Z`  ^  ^  ~B  ~Y  ^  ^  ^  	^r5   N)r   rj   rk   )rl   rm   rn   rm   ro   rH   rB   rC   re   )r0   r1   r2   r3   rG   rO   r4   r5   r6   ri   ri      sX         
 UW    ^ ^ ^ ^ ^ ^r5   ri   r)   c                     e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddd(Zdd)Z	 ddd,Zdd-Zdd/Zdd0Z	e
dd1            Zej        dd2            Ze
dd3            Zej        dd4            Ze
dd5            Zej        dd6            Zdd7Zdd8Ze
dd:            Zej        dd;            Zddd=Ze
dd>            Zddd@ZddEZddFZddIZdddLZdddMZdddNZdddOZ	 dddQZ	 dddRZdddSZdddTZdddWZ dddXZ!ddYZ"dd[Z#ddd]Z$	 ddd^Z%dd_Z&ddcZ'dddZ(ddfZ)ddiZ*ddjZ+ddlZ,dddmZ-dddnZ.dddqZ/dddrZ0e1j2        fdduZ3dddxZ4ddyZ5e6j7        dJfdd}Z8dddZ9dddZ:dddZ;	 	 	 dddZ<ddZ=ddZ>dddZ?ddZ@ddZA	 	 dddZBddZC	 	 dddZD	 	 dddZEddZFddZGddZHdddZIddZJ	 	 	 	 dddZKddZLddZMddZNddZOdS )r)   a  
    The core data structure that holds the text and cursor position of the
    current input line and implements all text manipulations on top of it. It
    also implements the history, undo stack and the completion state.

    :param completer: :class:`~prompt_toolkit.completion.Completer` instance.
    :param history: :class:`~prompt_toolkit.history.History` instance.
    :param tempfile_suffix: The tempfile suffix (extension) to be used for the
        "open in editor" function. For a Python REPL, this would be ".py", so
        that the editor knows the syntax highlighting to use. This can also be
        a callable that returns a string.
    :param tempfile: For more advanced tempfile situations where you need
        control over the subdirectories and filename. For a Git Commit Message,
        this would be ".git/COMMIT_EDITMSG", so that the editor knows the syntax
        highlighting to use. This can also be a callable that returns a string.
    :param name: Name for this buffer. E.g. DEFAULT_BUFFER. This is mostly
        useful for key bindings where we sometimes prefer to refer to a buffer
        by their name instead of by reference.
    :param accept_handler: Called when the buffer input is accepted. (Usually
        when the user presses `enter`.) The accept handler receives this
        `Buffer` as input and should return True when the buffer text should be
        kept instead of calling reset.

        In case of a `PromptSession` for instance, we want to keep the text,
        because we will exit the application, and only reset it during the next
        run.
    :param max_number_of_completions: Never display more than this number of
        completions, even when the completer can produce more (limited by
        default to 10k for performance).

    Events:

    :param on_text_changed: When the buffer text changes. (Callable or None.)
    :param on_text_insert: When new text is inserted. (Callable or None.)
    :param on_cursor_position_changed: When the cursor moves. (Callable or None.)
    :param on_completions_changed: When the completions were changed. (Callable or None.)
    :param on_suggestion_set: When an auto-suggestion text has been set. (Callable or None.)

    Filters:

    :param complete_while_typing: :class:`~prompt_toolkit.filters.Filter`
        or `bool`. Decide whether or not to do asynchronous autocompleting while
        typing.
    :param validate_while_typing: :class:`~prompt_toolkit.filters.Filter`
        or `bool`. Decide whether or not to do asynchronous validation while
        typing.
    :param enable_history_search: :class:`~prompt_toolkit.filters.Filter` or
        `bool` to indicate when up-arrow partial string matching is enabled. It
        is advised to not enable this at the same time as
        `complete_while_typing`, because when there is an autocompletion found,
        the up arrows usually browse through the completions, rather than
        through the history.
    :param read_only: :class:`~prompt_toolkit.filters.Filter`. When True,
        changes will not be allowed.
    :param multiline: :class:`~prompt_toolkit.filters.Filter` or `bool`. When
        not set, pressing `Enter` will call the `accept_handler`.  Otherwise,
        pressing `Esc-Enter` is required.
    Nrk   FT'  	completerCompleter | Noneauto_suggestAutoSuggest | NonehistoryHistory | None	validatorValidator | Nonetempfile_suffixstr | Callable[[], str]tempfilenamerH   complete_while_typingr   validate_while_typingenable_history_searchdocumentDocument | Noneaccept_handlerBufferAcceptHandler | None	read_only	multilinemax_number_of_completionsrm   on_text_changedBufferEventHandler | Noneon_text_inserton_cursor_position_changedon_completions_changedon_suggestion_setrB   rC   c                   t          |
          }
t          |          }t          |	          }	t          |          }t          |          }|pt                      | _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        || _        || _        d| _        |t!                      n|| _        d| _        t'          | |          | _        t'          | |          | _        t'          | |          | _        t'          | |          | _        t'          | |          | _        t3          t4          d          | _        |                                 | _        |                                 | _        |                                  | _!        d | _"        | #                    |           d S )Nr   
   )size)r   )$r   r   rt   rv   rz   r|   r~   r   r   r   r   r   r   r   r   
text_widthr   rx   _Buffer__cursor_positionr$   r   r   r   r   r   r   r   _document_cache_create_auto_suggest_coroutine_async_suggester_create_completer_coroutine_async_completer_create_auto_validate_coroutine_async_validator_load_history_taskreset)rF   rt   rv   rx   rz   r|   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                        r6   rG   zBuffer.__init__   s   0 !**? @ @ )*? @ @ )*? @ @i((	i((	"6n&6&6(". 	, &;"%:"%:""")B& 
 -4O(((!" /4D/.J.J-24-H-H9>,:
 :
' 6;4AW5X5X#05d<M0N0N
 (,,, 	
 !% C C E E $ @ @ B B $ D D F F @D 	

H
%%%%%r5   c                    t          | j                  dk     r| j        }n| j        d d         dz   }d| j        d|dt          |           dS )N      z...z<Buffer(name=z, text=z) at >)rM   rV   r   id)rF   rV   s     r6   rO   zBuffer.__repr__(  s[    ty>>B9DD9SbS>E)DMtyMM4MM4MMMMr5   append_to_historyboolc                   |r|                                   |pt                      }|j        | _        d| _        t
          j        | _        d| _        g | _	        d| _
        d| _        d| _        d| _        d| _        d| _        g | _        g | _        | j        | j                                         d| _        t)          |j        g          | _        d| _        dS )zR
        :param append_to_history: Append current input to history first.
        Nr   )r   r   rW   r   validation_errorr8   r;   validation_stateselection_statemultiple_cursor_positionspreferred_columncomplete_stateyank_nth_arg_statedocument_before_paste
suggestionhistory_search_text_undo_stack_redo_stackr   cancelr   rV   _working_lines_Buffer__working_index)rF   r   r   s      r6   r   zBuffer.reset0  s      	%""$$$)xzz!)!9 9=8G8O 7;
 57& -1 7; ;? 7;" .2 04  3524
 ".#**,,,"& +0*@*@ r5   c                      j         Td fd}t                                           |                       _         d	d} j                             |           dS dS )
a  
        Create task for populating the buffer history (if not yet done).

        Note::

            This needs to be called from within the event loop of the
            application, because history loading is async, and we need to be
            sure the right event loop is active. Therefor, we call this method
            in the `BufferControl.create_content`.

            There are situations where prompt_toolkit applications are created
            in one thread, but will later run in a different thread (Ptpython
            is one example. The REPL runs in a separate thread, in order to
            prevent interfering with a potential different event loop in the
            main thread. The REPL UI however is still created in the main
            thread.) We could decide to not support creating prompt_toolkit
            objects in one thread and running the application in a different
            thread, but history loading is the only place where it matters, and
            this solves it.
        NrB   rC   c                    K   j                                         2 3 d {V } j                            |            xj        dz  c_        26 d S )Nr   )rx   loadr   
appendleftr   )itemrF   s    r6   load_historyz;Buffer.load_history_if_not_yet_loaded.<locals>.load_history  sv      "&,"3"3"5"5 . . . . . . .$'224888((A-((( #6"5"5s   Afasyncio.Future[None]c                    	 |                                   dS # t          j        $ r Y dS t          $ r Y dS t          $ r t
                              d           Y dS w xY w)z
                Handle `load_history` result when either done, cancelled, or
                when an exception was raised.
                zLoading history failedN)resultasyncioCancelledErrorGeneratorExitBaseExceptionlogger	exception)r   s    r6   load_history_donez@Buffer.load_history_if_not_yet_loaded.<locals>.load_history_done  s    
?HHJJJJJ-    DD$    DD$ ? ? ? $$%=>>>>>>?s    A	A#AArB   rC   )r   r   rB   rC   )r   r   create_background_taskadd_done_callback)rF   r   r   s   `  r6   load_history_if_not_yet_loadedz%Buffer.load_history_if_not_yet_loadedq  s    * "*. . . . . .
 '.ii&F&F||~~&V&VD#? ? ? ?* #556GHHHHH= +*r5   valuec                    | j         }| j        }||         }|||<   t          |          t          |          k    rdS ||k    rdS dS )z=set text at current working_index. Return whether it changed.TF)working_indexr   rM   )rF   r   r   working_linesoriginal_values        r6   	_set_textzBuffer._set_text  s]    *+&}5',m$ u::^,,,, 4n$$4ur5   c                P    | j         }t          d|          | _         | j         |k    S )z/Set cursor position. Return whether it changed.r   )r   max)rF   r   original_positions      r6   _set_cursor_positionzBuffer._set_cursor_position  s*     2!$Q%):::r5   c                &    | j         | j                 S rE   )r   r   rN   s    r6   rV   zBuffer.text  s    "4#566r5   c                
   | j         t          |          k    rt          |          | _         |                                 rt                      |                     |          }|r|                                  d| _        dS dS )z
        Setting text. (When doing this, make sure that the cursor_position is
        valid for this text. text/cursor_position should be consistent at any time,
        otherwise set a Document instead.)
        N)rW   rM   r   r(   r   _text_changedr   rF   r   changeds      r6   rV   zBuffer.text  s     #e**,,#&u::D  >> 	'$&&&..'' 	,    (,D$$$	, 	,r5   c                    | j         S rE   )r   rN   s    r6   rW   zBuffer.cursor_position  s    %%r5   c                    t          |t                    sJ |t          | j                  k    rt          | j                  }|dk     rd}|                     |          }|r|                                  dS dS )z*
        Setting cursor position.
        r   N)
isinstancerm   rM   rV   r   _cursor_position_changedr   s      r6   rW   zBuffer.cursor_position  s    
 %%%%%% 3ty>>!!	NNE199E++E22 	,))+++++	, 	,r5   c                    | j         S rE   )r   rN   s    r6   r   zBuffer.working_index  s    ##r5   c                d    | j         |k    r$|| _         d| _        |                                  d S d S )Nr   )r   rW   r   rF   r   s     r6   r   zBuffer.working_index  sB    5((#(D  $%D       )(r5   c                `   d | _         t          j        | _        d | _        d | _        d | _        d | _        d | _        d | _	        | j
                                         | j        rI|                                 r7t                                          |                                            d S d S d S rE   )r   r8   r;   r   r   r   r   r   r   r   r   firerz   r   r   r   r   rN   s    r6   r   zBuffer._text_changed  s     $ / 7""&%)"# $ 	!!###
 > 	Fd88:: 	FII,,T-B-B-D-DEEEEE	F 	F 	F 	Fr5   c                p    d | _         d | _        d | _        d | _        | j                                         d S rE   )r   r   r   r   r   r   rN   s    r6   r   zBuffer._cursor_position_changed  sC     #"&%)" !% 	',,.....r5   r   c                @    | j         | j        | j        | j        f         S )z
        Return :class:`~prompt_toolkit.document.Document` instance from the
        current text, cursor position and selection state.
        )r   rV   rW   r   rN   s    r6   r   zBuffer.document+  s&     #It+T-AA
 	
r5   c                0    |                      |           dS )z
        Set :class:`~prompt_toolkit.document.Document` instance.

        This will set both the text and cursor position at the same time, but
        atomically. (Change events will be triggered only after both have been set.)
        N)set_documentr   s     r6   r   zBuffer.document5  s     	%     r5   bypass_readonlyc                    |s"|                                  rt                      |                     |j                  }|                     |j                  }|r|                                  d| _        |r|                                  dS dS )a3  
        Set :class:`~prompt_toolkit.document.Document` instance. Like the
        ``document`` property, but accept an ``bypass_readonly`` argument.

        :param bypass_readonly: When True, don't raise an
                                :class:`.EditReadOnlyBuffer` exception, even
                                when the buffer is read-only.

        .. warning::

            When this buffer is read-only and `bypass_readonly` was not passed,
            the `EditReadOnlyBuffer` exception will be caught by the
            `KeyProcessor` and is silently suppressed. This is important to
            keep in mind when writing key bindings, because it won't do what
            you expect, and there won't be a stack trace. Use try/finally
            around this function if you need some cleanup code.
        N)	r   r(   r   rV   r   rW   r   r   r   )rF   r   r   text_changedcursor_position_changeds        r6   r   zBuffer.set_document?  s    &  	'4>>#3#3 	'$&&& ~~ej11"&";";E<Q"R"R  	,   '+D$" 	,))+++++	, 	,r5   c                *    t          | j                  S )z?
        True when there is something handling accept.
        )r   r   rN   s    r6   is_returnablezBuffer.is_returnableb  s    
 D'(((r5   clear_redo_stackc                    | j         r?| j         d         d         | j        k    r#| j         d         d         | j        f| j         d<   n&| j                             | j        | j        f           |r	g | _        dS dS )zy
        Safe current state (input text and cursor position), so that we can
        restore it by calling undo.
        rj   r   N)r   rV   rW   appendr   )rF   r   s     r6   save_to_undo_stackzBuffer.save_to_undo_stackk  s      	G 0 4Q 749 D D$($4R$8$;T=Q#RDR  ##TY0D$EFFF  	"!D	" 	"r5   line_index_iteratorIterable[int]transform_callbackCallable[[str], str]c                    | j                             d          }|D ]'}	  |||                   ||<   # t          $ r Y $w xY wd                    |          S )a/  
        Transforms the text on a range of lines.
        When the iterator yield an index not in the range of lines that the
        document contains, it skips them silently.

        To uppercase some lines::

            new_text = transform_lines(range(5,10), lambda text: text.upper())

        :param line_index_iterator: Iterator of line numbers (int)
        :param transform_callback: callable that takes the original text of a
                                   line, and return the new text for this line.

        :returns: The new text.
        
)rV   split
IndexErrorjoin)rF   r   r   linesrP   s        r6   transform_lineszBuffer.transform_lines{  s{    * 	%% ) 	 	E11%,??e    yys   5
AAc                    | j         }|j        |                                z   }|j        |                                z   }|j        d|          ||j        ||                   z   |j        |d         z   | _        dS )z
        Apply the given transformation function to the current line.

        :param transform_callback: callable that takes a string and return a new string.
        N)r   rW   get_start_of_line_positionget_end_of_line_positionrV   )rF   r   r   abs        r6   transform_current_linezBuffer.transform_current_line  s     =$x'J'J'L'LL$x'H'H'J'JJM"1"  qs!3445mABB  				r5   from_toc                    ||k     sJ d                     | j        d|          || j        ||                   z   | j        |d         z   g          | _        dS )z
        Transform a part of the input string.

        :param from_: (int) start position.
        :param to: (int) end position.
        :param transform_callback: Callable which accepts a string and returns
            the transformed string.
        rk   N)r   rV   )rF   r  r  r   s       r6   transform_regionzBuffer.transform_region  sm     rzzzzGG	&5&!$$TYuRx%899:)BCC.!
 
			r5   r   countc                X    | xj         | j                            |          z  c_         d S Nr  )rW   r   get_cursor_left_positionrF   r  s     r6   cursor_leftzBuffer.cursor_left  s/     F FU F S SSr5   c                X    | xj         | j                            |          z  c_         d S r  )rW   r   get_cursor_right_positionr
  s     r6   cursor_rightzBuffer.cursor_right  s/     G Ge G T TTr5   c                    | j         p| j        j        }| xj        | j                            ||          z  c_        || _         dS )z7(for multiline edit). Move cursor to the previous line.r  r   N)r   r   cursor_position_colrW   get_cursor_up_positionrF   r  original_columns      r6   	cursor_upzBuffer.cursor_up  sW    /T4=3T D D/ !E !
 !
 	

 !0r5   c                    | j         p| j        j        }| xj        | j                            ||          z  c_        || _         dS )z3(for multiline edit). Move cursor to the next line.r  N)r   r   r  rW   get_cursor_down_positionr  s      r6   cursor_downzBuffer.cursor_down  sW    /T4=3T F F/ !G !
 !
 	

 !0r5   &go_to_start_of_line_if_history_changesc                (   | j         r|                     |           dS | j        j        dk    r|                     |           dS | j        sA|                     |           |r+| xj        | j                                        z  c_        dS dS dS )z
        If we're not on the first line (of a multiline input) go a line up,
        otherwise go back in history. (If nothing is selected.)
        r  r   N)	r   complete_previousr   cursor_position_rowr  r   history_backwardrW   r   rF   r  r  s      r6   auto_upzBuffer.auto_up  s      		S"""/////].22NNN'''''% 	S!!!... 6 S$$(P(P(R(RR$$$$	S 	SS Sr5   c                B   | j         r|                     |           dS | j        j        | j        j        dz
  k     r|                     |           dS | j        sA|                     |           |r+| xj        | j        	                                z  c_        dS dS dS )z
        If we're not on the last line (of a multiline input) go a line down,
        otherwise go forward in history. (If nothing is selected.)
        r  r   N)
r   complete_nextr   r  
line_countr  r   history_forwardrW   r   r  s      r6   	auto_downzBuffer.auto_down  s      		SU+++++].1IA1MMM5)))))% 	S  u --- 6 S$$(P(P(R(RR$$$$	S 	SS Sr5   c                   |dk    sJ d}| j         dk    rt| j        | j         |z
  | j                  }| j        d| j         |z
           | j        | j         d         z   }| j         t          |          z
  }t          ||          | _        |S )zj
        Delete specified number of characters before cursor and return the
        deleted text.
        r   rk   N)rW   rV   rM   r   r   )rF   r  deletedr_   r`   s        r6   delete_before_cursorzBuffer.delete_before_cursor  s    
 zzzz!##i 4u <t?S STG 	8D05889)D02234  #'"6W"E %X/BCCDMr5   c                    | j         t          | j                  k     rT| j        j        d|         }| j        d| j                  | j        | j         t          |          z   d         z   | _        |S dS )zT
        Delete specified number of characters and Return the deleted text.
        Nrk   )rW   rM   rV   r   rY   )rF   r  r&  s      r6   deletezBuffer.delete  sw     #di..00m5fuf=G	0D001)D03w<<?AABC I N2r5    	separatorc                    | j         j        sq| xj        | j                                         z  c_        |                                  | j         j        |z   | j         j                            d          z   | _        dS dS )zs
        Join the next line to the current one by deleting the line ending after
        the current line.
        r*  N)	r   on_last_linerW   r   r)  rX   rY   lstriprV   )rF   r+  s     r6   join_next_linezBuffer.join_next_line!  s    
 }) 		  DM$J$J$L$LL  KKMMM 0-188==> III		 		r5   c                   | j         sJ t          | j        | j         j        g          \  }}| j        d|         }| j        ||                                         }| j        |d         }fd|D             }t          |d                    |          z   |z   t          |d                    |dd                   z             dz
            | _	        dS )z*
        Join the selected lines.
        Nc                @    g | ]}|                     d           z   S r*  )r.  ).0lr+  s     r6   
<listcomp>z.Buffer.join_selected_lines.<locals>.<listcomp>A  s(    :::q#*:::r5   rk   rj   r   rV   rW   )
r   sortedrW   original_cursor_positionrV   
splitlinesr   r   rM   r   )rF   r+  r  r  r^   r   afters    `     r6   join_selected_lineszBuffer.join_selected_lines1  s     #### !4#7#PQ
 
	r 6E6"	%(#..00	"## ;:::E::: !"''%..(50ss)<)< <==A
 
 
r5   c                    | j         }|dk    rO| j        |dz
           }| j        |dz
           }| j        d|dz
           |z   |z   | j        |d         z   | _        dS dS )zA
        Swap the last two characters before the cursor.
           r   N)rW   rV   )rF   posr   r   s       r6   swap_characters_before_cursorz$Buffer.swap_characters_before_cursorI  so     "!88	#'"A	#'"A	)C!G),q014tyFDIII	 8r5   rP   c                z    |t          | j                  k     r"|| _        t          | j                  | _        dS dS )z1
        Go to this item in the history.
        N)rM   r   r   rV   rW   rR   s     r6   go_to_historyzBuffer.go_to_historyU  s@     3t*++++!&D#&ty>>D    ,+r5   disable_wrap_aroundc                   | j         ryt          | j         j                  }| j         j        d}n:| j         j        |dz
  k    rd}|rdS n t	          |dz
  | j         j        |z             }|                     |           dS dS )zd
        Browse to the next completions.
        (Does nothing if there are no completion.)
        Nr   r   )r   rM   r>   r@   mingo_to_completion)rF   r  rB  completions_countrP   s        r6   r!  zBuffer.complete_next]  s      	) #D$7$C D D"19$37H17LLL& F %)4+>+MPU+U  !!%(((((	) 	)r5   c                    | j         rt| j         j        dk    rd}|rdS nF| j         j        t          | j         j                  dz
  }nt	          d| j         j        |z
            }|                     |           dS dS )zh
        Browse to the previous completions.
        (Does nothing if there are no completion.)
        r   Nr   )r   r@   rM   r>   r   rE  )rF   r  rB  rP   s       r6   r  zBuffer.complete_previoust  s      	)"1Q66& F$3;D/;<<q@At2AEIJJ!!%(((((	) 	)r5   c                P    | j         r|                     d           d| _         dS dS )zB
        Cancel completion, go back to the original text.
        N)r   rE  rN   s    r6   cancel_completionzBuffer.cancel_completion  s;      	'!!$'''"&D	' 	'r5   r>   list[Completion]r*   c                x    t          | j        |          | _        | j                                         | j        S )z
        Start completions. (Generate list of completions and initialize.)

        By default, no completion will be selected.
        )r=   r>   )r*   r   r   r   r   )rF   r>   s     r6   _set_completionszBuffer._set_completions  sB     ."m
 
 

 	#((***""r5   c           
        t                      }g }| j        j                                        }t	          | j                  D ]\  }}t	          |                    d                    D ]\  }}|                                }|r|                    |          rn||vrj|	                    |           || j
        k    r	d|dz   z  }nd|dz    d|dz    }|                    t          |t          |           |                     |                     |ddd         	           |                     d
           dS )zj
        Start a completion based on all the other lines in the document and the
        history.
        r   zCurrent, line %sr   zHistory z, line )rV   rZ   display_metaNrj   r>   r   )setr   current_line_before_cursorr.  	enumerater   r   strip
startswithaddr   r   r   rM   rL  rE  )	rF   found_completionsr>   current_lineistringjr4  rN  s	            r6   start_history_lines_completionz%Buffer.start_history_lines_completion  sw   
 '*ee }?FFHH"4#677 	 	IAv!&,,t"4"455  1GGII l33  111)--a000  222+=Q+GLL+Ka!e+K+KAE+K+KL#**&%&03L0A0A/A-9    * 	+ddd*;<<<a     r5   rA   c                    | j         sJ | j         }|                    |           |                                \  }}t          ||          | _        || _         dS )zK
        Select a completion from the list of current completions.
        N)r   rS   ra   r   r   )rF   rP   stater_   r`   s        r6   rE  zBuffer.go_to_completion  sl     """" #%    ).(C(C(E(E%% +>?? $r5   
completionr   c                    | j         r|                     d           d| _         |                     |j                    |                     |j                   dS )z,
        Insert a given completion.
        N)r   rE  r'  rZ   insert_textrV   )rF   r^  s     r6   apply_completionzBuffer.apply_completion  sc    
  	(!!$'''" 	!!:#<"<===)))))r5   c                t    |                                  r| j        | j        j        | _        dS dS d| _        dS )zy
        Set `history_search_text`.
        (The text before the cursor will be used for filtering the history.)
        N)r   r   r   rX   rN   s    r6   _set_history_searchzBuffer._set_history_search  sL    
 %%'' 	,'/+/=+K((( 0/ (,D$$$r5   rX  c                ^    | j         du p$| j        |                             | j                   S )z
        True when the current entry matches the history search.
        (when we don't have history search, it's also True.)
        N)r   r   rT  )rF   rX  s     r6   _history_matcheszBuffer._history_matches  s9    
 '4/ 
43Fq3I3T3T$4
 4
 	
r5   c                F   |                                   d}t          | j        dz   t          | j                            D ]-}|                     |          r|| _        |dz  }d}|dk    r n.|r0d| _        | xj        | j                                        z  c_        dS dS )zl
        Move forwards through the history.

        :param count: Amount of items to move forward.
        Fr   Tr   N)	rc  ranger   rM   r   re  rW   r   r   rF   r  found_somethingrX  s       r6   r#  zBuffer.history_forward  s     	  """  t)A-s43F/G/GHH 	 	A$$Q'' '%&"
"&zz   	M#$D   DM$J$J$L$LL    	M 	Mr5   c                    |                                   d}t          | j        dz
  dd          D ]-}|                     |          r|| _        |dz  }d}|dk    r n.|rt	          | j                  | _        dS dS )z1
        Move backwards through history.
        Fr   rj   Tr   N)rc  rg  r   re  rM   rV   rW   rh  s       r6   r  zBuffer.history_backward  s     	  """  t)A-r266 	 	A$$Q'' '%&"
"&zz   	2#&ty>>D   	2 	2r5   rn   _yank_last_argc                   |t          |t                    sJ | j                                        }t	          |          sdS | j        t          |rdnd          }n| j        }|||_        |j        dz
  }| t	          |          k    rd}||         }d t          
                    |          D             }d |D             }	 ||j                 }n# t          $ r d}Y nw xY w|j        r'|                     t	          |j                             |                     |           ||_        ||_        || _        dS )ay  
        Pick nth word from previous history entry (depending on current
        `yank_nth_arg_state`) and insert it at current position. Rotate through
        history if called repeatedly. If no `n` has been given, take the first
        argument. (The second word.)

        :param n: (None or int), The index of the word from the previous line
            to take.
        Nrj   r   )rn   c                6    g | ]}|                                 S r4   )rS  r3  ws     r6   r5  z'Buffer.yank_nth_arg.<locals>.<listcomp>E  s     AAAqAAAr5   c                    g | ]}||S r4   r4   rn  s     r6   r5  z'Buffer.yank_nth_arg.<locals>.<listcomp>F  s    '''qQ''''r5   rk   )r   rm   rx   get_stringsrM   r   ri   rn   rl   _QUOTED_WORDS_REr   r   ro   r'  r`  )	rF   rn   rk  history_stringsr]  new_poslinewordswords	            r6   yank_nth_argzBuffer.yank_nth_arg$  s~    yJq#..yyy,2244?## 	F "*#N&AbbBBBEE+E=EG (1,8c/****G w'AA$4$:$:4$@$@AAA''E'''	>DD 	 	 	DDD	 ' 	I%%c%*F&G&GHHH (,$!("'s   	C C&%C&c                4    |                      |d           dS )zp
        Like `yank_nth_arg`, but if no argument has been given, yank the last
        word by default.
        T)rn   rk  N)rx  )rF   rn   s     r6   yank_last_argzBuffer.yank_last_argW  s#    
 	Ad33333r5   selection_typer#   c                :    t          | j        |          | _        dS )zR
        Take the current cursor position as the start of this selection.
        N)r"   rW   r   )rF   r{  s     r6   start_selectionzBuffer.start_selection^  s      .d.BNSSr5   _cutr   c                ^    | j                                         \  }}|r|| _         d| _        |S )a8  
        Copy selected text and return :class:`.ClipboardData` instance.

        Notice that this doesn't store the copied data on the clipboard yet.
        You can store it like this:

        .. code:: python

            data = buffer.copy_selection()
            get_app().clipboard.set_data(data)
        N)r   cut_selectionr   )rF   r~  new_documentclipboard_datas       r6   copy_selectionzBuffer.copy_selectionf  s9     (,}'B'B'D'D$n 	)(DM#r5   c                .    |                      d          S )zS
        Delete selected text and return :class:`.ClipboardData` instance.
        T)r~  )r  rN   s    r6   r  zBuffer.cut_selectiony  s     """---r5   data
paste_moder!   c                    t          |t                    sJ |t          j        t          j        t          j        fv sJ | j        }| j                            |||          | _        || _        dS )z5
        Insert the data from the clipboard.
        )r  r  N)	r   r   r!   	VI_BEFOREVI_AFTEREMACSr   paste_clipboard_datar   )rF   r  r  r  r=   s        r6   r  zBuffer.paste_clipboard_data  sw     $.....i193EyWWWWW M::Zu ; 
 
 &7"""r5   copy_marginc                |    |r$|                      d| j        j        z              dS |                      d           dS )z?
        Insert a line ending at the current position.
        r   N)r`  r   "leading_whitespace_in_current_line)rF   r  s     r6   newlinezBuffer.newline  sJ      	#TDM$TTUUUUUT"""""r5   c                    |r| j         j        dz   }nd}| xj        | j                                         z  c_        |                     |           | xj        dz  c_        dS )z:
        Insert a new line above the current one.
        r   r   N)r   r  rW   r   r`  rF   r  inserts      r6   insert_line_abovezBuffer.insert_line_above  sr      	]ELFFF H H J JJ   !r5   c                    |rd| j         j        z   }nd}| xj        | j                                         z  c_        |                     |           dS )z:
        Insert a new line below the current one.
        r   N)r   r  rW   r   r`  r  s      r6   insert_line_belowzBuffer.insert_line_below  s^      	DMLLFFF F F H HH     r5   	overwritemove_cursor
fire_eventc                   | j         }| j        }|rd|||t          |          z            }d|v r|d|                    d                   }|d|         |z   ||t          |          z   d         z   }n|d|         |z   ||d         z   }|r| j        t          |          z   }	n| j        }	t	          ||	          | _        |r| j                                         | j        rG| 	                                r3t                                          |                                            | j        r7t                                          |                                            dS dS dS )z
        Insert characters at cursor position.

        :param fire_event: Fire `on_text_insert` event. This is mainly used to
            trigger autocompletion while typing.
        r   N)rV   rW   rM   findr   r   r   r   rt   r   r   r   r   rv   r   )
rF   r  r  r  r  otextocposoverwritten_textrV   cposs
             r6   r`  zBuffer.insert_text  s    	$  		8  %UUSYY->%>?'''#34Q6F6K6KD6Q6Q4Q#R %=4'%<L8M8M0M0O0O*PPDD%=4'%-7D 	('#d))3DD'D !t,,  		J$$&&& ~ J$"<"<">"> J		001F1F1H1HIII   J		001F1F1H1HIIIII		J 		JJ Jr5   c                    | j         rn| j                                         \  }}|| j        k    r>| j                            | j        | j        f           t          ||          | _        d S | j         ld S d S )NrW   )r   poprV   r   r   rW   r   r   rF   rV   r>  s      r6   undozBuffer.undo  s    
  		(,,..ID#ty   ''D4H(IJJJ !)s C C C  		 		 		 		 		r5   c                    | j         rJ|                     d           | j                                         \  }}t          ||          | _        d S d S )NF)r   r  )r   r   r  r   r   r  s      r6   redozBuffer.redo  sc     	@##U#;;; (,,..ID#$T3???DMMM	@ 	@r5   
set_cursorc                   | j         t          j        k    r| j         t          j        k    S | j        r	 | j                            | j                   nl# t          $ r_}|r:t          t          d|j
                  t          | j                            | _
        t          j        | _         || _        Y d}~dS d}~ww xY wt          j        | _         d| _        dS )zv
        Returns `True` if valid.

        :param set_cursor: Set the cursor position, if an error was found.
        r   NFT)r   r8   r;   r9   rz   validater   r&   rD  r   rW   rM   rV   r:   r   )rF   r  es      r6   r  zBuffer.validate  s      O$;;;(O,AAA > 	''6666" 	 	 	 +.Aq0113ty>>, ,D( )8(?%()%uuuuu	 !0 5 $ts   A 
B<AB77B<c                  K   	 | j         t          j        k    rdS d}| j        }| j        rL	 | j                            | j                   d{V  n# t          $ r}|}Y d}~nd}~ww xY w| j        |k    rt|rt          j        | _         nt          j        | _         || _	        t                                                       )a  
        Asynchronous version of `validate()`.
        This one doesn't set the cursor position.

        We have both variants, because a synchronous version is required.
        Handling the ENTER key needs to be completely synchronous, otherwise
        stuff like type-ahead is going to give very weird results. (People
        could type input while the ENTER key is still processed.)

        An asynchronous version is required if we have `validate_while_typing`
        enabled.
        TN)r   r8   r;   r   rz   validate_asyncr&   r:   r9   r   r   
invalidate)rF   errorr   r  s       r6   _validate_asynczBuffer._validate_async"  s      	# $(??? E}H~ .77FFFFFFFFFF&   EEEEEE =H,,  >(7(?%%(7(=%$)D!II  """7	#s   %A 
A(A##A(c                    | j         rZ| j                                        }t          |          r|d         | j         k    r#| j                            | j                    dS dS dS )z:
        Append the current input to the history.
        rj   N)rV   rx   rq  rM   append_string)rF   rs  s     r6   r   zBuffer.append_to_historyL  sp     9 	6"l6688O'' 6?2+>$)+K+K**4955555	6 	6+K+Kr5   search_stater    include_current_positiontuple[int, int] | Nonec                    	
 |dk    sJ |j         |j        	|                                
d
	
 fd} j        } j        }t          |          D ]} |||          }| d	S |\  }}||j        fS )z
        Execute search. Return (working_index, cursor_position) tuple when this
        search is applied. Returns `None` when this text cannot be found.
        r   r   rm   r   r   rB   tuple[int, Document] | Nonec                |   t           j        k    r|                              }|| t          |j        |j        |z             fS t          | dz   t          j                  dz             D ]g}|t          j                  z  }t          j        |         d          }|                    d          }||t          |j        |          fc S hn|	                              }|| t          |j        |j        |z             fS t          | dz
  dd          D ]}|t          j                  z  }t          j        |         t          j        |                             }|	                              }|.|t          |j        t          |j                  |z             fc S dS )	zd
            Do search one time.
            Return (working_index, document) or `None`
            )r  ignore_caseNr   r   T)r  rj   )
r   FORWARDr  r   rV   rW   rg  rM   r   find_backwards)	r   r   	new_indexrX  	directionr  r  rF   rV   s	       r6   search_oncez#Buffer._search.<locals>.search_onceg  s    O333$MM-E + *  	 (% 0H90TUU  #=1#4c$:M6N6NQR6RSS K KS!4555#+D,?,BA#F#F$,MM 4[ %2 % %	 %0$%xy'I'I#JJJJ 1K %33Dk3RR	(% 0H90TUU  #=1#4b"==  S!4555#+ /2C8KA8N4O4O$ $ %-$;$; k %< % %	 %0 ! (HM8J8JY8V W W$    1
 4r5   N)r   rm   r   r   rB   r  )rV   r  r  r   r   rg  rW   )rF   r  r  r  r  r   r   _r   r  r  rV   s   ` `      @@@r6   _searchzBuffer._searchW  s     qyyyy  *	"..00:	 :	 :	 :	 :	 :	 :	 :	 :	 :	z *=u 	1 	1A [99F~tt*0'xxx788r5   c                    |                      |d          }|| j        S |\  }}|| j        k    r| j        }nd}t	          | j        |         ||          S )a#  
        Return a :class:`~prompt_toolkit.document.Document` instance that has
        the text/cursor position for this search, if we would apply it. This
        will be used in the
        :class:`~prompt_toolkit.layout.BufferControl` to display feedback while
        searching.
        T)r  N)	selection)r  r   r   r   r   r   )rF   r  search_resultr   rW   r  s         r6   document_for_searchzBuffer.document_for_search  sv     \DQQ = -:*M?  222 0		 	#M2Oy   r5   c                R    |                      |||          }|| j        S |\  }}|S )z
        Get the cursor position for this search.
        (This operation won't change the `working_index`. It's won't go through
        the history. Vi text objects can't span multiple items.)
        r  r  )r  rW   rF   r  r  r  r  r   rW   s          r6   get_search_positionzBuffer.get_search_position  sF     3KSX % 
 
  ''-:*M?""r5   c                d    |                      |||          }||\  }}|| _        || _        dS dS )zi
        Apply search. If something is found, set `working_index` and
        `cursor_position`.
        r  N)r  r   rW   r  s          r6   apply_searchzBuffer.apply_search  sU     3KSX % 
 
 $-:*M?!.D#2D    %$r5   c                    d | _         d S rE   )r   rN   s    r6   exit_selectionzBuffer.exit_selection  s    #r5   tuple[str, Callable[[], None]]c                    t          | j                  }t          j        |          \  }t	          j        || j                            d                     t	          j        |           dfd}|fS )za
        Simple (file) tempfile implementation.
        Return (tempfile, cleanup_func).
        utf-8rB   rC   c                 0    t          j                    d S rE   )osunlink)filenames   r6   cleanupz/Buffer._editor_simple_tempfile.<locals>.cleanup  s    Ihr5   r   )	r%   r|   r~   mkstempr  writerV   encodeclose)rF   suffix
descriptorr  r  s       @r6   _editor_simple_tempfilezBuffer._editor_simple_tempfile  s    
 ,--'/77
H
TY--g66777
	  	  	  	  	  	    r5   c                z   t          | j                  }|s|                                 S t          |          }t          j                            |          \  }}t          j                            |          r
|dd          }t          j                    |r t          j        	                    |          t	          j
                   t          j        	                    |          }t          |dd          5 }|                    | j                   d d d            n# 1 swxY w Y   dfd}||fS )	Nr   ro  r  )encodingrB   rC   c                 0    t          j                    d S rE   )shutilrmtree)dirpaths   r6   r  z0Buffer._editor_complex_tempfile.<locals>.cleanup  s    M'"""""r5   r   )r%   r~   r  rH   r  pathr   isabsmkdtempr   makedirsopenr  rV   )rF   headtailheadtailr  fhr  r  s          @r6   _editor_complex_tempfilezBuffer._editor_complex_tempfile  sk   $-(( 	2//111x== W]]8,,
d7== 	8D"$$ 	2gll7D11G
G 7<<..(C'222 	 bHHTY	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 	# 	# 	# 	# 	# 	#   s   D((D,/D,validate_and_handleasyncio.Task[None]c                                                      rt                       j        r                                 \  n                                 \  d fd}t                                           |                      S )ze
        Open code in editor.

        This returns a future, and runs in a thread executor.
        rB   rC   c                   K   	 t          fdd           d {V } | rt          d          5 }|                                                    d          }|                    d          r
|d d         }t          |t          |                    _        d d d            n# 1 swxY w Y   r                                               d S #               w xY w)	Nc                 .                                    S rE   )_open_file_in_editor)r  rF   s   r6   <lambda>z4Buffer.open_in_editor.<locals>.run.<locals>.<lambda>6  s    D55h?? r5   T)in_executorrbr  r   rj   r6  )	r   r  readdecodeendswithr   rM   r   r  )successr   rV   cleanup_funcr  rF   r  s      r6   runz"Buffer.open_in_editor.<locals>.run/  sa     
 !0?????T! ! !      
  3h-- W vvxxw77  ==.. -#'9D(0dCPTII(V(V(VW W W W W W W W W W W W W W W + 300222 s/   -C A*B(C (B,,C /B,0C C!r   )r   r(   r~   r  r  r   r   )rF   r  r  r  r  s   `` @@r6   open_in_editorzBuffer.open_in_editor   s     >> 	'$&&& = 	D%)%B%B%D%D"Hll%)%A%A%C%C"Hl	 	 	 	 	 	 	 	 	< yy//666r5   r  c                (   t           j                            d          }t           j                            d          }||dddddg}|D ]G}|rC	 t          j        t          j        |          |gz             }|dk    c S # t          $ r Y Cw xY wHd	S )
zc
        Call editor executable.

        Return True when we received a zero return code.
        VISUALEDITORz/usr/bin/editorz/usr/bin/nanoz/usr/bin/picoz/usr/bin/viz/usr/bin/emacsr   F)r  environget
subprocesscallshlexr   OSError)rF   r  visualeditoreditorsr  
returncodes          r6   r  zBuffer._open_file_in_editorO  s     )))) 	
  
	 
	A 	 ",Q8*1L!M!MJ%?***   D	 us   /B
BBselect_firstselect_lastinsert_common_partcomplete_eventCompleteEvent | Nonec           
         ||z   |z   dk    sJ t                                          |                     ||||pt          d                               dS )z
        Start asynchronous autocompletion of this buffer.
        (This will do nothing if a previous completion was still in progress.)
        r   T)completion_requested)r  r	  r
  r  N)r   r   r   r   )rF   r  r	  r
  r  s        r6   start_completionzBuffer.start_completions  s}     k),>>!CCCC		((!!)'#5-  < d;;; "  	
 	
 	
 	
 	
r5   (Callable[..., Coroutine[Any, Any, None]]c                D     ddt           	 	 	 	 dd fd            }|S )z
        Create function for asynchronous autocompletion.

        (This consumes the asynchronous completer generator, which possibly
        runs the completion algorithm in another thread.)
        r   r   r^  r   rB   r   c                d    | j         }|t          |          |j        z   d         }||j        k    S )z
            Return `True` if applying this completion doesn't have any effect.
            (When it doesn't insert any new text.
            N)rX   rM   rZ   rV   )r   r^  rX   replaced_texts       r6   completion_does_nothingzCBuffer._create_completer_coroutine.<locals>.completion_does_nothing  s@    
 "*!<.&''**CCEEM !JO33r5   FNr  r	  r
  r  r  rC   c                v  K   j         }|pt          d          }j        sj        sd S t	          j                   _        dfd}t          j                    dfd}t          j         |                      }	 t          j        	                    ||                    4 d {V 	 }|2 3 d {V }	j
                            |	                                             |            s n!t          j
                  j        k    r na6 	 d d d           d {V  n# 1 d {V swxY w Y   |                                 j                                         n2# |                                 j                                         w xY wj
        }
t          |
          d	k    r ||
d
                   r|
d d =  |            rj        rj        j        d S |
s"d _        j                                         d S | r                    d
           d S |r'                    t          |
          d	z
             d S |rt)          ||
          r\                               t          |
          d	k    r+fd|
D             |
d d <                       |
           d S d _        d S t          |
          d	k    r                    d
           d S d S d S j         j        |j        k    rd S j         j                            |j                  rt2          d S )NT)text_inserted)r=   rB   r   c                     j          k    S )ziKeep retrieving completions. Input text has not yet changed
                while generating completions.)r   )r   rF   s   r6   proceedzLBuffer._create_completer_coroutine.<locals>.async_completer.<locals>.proceed  s     *n<<r5   rC   c                    K   	 j                                                                            t          j        d           d{V                                    d{V  b)a  Background loop to refresh the UI at most 3 times a second
                while the completion are loading. Calling
                `on_completions_changed.fire()` for every completion that we
                receive is too expensive when there are many completions. (We
                could tune `Application.max_render_postpone_time` and
                `Application.min_redraw_interval`, but having this here is a
                better approach.)
                Tg333333?N)r   r   clearr   sleepwait)refresh_neededrF   s   r6   refresh_while_loadingzZBuffer._create_completer_coroutine.<locals>.async_completer.<locals>.refresh_while_loading  s~      0/44666"((***!-,,,,,,,,,(--/////////	0r5   r   r   c                T    g | ]$}|                     t                              %S r4   )new_completion_from_positionrM   )r3  r]   common_parts     r6   r5  zOBuffer._create_completer_coroutine.<locals>.async_completer.<locals>.<listcomp>  s?     . . .$% !" > >s;?O?O P P. . .r5   rO  rB   r   r   )r   r   r   rt   r*   r   r$   ensure_futurer   get_completions_asyncr>   r   rP  rM   r   r   r   r   r@   rE  r   r`  rL  rX   rT  _Retry)r  r	  r
  r  r   r  r  refresh_taskasync_generatorr^  r>   r!  r   r  r  rF   s              @@@r6   async_completerz;Buffer._create_completer_coroutine.<locals>.async_completer  s      }H+P}4/P/P/PN " $.  -t}MMMN"0D= = = = = = =
 %]__N0 0 0 0 0 0 0 #01F1F1H1HIIL3#N88>RR  " " " " " " " "$,; " " " " " " "j&299*EEE&**,,,  'wyy "!E   :;;#=> > "E> -<O" " " " " " " " " " " " " " " " " " " " " " " " " " "$ ##%%% +002222 ##%%% +002222(4K ;1$$)@)@+a.* *$  N wyy @! +*9EF # *.D' /44666F   5))!,,,,,  5))#k*:*:Q*>?????' 5"<X{"S"SK" 5((555{++a//. . . .)4. . .KN
 !11k1JJJJJ26D/// {++q00 11!4444435 50 10 =3x7RRRF=3>>/  ! !L! !s=   
.E0 9D1<DAD1E0 1
D;;E0 >D;?E0 0/F)r   r   r^  r   rB   r   FFFN
r  r   r	  r   r
  r   r  r  rB   rC   _only_one_at_a_time)rF   r(  r  s   ` @r6   r   z"Buffer._create_completer_coroutine  sj    		4 		4 		4 		4 
!& %',37	J	! J	! J	! J	! J	! J	! J	! 
	J	!X r5   'Callable[[], Coroutine[Any, Any, None]]c                .     t           d fd            }|S )zl
        Create function for asynchronous auto suggestion.
        (This can be in another thread.)
        rB   rC   c                    K   j         } j        sj        sd S j                            |            d {V }j         | k    r"|_        j                                         d S t          rE   )r   r   rv   get_suggestion_asyncr   r   r%  )r   r   rF   s     r6   async_suggestorz>Buffer._create_auto_suggest_coroutine.<locals>.async_suggestor3  s      }H  d&7 #0EEdHUUUUUUUUJ }((",&++----- r5   r   r+  )rF   r1  s   ` r6   r   z%Buffer._create_auto_suggest_coroutine-  s6     
	 	 	 	 	 
		$ r5   c                .     t           d fd            }|S )zv
        Create a function for asynchronous validation while typing.
        (This can be in another thread.)
        rB   rC   c                 @   K                                      d {V  d S rE   )r  rN   s   r6   async_validatorz?Buffer._create_auto_validate_coroutine.<locals>.async_validatorP  s1      &&(((((((((((r5   r   r+  )rF   r4  s   ` r6   r   z&Buffer._create_auto_validate_coroutineH  s6     
	) 	) 	) 	) 	) 
		) r5   c                    |                      d          }|rK| j        r|                     |           }nd}|                                  |s|                                  dS dS dS )z?
        Validate buffer and handle the accept action.
        T)r  FN)r  r   r   r   )rF   valid	keep_texts      r6   r  zBuffer.validate_and_handleV  s     ..  		" " //55		!	""$$$ 

		 		 r5   )NNNNrk   rk   rk   FFFNNFTrs   NNNNN)*rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r}   r   rH   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rm   r   r   r   r   r   r   r   r   r   r   rB   rC   re   )NF)r   r   r   r   rB   rC   r   )r   rH   rB   r   )r   rm   rB   r   )r   rH   rB   rC   )rB   rm   )r   rm   rB   rC   )rB   r   )r   r   rB   rC   )F)r   r   r   r   rB   rC   r"  )T)r   r   rB   rC   )r   r   r   r   rB   rH   )r   r   rB   rC   )r  rm   r  rm   r   r   rB   rC   r   )r  rm   rB   rC   )r   F)r  rm   r  r   rB   rC   )r  rm   rB   rH   r2  )r+  rH   rB   rC   )rP   rm   rB   rC   )r  rm   rB  r   rB   rC   )r>   rJ  rB   r*   rf   )r^  r   rB   rC   )rX  rm   rB   r   )rn   rA   rk  r   rB   rC   rE   )rn   rA   rB   rC   )r{  r#   rB   rC   )r~  r   rB   r   )rB   r   )r  r   r  r!   r  rm   rB   rC   )r  r   rB   rC   )FTT)
r  rH   r  r   r  r   r  r   rB   rC   )r  r   rB   r   )Fr   )r  r    r  r   r  rm   rB   r  )r  r    rB   r   )Tr   )r  r    r  r   r  rm   rB   rm   )r  r    r  r   r  rm   rB   rC   )rB   r  )r  r   rB   r  )r  rH   rB   r   r)  r*  )rB   r  )rB   r-  )Pr0   r1   r2   r3   rG   rO   r   r   r   r   rg   rV   setterrW   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r$  r'  r)  r/  r;  r?  rA  r!  r  rI  rL  r[  rE  ra  rc  re  r#  r  rx  rz  r#   
CHARACTERSr}  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  r4   r5   r6   r)   r)      s       9 9z '++/"&&*35,..3.3.3$(59"'"&).5948@D<@7;+O& O& O& O& O&bN N N N KP?! ?! ?! ?! ?!B3I 3I 3I 3In   (; ; ; ; 7 7 7 X7 
[, , , [,2 & & & X& , , , ," $ $ $ X$ ! ! ! !F F F F(/ / / /$ 
 
 
 X
 _! ! ! _!!, !, !, !, !,F ) ) ) X)" " " " "        @
 
 
 

 
 
 
*T T T T TU U U U U0 0 0 0 00 0 0 0 0 NSS S S S S& NSS S S S S$    ,         
 
 
 
 
0
G 
G 
G 
G2 2 2 2) ) ) ) )0 ;@) ) ) ) ),' ' ' '# # # #"! "! "! "!H$ $ $ $"* * * *	, 	, 	, 	,
 
 
 
M M M M M02 2 2 2 2*1( 1( 1( 1( 1(f4 4 4 4 4 /<.FT T T T T    &. . . . !*	7 7 7 7 7*# # # # #" " " " "
! 
! 
! 
! 
!   2J 2J 2J 2J 2Jh    @ @ @ @    >(# (# (# (#T	6 	6 	6 	6 */	V9 V9 V9 V9 V9p   8 *.	# # # # #0 *.	3 3 3 3 3&$ $ $ $! ! ! ! ! ! ! !:-7 -7 -7 -7 -7^" " " "L #!#(/3
 
 
 
 
0` ` ` `D   6        r5   _T.)bound	coroutinerB   c                l     dt                     d fd            }t          t          |          S )a  
    Decorator that only starts the coroutine only if the previous call has
    finished. (Used to make sure that we have only one autocompleter, auto
    suggestor and validator running at a time.)

    When the coroutine raises `_Retry`, it is restarted.
    Fr   r   kwrB   c                 n   K   rd S d	 	 	  | i | d {V  	 dd S # t           $ r Y !w xY w# dw xY w)NTF)r%  )r   r?  r=  runnings     r6   new_coroutinez*_only_one_at_a_time.<locals>.new_coroutinev  s      
  	F		  #)Q-"---------  GGG    H
 GOOOOs   0   
-0 -0 4)r   r   r?  r   rB   r   )r   r   r;  )r=  rB  rA  s   ` @r6   r,  r,  l  sS     G
9      ( M"""r5   c                      e Zd ZdZdS )r%  zRetry in `_only_one_at_a_time`.Nr/   r4   r5   r6   r%  r%    s        %%%%r5   r%  bufferfrom_rowrm   to_rowr  rC   c                @   | j         j        }| j         j        }t          ||          }d|z  |                     |fd          }t          |t          |                              |d                    | _         | xj        |t                    z   z  c_        dS )z3
    Indent text of a :class:`.Buffer` object.
        c                    | z   S rE   r4   )r4  indent_contents    r6   r  zindent.<locals>.<lambda>  s    NQ<N r5   r   N	r   r  r  rg  r   r   translate_row_col_to_indexrW   rM   )	rD  rE  rF  r  current_rowcurrent_col
line_ranger_   rJ  s	           @r6   r+   r+     s     /5K/5Kx((J e^N%%j2N2N2N2NOOH(8$$??QOO FO
 kC,?,???r5   c                F  	 | j         j        }| j         j        }t          ||          }d|z  	d	fd}|                     ||          }t          |t          |                              |d                    | _         | xj        |t          	          z
  z  c_        dS )	z5
    Unindent text of a :class:`.Buffer` object.
    rH  rV   rH   rB   c                    }|                      |          r| t          |          d          S |                                 S rE   )rT  rM   r.  )rV   removerJ  s     r6   	transformzunindent.<locals>.transform  s?    ??6"" 	!F&&;;== r5   r   N)rV   rH   rB   rH   rK  )
rD  rE  rF  r  rM  rN  rO  rS  r_   rJ  s
            @r6   r,   r,     s     /5K/5Kx((Je^N! ! ! ! ! ! %%j)<<H(8$$??QOO FO
 kC,?,???r5   c           	        | j                             d          }|d|         }||dz   d         }|||dz            }|rt          j        d|d                   }|r|                                nd}|d         d|                             dd          }	d                    |                                          }
| j        pdt          |	          z
  }|	g}d}|
D ]}|r`t          |          |z   dz   |k    r-|
                    d           |
                    |	           d}n|
                    d	           |dz  }|
                    |           |t          |          z  }|d
         dk    r|
                    d           t          d                    ||z   |z             t          d                    ||z                                 | _        dS dS )zi
    Reformat text, taking the width into account.
    `to_row` is included.
    (Vi 'gq' operator.)
    TNr   z^\s*r   r   rk   P   r*  rj   r6  )rV   r9  researchendreplacer   r   r   rM   r   r   r   )rD  rE  rF  r   lines_beforelines_afterlines_to_reformatmatchlengthr+   rv  widthreshaped_textcurrent_widthro  s                  r6   r-   r-     s    K""4((E(#L
%Kh!34 "
	'#4Q#788 %,1"1%gvg.66tR@@ )**0022 "(bCKK7 	$ 	$A 'q66M)A-55!((...!((000$%MM!((---!Q&M  ###SVV#MM$$  &&& #5CDD}(D E EFF
 
 
?"
 "
r5   )r=  r;  rB   r;  r8  )
rD  r)   rE  rm   rF  rm   r  rm   rB   rC   )rD  r)   rE  rm   rF  rm   rB   rC   )Ur3   
__future__r   r   loggingr  rV  r  r  r   r~   collectionsr   enumr   	functoolsr   typingr   r   r	   r
   r   r   application.currentr   application.run_in_terminalr   rv   r   r   cacher   	clipboardr   r^  r   r   r   r   r   r   r   	eventloopr   filtersr   r   rx   r   r   rW  r   r    r  r!   r"   r#   utilsr$   r%   
validationr&   r'   __all__	getLoggerr0   r   	Exceptionr(   r8   r*   compilerr  ri   BufferEventHandlerr   BufferAcceptHandlerr)   r;  r,  r%  r+   r,   r-   r4   r5   r6   <module>rv     s8   
 # " " " " "   				 				                          D D D D D D D D D D D D D D D D ( ( ( ( ( ( 8 8 8 8 8 8 1 1 1 1 1 1 1 1             $ $ $ $ $ $                          , , , , , , , , - - - - - - - - 0 0 0 0 0 0 0 0 ? ? ? ? ? ? ? ? ? ?                 2 2 2 2 2 2 2 2   
	8	$	$5 5 5 5 5 5 5 5    d   ? ? ? ? ? ? ? ?D 2:677 ^ ^ ^ ^ ^ ^ ^ ^  xj$./ z4/0 K K K K K K K K\6 WT#yc4'@"@ABBB# # # #D& & & & &Y & & &@ @ @ @ @&@ @ @ @ @6-
 -
 -
 -
 -
 -
r5   