B
    \BS                 @   s  d Z ddlZddlZddl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lmZ dd	lmZmZmZmZmZmZmZmZmZmZmZmZ dd
lmZ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*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZAmBZB ddlCmDZD ddlEmFZF ddlGmHZHmIZImJZJ ddlKmLZLmMZM ddlNmOZO eP ZQG dd de=ZRe?jSd e?jTd!e?jUd"e?jVd#iZWe?jSd$e?jTd%e?jUd"e?jVd#iZXd&d' ZYx>d(D ]2ZZe[eeZZ\e\r>e]e\d)r>e\^ sd*Z_P qW d+Z_d,ej`kp^e_ ZaG d-d. d.eZbeceb edd/krebe f  dS )0z/IPython terminal interface using prompt_toolkit    N)warn)InteractiveShellInteractiveShellABC)io)input)toggle_set_term_titleset_term_title)
abbrev_cwd)BoolUnicodeDictIntegerobserveInstanceTypedefaultEnumUnionAnyvalidate)DEFAULT_BUFFEREditingMode)HasFocus	ConditionIsDone)PygmentsTokens)InMemoryHistory)ConditionalProcessor!HighlightMatchingBracketProcessor)
ColorDepth)patch_stdout)PromptSessionCompleteStyleprint_formatted_text)DynamicStylemerge_styles)style_from_pygments_clsstyle_from_pygments_dict)get_style_by_name)Style)Token   )TerminalPdbPdb)TerminalMagics)get_inputhook_name_and_func)PromptsClassicPromptsRichPromptDisplayHook)IPythonPTCompleterIPythonPTLexer)create_ipython_shortcutsc               @   s   e Zd ZdS )_NoStyleN)__name__
__module____qualname__ r:   r:   @lib/python3.7/site-packages/IPython/terminal/interactiveshell.pyr6   +   s    r6   z#0000ffz#0000ee boldz#cc0000z#bb0000 boldz#00cc00z#00bb00 boldc               C   sP   y
t jd S  tk
r   Y n tk
r8   td Y nX t jdkrHdS dS d S )NZEDITORzN$EDITOR environment variable is not pure ASCII. Using platform default editor.posixviZnotepad)osenvironKeyErrorUnicodeErrorr   namer:   r:   r:   r;   get_default_editor=   s    

rC   )stdinstdoutstderrisattyFTZIPY_TEST_SIMPLE_PROMPTc                   s  e Zd ZedddjddZdZdZee	ddjddZ
edd	 Zedd
djddZedddjddZedddjddZeedeedgddjddZeddd Zeddd Zededdd Zdd ZeddjddZedddjddZee ddjddZee d djddZ!e"e Z#e$d!d"d# Z%e$d$d%d& Z&edd'djddZ'ed(d)djddZ(e)d*d+d,d-jddZ*edd.djddZ+edd/djddZ,e-dd0djddZ.edd1djddZ/edd2djddZ0ed3d\d4d5Z1 fd6d7Z2d8d9 Z3d:d; Z4ed<d= Z5ed>d? Z6d@dA Z7dBdC Z8dDdE Z9dFdG Z: fdHdIZ; fdJdKZ< fdLdMZ=dNdO Z>dZ?e@fdPdQZAe@fdRdSZBdZCdTdU ZDdZEd]dVdWZFeGjHZIdXdY ZJdZKdZd[ ZL  ZMS )^TerminalInteractiveShell   zMNumber of line at the bottom of the screen to reserve for the completion menu)helpT)ZconfigNa  Use `raw_input` for the REPL, without completion and prompt colors.

            Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
            IPython own testing machinery, and emacs inferior-shell integration through elpy.

            This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
            environment variable is set, or the current terminal is not a tty.c             C   s   | j r
tS tS )N)simple_promptr-   r,   )selfr:   r:   r;   debugger_clsl   s    z%TerminalInteractiveShell.debugger_clsz
        Set to confirm when you try to exit IPython with an EOF (Control-D
        in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
        you can force a direct exit without any confirmation.emacsz5Shortcut style to use at the prompt. 'vi' or 'emacs'.FzQEnable mouse support in the prompt
(Note: prevents selecting text with the mouse)legacy)klasszThe name or class of a Pygments style to use for syntax
        highlighting. To see available styles, run `pygmentize -L styles`.editing_modec             C   sV   |d   dkrd|d< n|d   dkr2d|d< tt|d  rP|d   S | jS )NvalueZvimr=   r   rN   )lowerhasattrr   upperrQ   )rL   Zproposalr:   r:   r;   _validate_editing_mode   s    
z/TerminalInteractiveShell._validate_editing_modec             C   s   |j  }| jr|| j_d S )N)newrU   pt_apprQ   )rL   changeZu_moder:   r:   r;   _editing_mode   s    
z&TerminalInteractiveShell._editing_modehighlighting_stylecolorsc             C   s   |    d S )N)refresh_style)rL   rY   r:   r:   r;   _highlighting_style_changed   s    z4TerminalInteractiveShell._highlighting_style_changedc             C   s   |  | j| _d S )N)_make_style_from_name_or_clsr[   _style)rL   r:   r:   r;   r]      s    z&TerminalInteractiveShell.refresh_stylez0Override highlighting format for specific tokenszUse 24bit colors instead of 256 colors in prompt highlighting. If your terminal supports true color, the following command should print 'TRUECOLOR' in orange: printf "\x1b[38;2;255;100;0mTRUECOLOR\x1b[0m\n"z?Set the editor used by IPython (default to $EDITOR/vi/notepad).z6Class used to generate Prompt token for prompt_toolkitpromptsc             C   s
   |  | S )N)prompts_class)rL   r:   r:   r;   _prompts_default   s    z)TerminalInteractiveShell._prompts_defaultZdisplayhook_classc             C   s   t S )N)r2   )rL   r:   r:   r;   _displayhook_class_default   s    z3TerminalInteractiveShell._displayhook_class_defaultz$Automatically set the terminal titlezIPython: {cwd}ziCustomize the terminal title format.  This is a python format string. Available substitutions are: {cwd}.)columnmulticolumnreadlinelikezOptions for displaying tab completions, 'column', 'multicolumn', and 'readlinelike'. These options are for `prompt_toolkit`, see `prompt_toolkit` documentation for more information.rf   )rJ   Zdefault_valuezHighlight matching brackets.zEnable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. This is in addition to the F2 binding, which is always enabled.zProvide an alternative handler to be called when the user presses Return. This is an advanced option intended for debugging, which may be changed or removed in later releases.z:Allows to enable/disable the prompt toolkit history searchz9Display the current vi mode (when using vi editing mode).
term_titlec             C   s0   | j r$td t| jjt d ntd d S )NT)cwdF)rh   r   r   term_title_formatformatr	   )rL   rY   r:   r:   r;   init_term_title   s    z(TerminalInteractiveShell.init_term_titlec                s&   t t|   dg| j_d| jj_d S )Nz
text/plainF)superrH   init_display_formatterZdisplay_formatterZactive_typesZipython_display_formatterZenabled)rL   )	__class__r:   r;   rn      s    
z/TerminalInteractiveShell.init_display_formatterc       	         s    j r fdd}| _d S t }t }d}xB jj jddD ],\}}}| }|rB||krB|| |}qBW  	 j
 _t fdd _tt j }tf |||t d j jd	 j j jd

   _d S )Nc                 st   d dd  j D } t| g}d dd  j D }x* d |d dkrh|t| q@W d |S )N c             s   s   | ]}|d  V  qdS )r+   Nr:   ).0xr:   r:   r;   	<genexpr>   s    zSTerminalInteractiveShell.init_prompt_toolkit_cli.<locals>.prompt.<locals>.<genexpr>c             s   s   | ]}|d  V  qdS )r+   Nr:   )rq   rr   r:   r:   r;   rs      s    
r   Z
incomplete)joinra   in_prompt_tokensr   continuation_prompt_tokensZcheck_completeappend)Zprompt_textlinesprompt_continuation)rL   r:   r;   prompt   s    
z@TerminalInteractiveShell.init_prompt_toolkit_cli.<locals>.promptrp   T)Zinclude_latestc                  s    j S )N)r`   r:   )rL   r:   r;   <lambda>  s    zBTerminalInteractiveShell.init_prompt_toolkit_cli.<locals>.<lambda>)shellF)
rQ   key_bindingshistoryZ	completerenable_history_searchstyleZinclude_default_pygments_stylemouse_supportZenable_open_in_editorcolor_depth)rK   prompt_for_coder5   r   Zhistory_managerZget_tailZhistory_load_lengthrstripZappend_stringr_   r[   r`   r$   r   getattrr   rQ   rU   r!   r3   r   r   extra_open_editor_shortcutsr   _extra_prompt_optionsrX   )	rL   r{   r~   r   Z	last_cell__Z___ZcellrQ   r:   )rL   r;   init_prompt_toolkit_cli   s8    
z0TerminalInteractiveShell.init_prompt_toolkit_clic             C   sB  i }|dkr| j  }|dkr,td}t}n|dkrBt}td}n|dkrtd}|tjdtjd	tj	d
tj
jdtj
jdtj
jdtjdtjdtjdtjdi
 tjdkr|tjdtjdtjdtjdi n|dkrt}i }n
td|n4t|trt|}n|}tjdtjdtjdtjdi}|| j tt|t|g}|S )z
        Small wrapper that make an IPython compatible style from a style name

        We need that to add style for prompt ... etc.
        rO   ZlinuxZmonokaiZlightbgZpastieZneutralr   z#007700Z	noinheritz#BB6622z#2080D0zbold #2080D0z#009900z#ansibrightgreen boldz#990000z#ansibrightred boldntz#ansidarkgreenz#ansigreen boldz#ansidarkredz#ansired boldZnocolorzGot unknown colors: )r\   rS   r(   _style_overrides_linux_style_overrides_light_bgupdater*   NumberOperatorStringNameZFunctionZClassZ	NamespacePrompt	PromptNum	OutPromptOutPromptNumr>   rB   r6   
ValueError
isinstancestrhighlighting_style_overridesr%   r&   r'   )rL   Zname_or_clsZstyle_overridesrO   Z	style_clsr   r:   r:   r;   r_   &  sX    





z5TerminalInteractiveShell._make_style_from_name_or_clsc             C   s   t jt jt jd| j S )N)rf   re   rg   )r"   ZMULTI_COLUMNZCOLUMNZREADLINE_LIKEdisplay_completions)rL   r:   r:   r;   pt_complete_styleh  s    z*TerminalInteractiveShell.pt_complete_stylec             C   s   | j rtjS d S )N)
true_colorr   Z
TRUE_COLOR)rL   r:   r:   r;   r   p  s    z$TerminalInteractiveShell.color_depthc                s`    fdd}dt   j| fddd jttddttt  @ t fd	d@ d
g j	d	S )z\
        Return the current layout option for the current Terminal InteractiveShell
        c                  s   t  j S )N)r   ra   rv   r:   )rL   r:   r;   get_messagex  s    zCTerminalInteractiveShell._extra_prompt_options.<locals>.get_messageFc                s   t  j| S )N)r   ra   rw   )widthlinenoZis_soft_wrap)rL   r:   r;   r|     s    z@TerminalInteractiveShell._extra_prompt_options.<locals>.<lambda>Tz[](){})charsc                  s    j S )N)highlight_matching_bracketsr:   )rL   r:   r;   r|     s    )Z	processorfilter)	Zcomplete_in_threadZlexerZreserve_space_for_menumessagerz   Z	multilineZcomplete_styleZinput_processors	inputhook)
r4   space_for_menur   r   r   r   r   r   r   r   )rL   r   r:   )rL   r;   r   t  s    
z.TerminalInteractiveShell._extra_prompt_optionsc          	   C   sL   | j r| j }d | _ nd}tdd  | jjf d|i|  }W d Q R X |S )Nrp   T)rawr   )rl_next_inputr    rX   r{   r   )rL   r   textr:   r:   r;   r     s    
z(TerminalInteractiveShell.prompt_for_codec             C   s"   t jdkrd S dd l}|  d S )N)   rI   r   )sysversion_infowin_unicode_consoleenable)rL   r   r:   r:   r;   enable_win_unicode_console  s    
z3TerminalInteractiveShell.enable_win_unicode_consolec          	   C   sf   t jdkrd S |   dd l}|  t . tdt t	
t jt	_t	
t jt	_W d Q R X d S )N>   cliwin32r   ignore)r   platformr   coloramaZinitwarningscatch_warningssimplefilterDeprecationWarningr   ZIOStreamrE   rF   )rL   r   r:   r:   r;   init_io  s    

z TerminalInteractiveShell.init_ioc                s   t t|   | t d S )N)rm   rH   init_magicsZregister_magicsr.   )rL   )ro   r:   r;   r     s    z$TerminalInteractiveShell.init_magicsc                s8   t t|   tjdkr4xdD ]}| j|| qW d S )Nr<   )clearZmoreZlessZman)rm   rH   
init_aliasr>   rB   Zalias_managerZsoft_define_alias)rL   cmd)ro   r:   r;   r     s    

z#TerminalInteractiveShell.init_aliasc                s4   t t| j|| |   |   d| _t | _d S )NT)rm   rH   __init__r   rl   keep_runningr   debugger_history)rL   argskwargs)ro   r:   r;   r     s
    z!TerminalInteractiveShell.__init__c             C   s
   d| _ d S )NF)r   )rL   r:   r:   r;   ask_exit  s    z!TerminalInteractiveShell.ask_exitc             C   s   |t k	rtdtdd d| _xh| jrt| jdd y|  }W n0 tk
rn   | jrb| 	ddd	rj| 
  Y qX |r| j|dd
 qW d S )Nzcinteract `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.   )
stacklevelTrp   )endz#Do you really want to exit ([y]/n)?yn)Zstore_history)DISPLAY_BANNER_DEPRECATEDr   r   r   printZseparate_inr   EOFErrorconfirm_exitZ
ask_yes_nor   Zrun_cell)rL   display_bannercoder:   r:   r;   interact  s    z!TerminalInteractiveShell.interactc          
   C   s   |t k	rtdtdd xdzHy|   P W n4 tk
r\ } ztdt|j  W d d }~X Y nX W d t| drv| j	
  X qW d S )Nzcmainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.r   )r   z
%s escaped interact()

_eventloop)r   r   r   r   KeyboardInterruptr   typer7   rT   r   stop)rL   r   er:   r:   r;   mainloop  s    (
z!TerminalInteractiveShell.mainloopc             C   s   | j d k	r|  | d S )N)
_inputhook)rL   contextr:   r:   r;   r     s    
z"TerminalInteractiveShell.inputhookc             C   s&   |rt |\| _| _nd  | _| _d S )N)r/   active_eventloopr   )rL   Zguir:   r:   r;   
enable_gui  s    z#TerminalInteractiveShell.enable_guic             C   sb   | j s
dS | j }| jr<tt|d| jjjd t| n"d	dd |D }t||dd dS )z>Overridden from the parent class to use fancy rewriting promptNrp   )r   r   c             s   s   | ]\}}|V  qd S )Nr:   )rq   tsr:   r:   r;   rs     s    z>TerminalInteractiveShell.auto_rewrite_input.<locals>.<genexpr>)sep)
Zshow_rewritten_inputra   Zrewrite_prompt_tokensrX   r#   r   Zappr   r   ru   )rL   r   tokensr{   r:   r:   r;   auto_rewrite_input  s    


z+TerminalInteractiveShell.auto_rewrite_inputc             C   s0   |r| j | _t| | _ n| jr,| j| _ d| _dS )z+Switch prompts to classic for %doctest_modeN)ra   _prompts_beforer1   )rL   moder:   r:   r;   switch_doctest_mode  s    z,TerminalInteractiveShell.switch_doctest_mode)N)N)Nr7   r8   r9   r   tagr   rX   r   r
   _use_simple_promptrK   propertyrM   r   r   rQ   r   r   r   r)   r[   r   rV   r   rZ   r^   r]   r   r   r   rC   Zeditorr0   rb   r   ra   r   rc   rd   rh   rj   r   r   r   r   r   Zhandle_returnr   Zprompt_includes_vi_moderl   rn   r   r_   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z
system_rawsystemr   r   r   __classcell__r:   r:   )ro   r;   rH   Z   s   .B	
	rH   __main__)g__doc__r>   r   r   r   ZIPython.core.interactiveshellr   r   ZIPython.utilsr   ZIPython.utils.py3compatr   ZIPython.utils.terminalr   r   ZIPython.utils.processr	   Z	traitletsr
   r   r   r   r   r   r   r   r   r   r   r   Zprompt_toolkit.enumsr   r   Zprompt_toolkit.filtersr   r   r   Zprompt_toolkit.formatted_textr   Zprompt_toolkit.historyr   Z prompt_toolkit.layout.processorsr   r   Zprompt_toolkit.outputr   Zprompt_toolkit.patch_stdoutr    Zprompt_toolkit.shortcutsr!   r"   r#   Zprompt_toolkit.stylesr$   r%   Zprompt_toolkit.styles.pygmentsr&   r'   Zpygments.stylesr(   Zpygments.styler)   Zpygments.tokenr*   Zdebuggerr,   r-   Zmagicsr.   Zpt_inputhooksr/   ra   r0   r1   r2   Zptutilsr3   r4   Z	shortcutsr5   objectr   r6   r   r   r   r   r   r   rC   _namer   _streamrT   rG   Z_is_ttyr?   r   rH   registerr7   instancer   r:   r:   r:   r;   <module>   sl   8



   R

