
    m                         d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	m
Z
mZ ddlmZmZmZmZmZmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZ ddlmZ ddlm Z m!Z!m"Z"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/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z?m@Z@mAZAmBZB ddlCmDZD ddlEmFZG ddlHmIZImJZJmKZK ddlLmMZM ddlNmOZOmPZPmQZQ ddlRmSZSmTZTmUZU ddlVZVddlWZWddlXZXddlYZYddlZZZ	 ddl[m\Z] dd l^mJZ_  eP       rdd!lambZb dd"lcmdZd ndd#lemfZf d$Zgd8d&Zhd9d(Zid:d)Zjd* Zk G d+ d,e       Zl	 	 	 	 	 	 	 	 d;d/Zmd-d'd%d'd'ej                  d%d'dd'd'ddd.ddddddddd'dd'ddej                  ej                  ej                  d'd-f d0Zqd<d1Zr	 	 d=d2Zsd<d3Ztd4 Zud>d5Zvd9d6ZFd7 ZwerZxemZyeqZzy# e`$ r dZ]dZ_Y w xY w)?a  
Shortcuts for retrieving input from the user.

If you are using this library for retrieving some input from the user (as a
pure Python replacement for GNU readline), probably for 90% of the use cases,
the :func:`.prompt` function is all you need. It's the easiest shortcut which
does a lot of the underlying work like creating a
:class:`~prompt_toolkit.interface.CommandLineInterface` instance for you.

When is this not sufficient:
    - When you want to have more complicated layouts (maybe with sidebars or
      multiple toolbars. Or visibility of certain user interface controls
      according to some conditions.)
    - When you wish to have multiple input buffers. (If you would create an
      editor like a Vi clone.)
    - Something else that requires more customization than what is possible
      with the parameters of `prompt`.

In that case, study the code in this file and build your own
`CommandLineInterface` instance. It's not too complicated.
    )unicode_literals   )BufferAcceptAction)Document)DEFAULT_BUFFERSEARCH_BUFFEREditingMode)IsDoneHasFocusRendererHeightIsKnownto_simple_filterto_cli_filter	Condition)InMemoryHistory)CommandLineInterfaceApplicationAbortAction)load_key_bindings_for_prompt)Registry)Keys)WindowHSplitFloatContainerFloat)ConditionalContainer)BufferControlTokenListControl)LayoutDimension)PygmentsLexer)PromptMarginConditionalMargin)CompletionsMenuMultiColumnCompletionsMenu)PasswordProcessorConditionalProcessorAppendAutoSuggestionHighlightSearchProcessorHighlightSelectionProcessorDisplayMultipleCursors)DefaultPrompt)Char)ValidationToolbarSystemToolbar
ArgToolbarSearchToolbar)explode_tokens)print_tokens)DEFAULT_STYLEStylestyle_from_dict)Token)is_conemu_ansi
is_windowsDummyContext)	text_typeexec_PY2N)Lexer)r4   )Win32Output)ConEmuOutput)Vt100_Output)create_eventloopcreate_outputcreate_prompt_layoutcreate_prompt_applicationpromptprompt_asynccreate_confirm_applicationrun_applicationconfirmr2   clearTc                 T    t               rddlm}  || |      S ddlm}  ||       S )z
    Create and return an
    :class:`~prompt_toolkit.eventloop.base.EventLoop` instance for a
    :class:`~prompt_toolkit.interface.CommandLineInterface`.
    r   )Win32EventLoop)	inputhookrecognize_paste)PosixEventLoop)rM   )r8   prompt_toolkit.eventloop.win32rL   prompt_toolkit.eventloop.posixrO   )rM   recognize_win32_pasteLoops      +lib/third_party/prompt_toolkit/shortcuts.pyrA   rA   W   s(     |Ii9NOOIi((    Fc                 4   | xs t         j                  } t        |      }t               r t	               rt        |       S t        |       S t        j                  j                  dd      }t        r|j                  d      }t        j                  | |||      S )aw  
    Return an :class:`~prompt_toolkit.output.Output` instance for the command
    line.

    :param true_color: When True, use 24bit colors instead of 256 colors.
        (`bool` or :class:`~prompt_toolkit.filters.SimpleFilter`.)
    :param ansi_colors_only: When True, restrict to 16 ANSI colors only.
        (`bool` or :class:`~prompt_toolkit.filters.SimpleFilter`.)
    TERM zutf-8)
true_coloransi_colors_onlyterm)sys
__stdout__r   r8   r7   r?   r>   osenvirongetr<   decoder@   from_pty)stdoutrY   rZ   r[   s       rT   rB   rB   e   s     %s~~F!*-J|''v&&zz~~fb);;w'D$$z-D: 	:rU   c                 @    t               rddlm} nddlm}  ||       S )a:  
    Returns an asyncio :class:`~prompt_toolkit.eventloop.EventLoop` instance
    for usage in a :class:`~prompt_toolkit.interface.CommandLineInterface`. It
    is a wrapper around an asyncio loop.

    :param loop: The asyncio eventloop (or `None` if the default asyncioloop
                 should be used.)
    r   )Win32AsyncioEventLoop)PosixAsyncioEventLoop)r8   &prompt_toolkit.eventloop.asyncio_win32re   &prompt_toolkit.eventloop.asyncio_posixrf   )loopAsyncioEventLoops     rT   create_asyncio_eventlooprk      s     |ddD!!rU   c                 ,      fd} fd} fd}|||fS )a2  
    Take a `get_prompt_tokens` function and return three new functions instead.
    One that tells whether this prompt consists of multiple lines; one that
    returns the tokens to be shown on the lines above the input; and another
    one with the tokens to be shown at the first line of the input.
    c                 2     |       D ]  \  }}d|v s y y)N
TF )clitokencharget_prompt_tokenss      rT   has_before_tokensz2_split_multiline_prompt.<locals>.has_before_tokens   s%    ,S1KE4t| 2 rU   c                     g }d}t        t         |                   D ]$  \  }}|r|j                  d||f       |dk(  s#d}& |S )NFr   rn   Treversedr1   insert)rp   resultfound_nlrq   rr   rs   s        rT   beforez'_split_multiline_prompt.<locals>.before   sT    #N3DS3I$JKKE4a%/	 L
 rU   c                     g }t        t         |                   D ]!  \  }}|dk(  r |S |j                  d||f       # |S )Nrn   r   rv   )rp   ry   rq   rr   rs   s       rT   first_input_linez1_split_multiline_prompt.<locals>.first_input_line   sS    #N3DS3I$JKKE4t|  a%/	 L
 rU   ro   )rs   rt   r{   r}   s   `   rT   _split_multiline_promptr~      s"     f&666rU   c                   $     e Zd ZdZd fd	Z xZS )_RPromptz? The prompt that is displayed on the right side of the Window. c                 P    |xs d }t         t        |   t        |d             y )Nc                     g S Nro   )rp   s    rT   <lambda>z#_RPrompt.__init__.<locals>.<lambda>   s    rU   T)align_right)superr   __init__r   )self
get_tokens	__class__s     rT   r   z_RPrompt.__init__   s&    3N
h&ZT:	<rU   r   )__name__
__module____qualname____doc__r   __classcell__)r   s   @rT   r   r      s    E< <rU   r   rX      c                     t         t              sJ d       |t        |      sJ |t        |      sJ |t        |      sJ  r|rJ t        |      }t        |
      }
| fd}t	        |      \  }}}	 t
        rt        |t
              rt        |d      }t        t        d      t        t                    t               t        t               t        t              t!                z        t        t#               |      t%        t              g}|	r|j'                  |	       |j)                  t        t+        |      |
              |rdt-        t/        t1        |t3        dt4        j6                              t9        j:                  d      	      t!                t=               z  
      g}ng }fd}t?        tA        t?        t-        t/        t1        |      d      tC        |            t/        tE        ||d      |tG        tI        ||      |

      g|      g      tK        ddtM        ddt        t              | z              tK        ddtO        t        t              |z  d            tK        dddtQ        |            g      tS               tU               t-        tW               |
      t-        tY               |
      g|z         S # t        $ r Y Fw xY w)ab  
    Create a :class:`.Container` instance for a prompt.

    :param message: Text to be used as prompt.
    :param lexer: :class:`~prompt_toolkit.layout.lexers.Lexer` to be used for
        the highlighting.
    :param is_password: `bool` or :class:`~prompt_toolkit.filters.CLIFilter`.
        When True, display input as '*'.
    :param reserve_space_for_menu: Space to be reserved for the menu. When >0,
        make sure that a minimal height is allocated in the terminal, in order
        to display the completion menu.
    :param get_prompt_tokens: An optional callable that returns the tokens to be
        shown in the menu. (To be used instead of a `message`.)
    :param get_continuation_tokens: An optional callable that takes a
        CommandLineInterface and width as input and returns a list of (Token,
        text) tuples to be used for the continuation.
    :param get_bottom_toolbar_tokens: An optional callable that returns the
        tokens for a toolbar at the bottom.
    :param display_completions_in_columns: `bool` or
        :class:`~prompt_toolkit.filters.CLIFilter`. Display the completions in
        multiple columns.
    :param multiline: `bool` or :class:`~prompt_toolkit.filters.CLIFilter`.
        When True, prefer a layout that is more adapted for multiline input.
        Text after newlines is automatically indented, and search/arg input is
        shown below the input, instead of replacing the prompt.
    :param wrap_lines: `bool` or :class:`~prompt_toolkit.filters.CLIFilter`.
        When True (the default), automatically wrap long lines instead of
        scrolling horizontally.
    z Please provide a unicode string.c                 *    t         j                  fgS r   )r6   Prompt)_messages    rT   r   z&create_prompt_layout.<locals>.<lambda>   s    g'>&?rU   T)sync_from_start)preview_search )default_charr   )height)filterc                     r@| j                   s4| j                  }|j                         s|j                  t	              S t	               S )N)min)is_donecurrent_buffercomplete_while_typingcomplete_stater   )rp   buffreserve_space_for_menus     rT   
get_heightz(create_prompt_layout.<locals>.get_height!  sG     "#++%%D
 ))+t/B/B/N&+ABB  rU   )dont_extend_height)input_processorslexerr   )r   left_margins
wrap_lines   )
max_heightscroll_offsetextra_filter)xcursorycursorcontent)r   	show_metar   )righttophide_when_covering_contentr   )-
isinstancer:   callabler   r~   pygments_Lexer
issubclassr    	TypeErrorr&   r(   r   r	   r)   r'   r   r   r%   r*   extendappendr+   r   r   r   r,   r6   Toolbarr   exactr   r   r   r   r   r"   r!   r   r#   r$   r   r-   r.   r/   r0   )r   r   is_passwordr   rs   get_continuation_tokensget_rprompt_tokensget_bottom_toolbar_tokensdisplay_completions_in_columnsextra_input_processors	multiliner   rt   get_prompt_tokens_1get_prompt_tokens_2r   toolbarsr   s   `  `              rT   rC   rC      s   J gy)M+MM)$,9R0SSS$1B(CCC%2D)EEE-..%23Q%R"i(I ? 	  12 @*,?j?!%>E 	 %D9]#	% 	$%13Xn5MQWQYPY5YZ.0+>~.  67 0)*YJ8 9 !(#$=15c5==1IK+:+@+@+CE H9466	8 9 ! $()<=+/1 /0	 !)9# (,-  * *()<>UV#,"  *! 8 d"-%'()'/'?(F'F(GHI d"8'/'?'E(F$(*+ A1&'9:<#7/	
` 	 	Z\95]_i8o8p 	q8 8 8m  s   :#K 	K$#K$c                     |t        |	|
      }|rt        j                  }t        |      }t        |      }t              || z  }	 t        r%t        |t              rt        |j                        }t        t        | ||||ndt        fd      |||||||      t        |||xs
 t               ||||t        |      	      |xs t        ||||||d||      S # t        $ r Y vw xY w)a  
    Create an :class:`~Application` instance for a prompt.

    (It is meant to cover 90% of the prompt use cases, where no extreme
    customization is required. For more complex input, it is required to create
    a custom :class:`~Application` instance.)

    :param message: Text to be shown before the prompt.
    :param mulitiline: Allow multiline input. Pressing enter will insert a
                       newline. (This requires Meta+Enter to accept the input.)
    :param wrap_lines: `bool` or :class:`~prompt_toolkit.filters.CLIFilter`.
        When True (the default), automatically wrap long lines instead of
        scrolling horizontally.
    :param is_password: Show asterisks instead of the actual typed characters.
    :param editing_mode: ``EditingMode.VI`` or ``EditingMode.EMACS``.
    :param vi_mode: `bool`, if True, Identical to ``editing_mode=EditingMode.VI``.
    :param complete_while_typing: `bool` or
        :class:`~prompt_toolkit.filters.SimpleFilter`. Enable autocompletion
        while typing.
    :param enable_history_search: `bool` or
        :class:`~prompt_toolkit.filters.SimpleFilter`. Enable up-arrow parting
        string matching.
    :param lexer: :class:`~prompt_toolkit.layout.lexers.Lexer` to be used for
        the syntax highlighting.
    :param validator: :class:`~prompt_toolkit.validation.Validator` instance
        for input validation.
    :param completer: :class:`~prompt_toolkit.completion.Completer` instance
        for input completion.
    :param reserve_space_for_menu: Space to be reserved for displaying the menu.
        (0 means that no space needs to be reserved.)
    :param auto_suggest: :class:`~prompt_toolkit.auto_suggest.AutoSuggest`
        instance for input suggestions.
    :param style: :class:`.Style` instance for the color scheme.
    :param enable_system_bindings: `bool` or
        :class:`~prompt_toolkit.filters.CLIFilter`. Pressing Meta+'!' will show
        a system prompt.
    :param enable_open_in_editor: `bool` or
        :class:`~prompt_toolkit.filters.CLIFilter`. Pressing 'v' in Vi mode or
        C-X C-E in emacs mode will open an external editor.
    :param history: :class:`~prompt_toolkit.history.History` instance.
    :param clipboard: :class:`~prompt_toolkit.clipboard.base.Clipboard` instance.
        (e.g. :class:`~prompt_toolkit.clipboard.in_memory.InMemoryClipboard`)
    :param get_bottom_toolbar_tokens: Optional callable which takes a
        :class:`~prompt_toolkit.interface.CommandLineInterface` and returns a
        list of tokens for the bottom toolbar.
    :param display_completions_in_columns: `bool` or
        :class:`~prompt_toolkit.filters.CLIFilter`. Display the completions in
        multiple columns.
    :param get_title: Callable that returns the title to be displayed in the
        terminal.
    :param mouse_support: `bool` or :class:`~prompt_toolkit.filters.CLIFilter`
        to enable mouse support.
    :param default: The default text to be shown in the input buffer. (This can
        be edited by the user.)
    )enable_system_bindingsenable_open_in_editorr   c                             S r   ro   )rp   r   s    rT   r   z+create_prompt_application.<locals>.<lambda>  s    IKrU   )r   r   r   r   r   rs   r   r   r   r   r   r   )	enable_history_searchr   is_multilinehistory	validator	completerauto_suggestaccept_actioninitial_documentT)layoutbufferstyle	clipboardkey_bindings_registry	get_titlemouse_supportediting_modeerase_when_donereverse_vi_search_directionon_aborton_exit)r   r
   VIr   pygments_Styler   r5   stylesr   r   rC   r   r   r   r   r3   ) r   r   r   r   vi_moder   r   r   r   r   r   r   r   r   r   r   r   r   rs   r   r   r   r   r   r   r   r   r   r   r   r   defaults     `                              rT   rD   rD   k  s3   p $ <#9"7!9
 "~~
 --BC,-BC +I15J4JJj?#ELL1E
 ##>G>S$:YZ 78/$;1&?+I#9!# "7"7"1 1%'%g.

 $}3#!'$(E" "	  s   +C! !	C-,C-c                     |j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }t        | fi |}t        ||||||	      S )
a  
    Get input from the user and return it.

    This is a wrapper around a lot of ``prompt_toolkit`` functionality and can
    be a replacement for `raw_input`. (or GNU readline.)

    If you want to keep your history across several calls, create one
    :class:`~prompt_toolkit.history.History` instance and pass it every time.

    This function accepts many keyword arguments. Except for the following,
    they are a proxy to the arguments of :func:`.create_prompt_application`.

    :param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
            print statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
    :param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
    :param true_color: When True, use 24bit colors instead of 256 colors.
    :param refresh_interval: (number; in seconds) When given, refresh the UI
        every so many seconds.
    patch_stdoutFreturn_asyncio_coroutinerY   refresh_intervalr   	eventloopN)r   r   rY   r   r   )poprD   rH   )r   kwargsr   r   rY   r   r   applications           rT   rE   rE     s    * ::ne4L%zz*DeLL%0Jzz"4a8

;-I+G>v>K;!!9) rU   c                    t        | t              sJ |rt               }n|xs
 t               }t	        | |t        |            }r8dgfd}fd}|xj                  |z  c_        |xj                  |z  c_        |r|j                  d      n	t               }	|r3|	|t        d}
t        t        j                  d	      |
        |
d
          S 	 |	5  |j                         }ddd       t        t              r|j                  |j!                          S ||j!                          S # 1 sw Y   GxY w# |j!                          w xY w)a  
    Run a prompt toolkit application.

    :param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
            print statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
    :param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
    :param true_color: When True, use 24bit colors instead of 256 colors.
    :param refresh_interval: (number; in seconds) When given, refresh the UI
        every so many seconds.
    )rY   )r   r   outputFc                 p      fd}t        j                  |      }d|_        |j                          y )Nc                  h    d   s,t        j                          j                          d   s+y y )Nr   )timesleeprequest_redraw)rp   doner   s   rT   runz8run_application.<locals>.start_refresh_loop.<locals>.runF  s,    q'JJ/0&&( q'rU   )targetT)	threadingThreaddaemonstart)rp   r   tr   r   s   `  rT   start_refresh_loopz+run_application.<locals>.start_refresh_loopE  s*    )   ,AAHGGIrU   c                     dd<   y )NTr   ro   )rp   r   s    rT   stop_refresh_loopz*run_application.<locals>.stop_refresh_loopN  s    DGrU   T)raw)patch_contextrp   r   a  
        def prompt_coro():
            # Inline import, because it slows down startup when asyncio is not
            # needed.
            import asyncio

            @asyncio.coroutine
            def run():
                with patch_context:
                    result = yield from cli.run_async()

                if isinstance(result, Document):  # Backwards-compatibility.
                    return result.text
                return result
            return run()
        prompt_coroN)r   r   rk   rA   r   rB   on_starton_stoppatch_stdout_contextr9   r   r;   textwrapdedentr   textclose)r   r   r   rY   r   r   rp   r   r   r   exec_contextry   r   s       `       @rT   rH   rH   '  s8    k;///,.	3!1!3	 
35C w		 	**(( ;GC,,,6LNM  )6s$,.hoo   	" +|M*,,	  &(+{{ OO OO  OOs*   D; D/)#D; D; /D84D; ;Ec                 $    d|d<   t        | fi |S )zN
    Similar to :func:`.prompt`, but return an asyncio coroutine instead.
    Tr   )rE   )r   r   s     rT   rF   rF   z  s     *.F%&'$V$$rU   c                     t               }|j                  d      |j                  d      d               }|j                  d      |j                  d      |j                  t        j                        d                      }t	        | |      S )zF
    Create a confirmation `Application` that returns True/False.
    yYc                 ~    d| j                   j                  t           _        | j                   j	                  d       y )Nr  Trp   buffersr   r  set_return_valueevents    rT   r   z%create_confirm_application.<locals>._  s-     25		.).		""4(rU   nNc                 ~    d| j                   j                  t           _        | j                   j	                  d       y )Nr  Fr  r  s    rT   r   z%create_confirm_application.<locals>._  s-     25		.).		""5)rU   )r   )r   add_bindingr   ControlCrD   )r   registryr   s      rT   rG   rG     s     zH##)  ) ##$--(* )  * %WHMMrU   c                 R    t        | t              sJ t        |       }t        |      S )z(
    Display a confirmation prompt.
    )r   r:   rG   rH   )r   apps     rT   rI   rI     s)     gy)))
$W
-C3rU   c                 l    |t         }t        |t              sJ t        ||      }t	        || |       y)at  
    Print a list of (Token, text) tuples in the given style to the output.
    E.g.::

        style = style_from_dict({
            Token.Hello: '#ff0066',
            Token.World: '#884444 italic',
        })
        tokens = [
            (Token.Hello, 'Hello'),
            (Token.World, 'World'),
        ]
        print_tokens(tokens, style=style)

    :param tokens: List of ``(Token, text)`` tuples.
    :param style: :class:`.Style` instance for the color scheme.
    :param true_color: When True, use 24bit colors instead of 256 colors.
    :param file: The output file. This can be `sys.stdout` or `sys.stderr`.
    N)rY   rc   )r3   r   r4   rB   renderer_print_tokens)tokensr   rY   filer   s        rT   r2   r2     s6    ( }eU###j>F&&%0rU   c                  |    t               } | j                          | j                  dd       | j                          y)z
    Clear the screen.
    r   N)rB   erase_screencursor_gotoflush)outs    rT   rJ   rJ     s.     /COOAqIIKrU   )NT)NFNr   )rX   NFr   NNNNFNFT)rX   )FFFr   N)zConfirm (y or n) ){r   
__future__r   r   r   r   documentr   enumsr   r	   r
   filtersr   r   r   r   r   r   r   r   	interfacer   r   r   key_binding.defaultsr   key_binding.registryr   keysr   r   r   r   r   r   layout.containersr   layout.controlsr   r   layout.dimensionr   layout.lexersr    layout.marginsr!   r"   layout.menusr#   r$   layout.processorsr%   r&   r'   r(   r)   r*   layout.promptr+   layout.screenr,   layout.toolbarsr-   r.   r/   r0   layout.utilsr1   rendererr2   r  r   r3   r4   r5   rq   r6   utilsr7   r8   r9   sixr:   r;   r<   r^   r\   r  r   r   pygments.lexerr=   r   pygments.styler   ImportErrorterminal.win32_outputr>   terminal.conemu_outputr?   terminal.vt100_outputr@   __all__rA   rB   rk   r~   r   rC   EMACSRAISE_EXCEPTIONRETURN_DOCUMENTrD   rE   rH   rF   rG   rI   rJ   	get_inputcreate_default_layoutcreate_default_applicationro   rU   rT   <module>rH     s  * ( (  = = h h $ E E > *  9 9 3 < - ( ; E l  l (  X X ( ; 9 9  ; ; % % 	 
   66
 <243):8"& 7F<v < >C01IM,0378=@E$(hX  &&"#$#  $"&',#",,++"22ATn"L CH8<Pf%N, 18 	, 6 a  NNs   6F3 3	F?>F?