B
    5d                 @   s  d Z ddlmZ ddlZddlZddlZddlmZ ddlmZ ddl	Z	ddl
mZ ddlZddlZddlZddlmZ ddl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"mZ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, ddl-m,Z. e./dZ0e0s8ddl1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA ddlBmCZC ddlDmEZE ddlFmGZGmHZH ddlImJZJ ddlKmLZL ddlMmNZNmOZO ddlPmQZQ ddlRmSZSmTZT dd lUmVZV dd!lWmXZX dd"lYmZZZ dd#l[m\Z\ dd$l]m^Z^ dd%l_m`Z` dd&lambZb dd'lcmdZdmeZe d2d(d)Zfd3d*d+Zgd,d- ZhG d.d/ d/e4ZiG d0d1 d1e&ZjdS )4zDIPython terminal interface using prompt_toolkit in place of readline    )print_functionN)getpass)BytesIO)Empty)TemporaryDirectory)warn)DictAny)ZMQError)page)	BoolIntegerFloatUnicodeListr   EnumInstancer	   )SingletonConfigurable   )ZMQCompleter)ZMQHistoryManager)__version__z3.)use_asyncio_event_loop)	Completer
Completion)Document)DEFAULT_BUFFEREditingMode)	Condition	has_focushas_selectionvi_insert_modeemacs_insert_modeis_done)InMemoryHistory)PromptSession)print_formatted_textCompleteStyle)KeyBindings)PygmentsLexer)ConditionalProcessor!HighlightMatchingBracketProcessor)merge_styles)style_from_pygments_clsstyle_from_pygments_dict)PygmentsTokens)
ColorDepth)suspend_to_background_supported)get_style_by_name)get_lexer_by_name)ClassNotFound)Token)run_syncensure_asyncc             C   s   ddddd}d}xv||  kryt| d  }|s:|}W q tk
rX   |rT|}Y q tk
r   ||  kr~|}t  n Y qX qW || S )a  Asks a question and returns a boolean (y/n) answer.

    If default is given (one of 'y','n'), it is used if the user input is
    empty. If interrupt is given (one of 'y','n'), it is used if the user
    presses Ctrl-C. Otherwise the question is repeated until an answer is
    given.

    An EOF is treated as the default answer.  If there is no default, an
    exception is raised to prevent infinite loops.

    Valid answers are: y/yes/n/no (match is not case sensitive).TF)ynyesnoN )keysinputlowerKeyboardInterruptEOFErrorprint)promptdefaultZ	interruptZanswersZans rE   d/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/jupyter_console/ptshell.py
ask_yes_noR   s     rG   c                s(   |dkrt  }|dt| I dH }|S )z:Simple async version of input using a the default executorN)asyncioget_event_looprun_in_executorr>   )rC   looprawrE   rE   rF   async_inputs   s    rM   c             C   st   |   } | dkr ddlm} |S | dkr8ddlm} |S y
t| jS  tk
rn   td|   ddlm	} |S X d S )NZipython2r   )IPythonLexerZipython3)IPython3Lexerz7No lexer found for language %r. Treating as plain text.)	TextLexer)
r?   ZIPython.lib.lexersrN   rO   r3   	__class__r4   r   Zpygments.lexers.specialrP   )namerN   rO   rP   rE   rE   rF   get_pygments_lexer|   s    
rS   c               @   s    e Zd ZdZdd Zdd ZdS )JupyterPTCompleterz7Adaptor to provide kernel completions to prompt_toolkitc             C   s
   || _ d S )N)jup_completer)selfrU   rE   rE   rF   __init__   s    zJupyterPTCompleter.__init__c       	      c   s   |j  sd S | jj|j|jd}|d }d|kry8i }x*t|d |d D ]\}}|d ||< qLW |}W n tk
r~   Y nX |d |j }x(|d D ]}t|||	|ddV  qW d S )	N)codeZ
cursor_posmetadataZ_jupyter_types_experimentalmatchestypeZcursor_start?)Zstart_positionZdisplay_meta)
current_linestriprU   Zcomplete_requesttextZcursor_positionzip	Exceptionr   get)	rV   documentZcomplete_eventcontentmetaZnew_metacm	start_posrE   rE   rF   get_completions   s*    

z"JupyterPTCompleter.get_completionsN)__name__
__module____qualname____doc__rW   ri   rE   rE   rE   rF   rT      s   rT   c                   s  e Zd ZU dZdZdZedZdZdZ	dZ
eddddZeddddZedd	dZeddd
dZeddddZeddddZeddddZeddddddZedddZedddZedddZedddgdddZeddddZeddddZed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)dd*Z&e%d+dd*Z'd,d- Z(e Z)d.d/ Z*edd0d!j!dd&Z+ fd1d2Z,d3d4 Z-d5d6 Z.d7d8 Z/dd9d:Z0d;d< Z1d=d> Z2d?d@ Z3dAdB Z4ddCdDZ5e6dEdF Z7i Z8e9e:e;f e<dG< dHdI Z=dJdK Z>dLdM Z?dNdO Z@dPdQ ZAdRdS ZBdTdU ZCdZDdVdW ZEddXdYZFdZd[ ZGd\d] ZHdd^d_ZIdd`daZJddbdcZKedddddZLededdfdZMdgdh ZNdidj ZOddkdlZPddmdnZQdodpdqdrZRdsdt ZSdudv ZTdwdx ZUdydz ZVd{d| ZWd}d~ ZXdddZY  ZZS )ZMQTerminalInteractiveShellFN emacsTz5Shortcut style to use at the prompt. 'vi' or 'emacs'.)confighelpz;The name of a Pygments style to use for syntax highlightingz0Override 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"i  z*How many history items to load into memoryz*Jupyter console {version}

{kernel_banner}zhText to display before the first prompt. Will be formatted with variables {version} and {kernel_banner}.<   a5  Timeout for giving up on a kernel (in seconds).

        On first connect and restart, the console tests whether the
        kernel is running and responsive by sending kernel_info_requests.
        This sets the timeout in seconds for how long the kernel can take
        before being presumed dead.
        )PILstreamtempfilecallablert   a2  
        Handler for image type output.  This is useful, for example,
        when connecting to the kernel in which pylab inline backend is
        activated.  There are four handlers defined.  'PIL': Use
        Python Imaging Library to popup image; 'stream': Use an
        external program to show the image.  Image will be fed into
        the STDIN of the program.  You will need to configure
        `stream_image_handler`; 'tempfile': Use an external program to
        show the image.  Image will be saved in a temporally file and
        the program is called with the temporally file.  You will need
        to configure `tempfile_image_handler`; 'callable': You can set
        any Python callable which is called with the image data.  You
        will need to configure `callable_image_handler`.
        )rq   
allow_nonerr   a6  
        Command to invoke an image viewer program when you are using
        'stream' image handler.  This option is a list of string where
        the first element is the command itself and reminders are the
        options for the command.  Raw image data is given as STDIN to
        the program.
        a  
        Command to invoke an image viewer program when you are using
        'tempfile' image handler.  This option is a list of string
        where the first element is the command itself and reminders
        are the options for the command.  You can use {file} and
        {format} in the string to represent the location of the
        generated image file and image format.
        a  
        Callable object called via 'callable' image handler with one
        argument, `data`, which is `msg["content"]["data"]` where
        `msg` is the message from iopub channel.  For example, you can
        find base64 encoded PNG data as `data['image/png']`. If your function
        can't handle the data supplied, it should return `False` to indicate
        this.
        z	image/pngz
image/jpegzimage/svg+xmlzt
        Preferred object representation MIME type in order.  First
        matched MIME type will be used.
        )default_valuerq   rr   zWhether to use the kernel's is_complete message
        handling. If False, then the frontend will use its
        own is_complete handler.
        r   a%  Timeout (in seconds) for giving up on a kernel's is_complete
        response.

        If the kernel does not respond at any point within this time,
        the kernel will no longer be asked if code is complete, and the
        console will default to the built-in is_complete test.
        zSet to display confirmation dialog on exit.
        You can always use 'exit' or 'quit', to force a
        direct exit without any confirmation.
        )rr   )columnmulticolumnreadlinelikezOptions for displaying tab completions, 'column', 'multicolumn', and 'readlinelike'. These options are for `prompt_toolkit`, see `prompt_toolkit` documentation for more information.r{   )rr   ry   )rq   z9Display the current vi mode (when using vi editing mode).zHighlight matching brackets.zjupyter_client.KernelManager)rx   zjupyter_client.KernelClientc             C   s   |j j | _d S )N)session
session_id)rV   rR   oldnewrE   rE   rF   _client_changedK  s    z+ZMQTerminalInteractiveShell._client_changedc             C   s   dj tdS )NzJupyter Console {version}
)version)formatr   )rV   rE   rE   rF   _banner1_defaultO  s    z,ZMQTerminalInteractiveShell._banner1_defaultz4Use simple fallback prompt. Features may be limited.c                sR   t t| jf | | g| _|   |   |   |   |   d| _	d| _
d S )NTr   )superrn   rW   configurablesinit_historyinit_completerinit_ioinit_kernel_infoinit_prompt_toolkit_clikeep_runningexecution_count)rV   kwargs)rQ   rE   rF   rW   V  s    z$ZMQTerminalInteractiveShell.__init__c             C   s   t | | j| jd| _dS )aN  Initialize the completion machinery.

        This creates completion machinery that can be used by client code,
        either interactively in-process (typically triggered by the readline
        library), programmatically (such as in test suites) or out-of-process
        (typically over the network by remote frontends).
        )rq   N)r   clientrq   r   )rV   rE   rE   rF   r   e  s    z*ZMQTerminalInteractiveShell.init_completerc             C   s    t | jd| _| j| j dS )zSets up the command history. )r   N)r   r   history_managerr   append)rV   rE   rE   rF   r   o  s    z(ZMQTerminalInteractiveShell.init_historyc             C   s:   t | dd dkr6| jr6dt| jjjjdd  d S dS )Nediting_modevi[      z] ro   )getattrprompt_includes_vi_modestrpt_cliappZvi_stateZ
input_mode)rV   rE   rE   rF   vi_modet  s     z#ZMQTerminalInteractiveShell.vi_modec             C   s:   |d kr| j }tj|  ftjdftjt|ftjdfgS )NzIn [z]: )r   r5   Promptr   	PromptNumr   )rV   ecrE   rE   rF   get_prompt_tokensz  s    z-ZMQTerminalInteractiveShell.get_prompt_tokensc             C   s   t jd|d  d fgS )Nr<      z...: )r5   r   )rV   widthrE   rE   rF   get_continuation_tokens  s    z3ZMQTerminalInteractiveShell.get_continuation_tokensc             C   s"   t jdft jt| jft jdfgS )NzOut[z]: )r5   	OutPromptOutPromptNumr   r   )rV   rE   rE   rF   get_out_prompt_tokens  s    z1ZMQTerminalInteractiveShell.get_out_prompt_tokensc             C   s$   |   }tt|d| jjjd d S )Nro   )endstyle)r   r&   r/   r   r   r   )rV   tokensrE   rE   rF   print_out_prompt  s    
z,ZMQTerminalInteractiveShell.print_out_promptc             C   s   t j| jfgS )N)r5   RemotePromptother_output_prefix)rV   rE   rE   rF   get_remote_prompt_tokens  s    z4ZMQTerminalInteractiveShell.get_remote_prompt_tokensc             C   s0   |   | j|d }tt|d| jjjd d S )N)r   ro   )r   r   )r   r   r&   r/   r   r   r   )rV   r   r   rE   rE   rF   print_remote_prompt  s    z/ZMQTerminalInteractiveShell.print_remote_promptc             C   s   t jt jt jd| j S )N)r{   rz   r|   )r'   ZMULTI_COLUMNZCOLUMNZREADLINE_LIKEdisplay_completions)rV   rE   rE   rF   pt_complete_style  s    z-ZMQTerminalInteractiveShell.pt_complete_stylekernel_infoc          
   C   s   | j }t }| jj  | j }xty| jjdd}W n< tk
rt } zt | |krdtd|W dd}~X Y q&X |d 	d|kr&|d | _dS q&W dS )z4Wait for a kernel to be ready, and store kernel infor   )timeoutz,Kernel didn't respond to kernel_info_requestNparent_headermsg_idrd   )
kernel_timeouttimer   Z
hb_channelZunpauser   Zget_shell_msgr   RuntimeErrorrb   )rV   r   Zticr   ZreplyerE   rE   rF   r     s    

z,ZMQTerminalInteractiveShell.init_kernel_infoc             C   s(   t | jjt| jdddddd d S )Nbannerro   )r   Zkernel_bannerT)r   flush)rB   r   r   r   r   rb   )rV   rE   rE   rF   show_banner  s    
z'ZMQTerminalInteractiveShell.show_bannerc                sx   j sdtjkr4 fdd}| _ fdd _d S t }ttB }|jdt	t
t @ |@ d fdd	}|jd
t	t
ddd	 }|jdt	t
ddd	 }|jdtdd ddd	 }|jdt	t
t@ ddd	 }t }d}x> jj jddD ](\}}}| }|r||kr|| qW tjdtjdtjdtjdtjdi} jrZt j}	n<td}	|tjdtjdtjdtjj dtjj!d tjj"d i | j# t$t%|	t&|g}
t't( j)* } j+,d!i }|,d"|,d#d$}t-t.d%d&t	t
t/ @ t fd'd@ d(g}t0s"t1  t2 fd)dd j3|t4t5| fd*d||t6 j7d|
| j8rjt9j:nd d+ _;d S ),NZJUPYTER_CONSOLE_TESTc                 s   d j  } t| I d H }|S )Nz	In [%d]: )r   rM   )rC   rL   )rV   rE   rF   rC     s    
zCZMQTerminalInteractiveShell.init_prompt_toolkit_cli.<locals>.promptc                  s   t d j ddS )Nz	Out[%d]: ro   )r   )rB   r   rE   )rV   rE   rF   <lambda>      zEZMQTerminalInteractiveShell.init_prompt_toolkit_cli.<locals>.<lambda>Zenter)filterc                sp   | j }|j}|js2|j|j|  ks2|  d S     |j	\}}|s^|j
r^|  n|d|  d S )N
)current_bufferrc   Zon_last_lineZcursor_position_row
line_countZempty_line_count_at_the_endnewlinehandle_iopubcheck_completer_   Zaccept_handlerZvalidate_and_handleinsert_text)eventbdmoreindent)rV   rE   rF   _  s    

z>ZMQTerminalInteractiveShell.init_prompt_toolkit_cli.<locals>._zc-cc             S   s   | j   d S )N)r   reset)r   rE   rE   rF   r     s    zc-\c             S   s   t d S )N)rA   )r   rE   rE   rF   r     s    zc-zc               S   s   t  S )N)r1   rE   rE   rE   rF   r     r   c             S   s   | j   d S )N)cliZsuspend_to_background)r   rE   rE   rF   r     s    zc-oc             S   s   | j d d S )Nr   )r   r   )r   rE   rE   rF   r     s    ro   T)Zinclude_latestz#009900z#00ff00 boldz#ff2200z#ff0000 boldz#999900rD   z#007700	noinheritz#BB6622z#2080D0zbold #2080D0Zlanguage_infoZpygments_lexerrR   r_   z[](){})charsc                  s    j S )N)highlight_matching_bracketsrE   )rV   rE   rF   r   %  r   )	processorr   c                  s   t   S )N)r/   r   rE   )rV   rE   rF   r   .  r   c                s   t  | S )N)r/   r   )r   linenoZis_soft_wrap)rV   rE   rF   r   4  s   )message	multilinecomplete_styler   lexerZprompt_continuationZkey_bindingshistory	completerZenable_history_searchr   input_processorsZcolor_depth)<simple_promptosenvironprompt_for_coder   r(   r!   r"   addr   r   r    r   r$   r   Zget_tailhistory_load_lengthrstripZappend_stringr5   r   r   r   r   r   highlighting_styler2   updateNumberOperatorStringNameFunctionClass	Namespacehighlighting_style_overridesr,   r-   r.   r   r   r   upperr   rb   r*   r+   r#   PTK3r   r%   r   r)   rS   rT   r   
true_colorr0   Z
TRUE_COLORr   )rV   rC   kbZinsert_moder   r   	last_cellcellZstyle_overridesZ	style_clsr   r   Zlanginfor   r   rE   )rV   rF   r     s|    "



z3ZMQTerminalInteractiveShell.init_prompt_toolkit_clic                sL   | j r| j }d | _ nd}tr2| jj|dI d H }n| jj|ddI d H }|S )Nro   )rD   T)rD   Zasync_)
next_inputr   r   Zprompt_asyncrC   )rV   rD   r_   rE   rE   rF   r   A  s    z+ZMQTerminalInteractiveShell.prompt_for_codec             C   s"   t jdkrd S dd l}|  d S )N>   r   win32r   )sysplatformcoloramainit)rV   r   rE   rE   rF   r   O  s    
z#ZMQTerminalInteractiveShell.init_ioc             C   sf   | j r:| j|}y| j|| jdS  tk
r6   dS X n(| }t|r^|d dk}|dfS dS d S )N)r   )Fro   ro   )use_kernel_is_completer   Zis_completehandle_is_complete_replykernel_is_complete_timeoutSyntaxError
splitlineslen)rV   rX   r   linesr   rE   rE   rF   r   V  s    
z*ZMQTerminalInteractiveShell.check_completec             C   s
   d| _ d S )NF)r   )rV   rE   rE   rF   ask_exitf  s    z$ZMQTerminalInteractiveShell.ask_exitc                sH   j rDj   fdd}tjdr8jjj| n|  d _ d S )Nc                  s   t  jjj_d S )N)r   r   r   bufferrc   rE   )srV   rE   rF   set_docs  s    z7ZMQTerminalInteractiveShell.pre_prompt.<locals>.set_docpre_run_callables)r   hasattrr   r   r  r   )rV   r  rE   )r  rV   rF   
pre_promptl  s    z&ZMQTerminalInteractiveShell.pre_promptc                sp   xj| j rjtddd y|  I d H }W n. tk
rT   | jrHtdddrP|   Y qX |r| j|dd qW d S )	Nr   ro   )r   z#Do you really want to exit ([y]/n)?r8   r9   T)store_history)r   rB   r   rA   confirm_exitrG   r   run_cell)rV   rK   Zdisplay_bannerrX   rE   rE   rF   interact}  s    z$ZMQTerminalInteractiveShell.interactc                s   t  }t | j|dg}| jr:|t | j|d t j|t jdI d H \}}x|D ]}|	  qZW yt j
| I d H  W n t jk
r   Y nX d S )N)rK   )return_when)rH   get_running_loopcreate_taskr	  include_other_outputr   handle_external_iopubwaitFIRST_COMPLETEDcancelgatherCancelledError)rV   rK   tasksr   pendingtaskrE   rE   rF   
_main_task  s    
z&ZMQTerminalInteractiveShell._main_taskc             C   s   | j  | _x6yt|   P W q tk
r<   td Y qX qW | jrR| j  | jrh| j shtd n2| jr| j rtd | j	
  ntd | j	
  d S )Nz&
KeyboardInterrupt escaped interact()
zkeeping kernel alivez#owning kernel, cannot keep it alivezShutting down kernel)
own_kernel
keepkernelrH   runr  r@   rB   
_eventloopcloser   shutdown)rV   rE   rE   rF   mainloop  s     


z$ZMQTerminalInteractiveShell.mainloopc          
   C   s  |r|  r|   dS x$t| jjj r<t| jjj  qW | j|| }d| _d| _	xx| j	dkr| j
 ry| j|dd W q\ tk
r   | | Y q\ tk
r } z|jtjkr W dd}~X Y q\X q\W x<| j
 ry| j|dd W n tk
r
   Y qX P qW d| _dS )a  Run a complete IPython cell.

        Parameters
        ----------
        cell : str
          The code (including IPython code such as %magic functions) to run.
        store_history : bool
          If True, the raw and translated cell will be stored in IPython's
          history. For user code calling back into IPython's machinery, this
          should be set to False.
        NTbusyidleg?)r   F)isspacer   r6   r   shell_channel	msg_readyget_msgexecute
_executing_execution_stateis_alivehandle_input_requestr   r
   errnoZEINTRhandle_execute_reply)rV   r   r  r   r   rE   rE   rF   r    s.    z$ZMQTerminalInteractiveShell.run_cellc       	      C   s   d|i}t | jjjf |}|d dd |kr| | |d }|d }|dkrbtjd d S |dkrxt|d	g D ]Z}|d
 }|dkrt		|d d  qx|dkr|d | _
qx|dkrx|dd| _|   qxW n|dkrt|d d | _d S )Nr   r   r   rd   statusZabortedzAborted
okpayloadsourcer   dataz
text/plainZset_next_inputr_   r   r  Ferrorr   r   )r6   r   r"  r$  rb   r   r   stdoutwriter   r   r  r   intr   )	rV   r   r   r   msgrd   r,  itemr/  rE   rE   rF   r+    s*    
z0ZMQTerminalInteractiveShell.handle_execute_replyc             C   s   d}y d|i}t | jjjf |}W n" tk
rF   td d| _dS X |d dd|krptdt|  dS |d	 d
d}|d	 dd}|dkrd|fS |dkrd|fS |dkrt	 n$|dkrd|fS td|  d|fS dS )aI  
        Wait for a repsonse from the kernel, and return two values:
            more? - (boolean) should the frontend ask for more input
            indent - an indent string to prefix the input
        Overloaded methods may want to examine the comeplete source. Its is
        in the self._source_lines_buffered list.
        Nr   z`The kernel did not respond to an is_complete_request. Setting `use_kernel_is_complete` to False.F)Fro   r   r   zBThe kernel did not respond properly to an is_complete_request: %s.rd   r,  r   ro   Zcomplete
incompleteTinvalidunknownz:The kernel sent an invalid is_complete_reply status: "%s".)
r6   r   r"  r$  r   r   r   rb   r   r   )rV   r   r   r5  r   r,  r   rE   rE   rF   r     s.    	z4ZMQTerminalInteractiveShell.handle_is_complete_replyzdWhether to include output from clients
        other than this one sharing the same kernel.
        zRemote zPrefix to add to outputs coming from clients other than this one.

        Only relevant if include_other_output is True.
        c             C   s   |d  d| j| jkS )z-Return whether a message is from this sessionr   r}   )rb   r~   )rV   r5  rE   rE   rF   	from_here7  s    z%ZMQTerminalInteractiveShell.from_herec             C   s4   |  |}|d dkr"| jo | S | jr,dS |S dS )z7Return whether we should include a given output messagemsg_typeexecute_inputTN)r:  r  )rV   r5  r:  rE   rE   rF   include_output;  s    
z*ZMQTerminalInteractiveShell.include_outputc                sF   x@| j r@t| jjjdI d H }|r.|   tdI d H  qW d S )Nr   g      ?)	r   r7   r   iopub_channelsocketpollr   rH   sleep)rV   rK   Zpoll_resultrE   rE   rF   r  G  s
    z1ZMQTerminalInteractiveShell.handle_external_iopubc             C   s  x t | jjj rt | jjj }|d d }|dkrPt|d d d | _| |r|dkrr|d d | _q|d	kr|d d
 dkr| j	rt
ddd d| _	t
|d d dd tj  nP|d d
 dkr | j	rt
dtjdd d| _	t
|d d tjdd tj  q|dkr| j	r:t
ddd d| _	t|d d | _| |sftj| j |d d }| | d|krqtj  tj  |   |d }d|krt
  t
| | |s tjd tj  |   q|dkrH|d d }| |}|s | |s0tj| j d|kr t
|d  q|dkr|d }|d| jd }	tjd tj  | j|	d tj|d d  q|dkr|d d rd| _	nt
ddd q|dkrx$|d d D ]}
t
|
tjd qW qW d S )!zProcess messages on the IOPub channel

           This method consumes and processes messages on the IOPub channel,
           such as stdout, stderr, execute_result and status.

           It only displays output that is caused by this session.
        headerr;  r<  rd   r   r   r,  Zexecution_stateru   rR   r2  ro   )r   Fr_   stderr)filer   Zexecute_resultr0  z
text/plainr   Zdisplay_data)r   rX   clear_outputr  Tr1  	traceback)rE  N)r6   r   r>  r#  r$  r4  r   r=  r'  _pending_clearoutputrB   r   r2  r   rD  r:  r3  r   handle_rich_datar   r   rb   )rV   r   Zsub_msgr;  Zformat_dictZ	text_reprr0  Zhandledrd   r   framerE   rE   rF   r   O  s    















z(ZMQTerminalInteractiveShell.handle_iopubZpngZjpegsvg)z	image/pngz
image/jpegzimage/svg+xmlc             C   s6   x0| j D ]&}||kr|| jkr| ||rdS qW dS )NTF)mime_preference
_imagemimehandle_image)rV   r0  mimerE   rE   rF   rI    s
    z,ZMQTerminalInteractiveShell.handle_rich_datac             C   s&   t | d| jd }|r"|||S d S )Nzhandle_image_{0})r   r   image_handler)rV   r0  rO  handlerrE   rE   rF   rN    s    z(ZMQTerminalInteractiveShell.handle_imagec             C   sb   |dkrdS yddl m}m} W n tk
r4   dS X t|| d}|t|}|	|S )N)z	image/pngz
image/jpegFr   )Image	ImageShowascii)
rt   rR  rS  ImportErrorbase64decodebytesencodeopenr   show)rV   r0  rO  rR  rS  rL   ZimgrE   rE   rF   handle_image_PIL  s    z,ZMQTerminalInteractiveShell.handle_image_PILc          	      st   t || d}| j| }t|d  fdd| jD }tj|tjtj	tj	d}|
| |jdkS Q R X d S )NrT  )r   c                s   g | ]}|j f  qS rE   )r   ).0r  )fmtrE   rF   
<listcomp>  s    zCZMQTerminalInteractiveShell.handle_image_stream.<locals>.<listcomp>)stdinr2  rD  r   )rV  rW  rX  rM  dictstream_image_handler
subprocessPopenPIPEDEVNULLcommunicate
returncode)rV   r0  rO  rL   imageformatargsprocrE   )r]  rF   handle_image_stream  s    



z/ZMQTerminalInteractiveShell.handle_image_streamc          
      s   t || d}| j| }d|}t h}tj||}t	|d}|
| W d Q R X t||d  fdd| jD }	tj|	tjtjd}
W d Q R X |
dkS )	NrT  ztmp.{0}wb)rE  r   c                s   g | ]}|j f  qS rE   )r   )r\  r  )r]  rE   rF   r^    s    zEZMQTerminalInteractiveShell.handle_image_tempfile.<locals>.<listcomp>)r2  rD  r   )rV  rW  rX  rM  r   r   r   pathjoinrY  r3  r`  tempfile_image_handlerrb  callre  )rV   r0  rO  rL   rh  filenametempdirfullpathfri  rcrE   )r]  rF   handle_image_tempfile  s    

z1ZMQTerminalInteractiveShell.handle_image_tempfilec             C   s   |  |}|dk	rd}|S )NFT)callable_image_handler)rV   r0  rO  resrE   rE   rF   handle_image_callable  s    
z1ZMQTerminalInteractiveShell.handle_image_callable皙?c          
      s  t | jjj|d}| | ||d dkrttj  fdd}ttj| |d }|ddrpt	nt
}zLy||d	 }W n6 tk
r   d
}Y n  tk
r   tjd dS X W dttj  X t | jjj st | jjj s| j
| dS )z% Method to capture raw_input
        )r   r   r   c                s    | | t d S )N)r@   )sigrJ  )real_handlerrE   rF   
double_int  s    
zDZMQTerminalInteractiveShell.handle_input_request.<locals>.double_intrd   passwordFrC   r   N)r6   r   Zstdin_channelr$  r   rb   signal	getsignalSIGINTr   r>   rA   r@   r   r2  r3  r#  r"  )rV   r   r   reqr}  rd   readZraw_datarE   )r|  rF   r)    s&    

z0ZMQTerminalInteractiveShell.handle_input_request)N)N)NN)T)N)N)N)ro   )rz  )[rj   rk   rl   Zreadline_user   r&  r   r'  rH  r  r  r   r   r   r   r   r   r   r   r   r   r   r   rP  r   ra  ro  r	   rw  rL  r   r   r  tagr   r   r   r   managerr   r   r~   r   r   rW   r   r   r   r   r   r   r   r   r   propertyr   r   DictTyper   AnyType__annotations__r   r   r   r   r   r   r   r   r  r	  r  r  r  r+  r   r  r   r:  r=  r  r   rM  rI  rN  r[  rk  rv  ry  r)  __classcell__rE   rE   )rQ   rF   rn      s   




 

3

&

d
rn   )NN)N)krm   
__future__r   rH   rV  r*  r   ior   r   queuer   r  rb  r   rv   r   r   warningsr   typingr   r  r	   r  Zzmqr
   ZIPython.corer   Z	traitletsr   r   r   r   r   r   r   Ztraitlets.configr   r   r   Z
zmqhistoryr   ro   r   Zprompt_toolkitZptk_version
startswithr   Z!prompt_toolkit.eventloop.defaultsr   Zprompt_toolkit.completionr   r   Zprompt_toolkit.documentr   Zprompt_toolkit.enumsr   r   Zprompt_toolkit.filtersr   r   r    r!   r"   r#   Zprompt_toolkit.historyr$   Zprompt_toolkit.shortcuts.promptr%   Zprompt_toolkit.shortcutsr&   r'   Zprompt_toolkit.key_bindingr(   Zprompt_toolkit.lexersr)   Z prompt_toolkit.layout.processorsr*   r+   Zprompt_toolkit.stylesr,   Zprompt_toolkit.styles.pygmentsr-   r.   Zprompt_toolkit.formatted_textr/   Zprompt_toolkit.outputr0   Zprompt_toolkit.utilsr1   Zpygments.stylesr2   Zpygments.lexersr3   Zpygments.utilr4   Zpygments.tokenr5   Zjupyter_console.utilsr6   r7   rG   rM   rS   rT   rn   rE   rE   rE   rF   <module>   sf   ,
 
!
	#