
    $Hea                     J   d Z ddlmZ ddlm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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 dZdZdZ dZ!dZ"dZ#ejH                  jK                  d      rdZ&ndZ& G d de      Z' G d de'      Z( G d de(      Z'y)zA FrontendWidget that emulates a repl for a Jupyter kernel.

This supports the additional functionality provided by Jupyter kernel.
    )
namedtuple)PopenN)warn)QtCoreQtGui)IPythonLexerIPython3Lexer)get_lexer_by_name)ClassNotFound)__version__)BoolUnicodeobservedefault   )FrontendWidget)stylesz/In [<span class="in-prompt-number">%i</span>]: z0Out[<span class="out-prompt-number">%i</span>]: 
 z&ipykernel.zmqshell.ZMQInteractiveShellwinnotepadc                       e Zd ZdZy)IPythonWidgetz4Dummy class for config inheritance. Destroyed below.N)__name__
__module____qualname____doc__     :/usr/lib/python3/dist-packages/qtconsole/jupyter_widget.pyr   r   1   s    >r   r   c                   4    e Zd ZdZ ed      Z ej                  ee      Z	 e
edd      Z e
dd      Z e
dd      Z e
dd      Z e
ed	      Z e
ed	      Z e
ed	      Z e
ed	      Z e
ed	      Z ed
g d      ZdZdZdZdZdZ dZ! fdZ"d Z# fdZ$d Z%d.dZ&d Z'd Z(d Z) fdZ*d Z+d Z,d Z-d/dZ.d Z/d Z0d0dZ1d/d Z2d1d!Z3d1d"Z4d1d#Z5d$ Z6d% Z7d& Z8d' Z9 e:d(      d/d)       Z; e:d*      d/d+       Z< e=d,      d-        Z> xZ?S )2JupyterWidgetz&A FrontendWidget for a Jupyter kernel.FTaN  
        A command for invoking a GUI text editor. If the string contains a
        {filename} format specifier, it will be used. Otherwise, the filename
        will be appended to the end the command. To use a terminal text editor,
        the command should launch a new terminal, e.g.
        ``"gnome-terminal -- vim"``.
        )confighelpa  
        The editor command to use when a specific line number is requested. The
        string should contain two format specifiers: {line} and {filename}. If
        this parameter is not specified, the line number option to the %edit
        magic will be ignored.
        a  
        A CSS stylesheet. The stylesheet can contain classes for:
            1. Qt: QPlainTextEdit, QFrame, QWidget, etc
            2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter)
            3. QtConsole: .error, .in-prompt, .out-prompt, etc
        z
        If not empty, use this Pygments style for syntax highlighting.
        Otherwise, the style sheet is queried for Pygments style
        information.
        )r#   _PromptBlock)blocklengthnumber
edit_magicask_exitset_next_inputpagec                    t        |   |i | | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  i| _
        d | _        d | _        | j                  r!| j                          | j                          n| j!                          d | _        d| _        y )NF)super__init___payload_source_edit_handle_payload_edit_payload_source_exit_handle_payload_exit_payload_source_page_handle_payload_page_payload_source_next_input_handle_payload_next_input_payload_handlers_previous_prompt_obj_keep_kernel_on_exitstyle_sheet_style_sheet_changed_syntax_style_changedset_default_stylelanguage_name_prompt_requested)selfargskw	__class__s      r    r/   zJupyterWidget.__init__r   s    $%"% %%(A(A%%(A(A%%(A(A++d.M.M	"P
 %)!$(! %%'&&(""$ "!&r   c                 \   | j                   j                  d|j                  dd             | j                         }| j                  j                  d      }|rR|j
                  |d   d   k(  r;|j                  | j                         k(  r|j                  | j                  k(  r|d   }|d   }|d   }|d	   }t        |d
      }t        ||      }| j                         }||k  r/|j                  t        j                  j                  ||z
         n3||kD  r.|j                  t        j                  j                  ||z
         | j                   j#                  |       ||z
  }	|j                  t        j                  j                  |	       | j%                  ||       yyyyy)z9Support Jupyter's improved completion machinery.
        zcomplete: %scontentr   completeparent_headermsg_idmatchescursor_start
cursor_endr   )nN)logdebugget_get_cursor_request_infoidpos_get_input_buffer_cursor_poscodeinput_buffermaxmovePositionr   QTextCursorLeftRight_controlsetTextCursor_complete_with_items)
rA   repcursorinforF   rJ   startend
cursor_posoffsets
             r    _handle_complete_replyz$JupyterWidget._handle_complete_reply   s    	~swwy"'=>!!#!!%%j1TWWO 4X >>HH A A CCII!2!22)nGi(GN+E,'CqMEc5/C ::<JZ##E$5$5$:$:'1C'7 $ :z!##E$5$5$;$;'*Z'7 $ : MM''/5[F  1 1 6 6&A%%fg61 3 D ?Dr   c                 d   |d   j                  d      }| j                  d   j                  |      }|rl|j                  dk(  r]d| _        |d   }|d   dk(  r| j	                          n|d	   d
z   }| j	                  |       | j                  d   j                  |       yt        |   |       y)z!Support prompt requests.
        rH   rI   executepromptFrF   statusabortedexecution_countr   N)rP   rR   kindr@   _show_interpreter_promptpopr.   _handle_execute_reply)rA   msgrI   rb   rF   r(   rD   s         r    rq   z#JupyterWidget._handle_execute_reply   s     _%))(3!!),008DII)%*D")nGx I---/ !23a7--f5y)--f5G)#.r   c                 B   |d   }d|vr| j                   j                  d|z         |j                  dd      dk(  ra| j                  sU| j                   j                  d       d| _        t	        j
                  d	       | j                  j                  d
d       yd| _        yd| _        |d   }| j                   j                  dt        |             g }d}|D ]/  \  }}}|j                         }||k7  s|j                  |       |}1 | j                  |       y)z_ Handle history tail replies, which are only supported
            by Jupyter kernels.
        rF   historyzHistory request failed: %rrk   r   rl   z Retrying aborted history requestTg      ?tail  hist_access_typerM   FNz&Received history reply with %i entries)rN   errorrP   _retrying_history_requesttimesleepkernel_clientrt   rO   lenrstripappend_set_history)rA   rr   rF   history_itemsitems	last_cell_cells           r    _handle_history_replyz#JupyterWidget._handle_history_reply   s    i.G#HHNN7?@{{8R(I5040N0N AB15.

4 ""**FT*J  27.).&	*?]AST	' 	!JAq$;;=Dy T" 			!
 	% r   c                    |j                  dd      }| j                  ||      }| j                  | j                  |      }|j	                  d       t        |d   j                         j                  d            D ]D  \  }}|dk(  r| j                  ||       n| j                  ||       | j                  ||dz          F | j                  |dz          y)z.Insert function for input from other frontendsrm   r   remoter   rV   r   N)rP   _make_in_prompt_make_continuation_prompt_prompt
insertText	enumeratestripsplit_insert_html_insert_plain_text_update_prompt)	rA   ra   rF   r   rM   rj   cont_promptilines	            r    _insert_other_inputz!JupyterWidget._insert_other_input   s    KK)1-%%a%744T\\&4Q$ !6!6!8!>!>t!DE 	9GAtAv!!&&1!!&+6##FD4K8	9 	AE"r   c                     | j                   j                  d|j                  dd             | j                  |      r"| j	                  | j
                  |d   d       y| j                  s#| j	                  | j
                  |d   dd       yy)	zHandle an execute_input messagezexecute_input: %srF   r   Tbefore_promptF)r   r   N)rN   rO   rP   include_output_append_customr   r   )rA   rr   s     r    _handle_execute_inputz#JupyterWidget._handle_execute_input   s    *CGGIr,BCs#((#i.   N((#i."5   2 r   c                 |   | j                   j                  d|j                  dd             | j                  |      r| j	                          |d   }|j                  dd      }|d   }d|v r| j                  | j                  d	       | j                  | j                  || j                  |       
      d	       |d   }d|v r.| j                  j                  d      s| j                  dd	       | j                  || j                  z   d	       | j                  |      s| j                  dd	       yyyy)z Handle an execute_result messagezexecute_result: %srF   r   rm   r   data
text/plainTr   r   r   N)rN   rO   rP   r   flush_clearoutput_append_plain_text
output_sep_append_html_make_out_prompt	from_hereendswithoutput_sep2)rA   rr   rF   prompt_numberr   texts         r    _handle_execute_resultz$JupyterWidget._handle_execute_result   s7   +SWWY-CDs#""$)nG#KK(91=M6?Dt#''t'L!!))-DNNSVDW@W)X"& "  L) 4<(@(@(F++D+E''t/?/?(?t'T~~c*++D+E + $ $r   c                     | j                  |      rF| j                          |d   d   }d|v r|d   }| j                  |d       | j                  dd       yy)z2The base handler for the ``display_data`` message.rF   r   r   Tr   N)r   r   r   )rA   rr   r   r   s       r    _handle_display_dataz"JupyterWidget._handle_display_data  se    
 s#""$y>&)D t#L)''d3##D$/ $r   c                 r   |d   }|d   d   | _         |d   j                  dd      }	 |dk(  rt               }n%|dk(  rt               }nt	        | j                         }|| j
                  _        |j                  dd      | _        | j                  rd	| _	        t        | -          y
y
# t        $ r Y Ew xY w)zHandle kernel info replies.rF   language_infonamepygments_lexerr   ipython3ipython2bannerFN)r?   rP   r	   r   r
   _highlighter_lexerr   kernel_banner	_startingr.   _started_channels)rA   r`   rF   r   lexerrD   s        r    _handle_kernel_info_replyz'JupyterWidget._handle_kernel_info_reply'  s    i.$_5f= 1556FK	 +%:-$)$*<*<=',D$ %[[26>>"DNG%' 	  		s   AB* *	B65B6c                     d| _         | j                  j                          | j                  j                  dd       y)zMake a history requestTru   rv   rw   N)r   r}   kernel_infort   rA   s    r    r   zJupyterWidget._started_channels@  s4    &&(""Fd"Cr   c                     | j                   j                  d|j                  dd             |d   }dj                  |d         dz   }	 | j                  || j                  |              y)zHandle an execute_error messagezexecute_error: %srF   r   r   	tracebackr   N)rN   rO   rP   joinreplacer   r   r   )rA   rr   rF   r   enameename_styleds         r    _process_execute_errorz$JupyterWidget._process_execute_errorK  sf    *CGGIr,BCi.IIgk23d:	  ##IPSAT=T#Ur   c                 V    | j                   j                  |d         }|y ||       y)z@ Reimplemented to dispatch payloads to handler methods.
        sourceFT)r8   rP   )rA   itemhandlers      r    _process_execute_payloadz&JupyterWidget._process_execute_payloadd  s0     ((,,T(^<?DMr   c                    |W| j                   ryd| _         | j                  j                  dd      }| j                  |dd      }|| j                  d   |<   y| j
                  | _        | j                  | j                  |      d       | j                  j                         j                         }t        | j                        }| j                  |||      | _        | j!                  | j#                  | j                        d       y)	2 Reimplemented for IPython-style prompts.
        NTr   )silentrj   Fri   html)r@   r}   ri   _ExecutionRequestrR   	input_sep_prompt_sep_show_promptr   r]   document	lastBlockr~   r   r%   r9   _set_continuation_promptr   )rA   r(   rI   rb   r&   r'   s         r    ro   z&JupyterWidget._show_interpreter_prompto  s     >%%%)D"''//4/@F))&(EBD48Dy)&1  >>$..v6TB&&(224T\\"$($5$5eVV$L! 	%%**4<<8t 	& 	Er   c                    | j                   y| j                   j                  }|j                         rQ|j                         r?t	        j
                  |      }|j                  t        j
                  j                  t        j
                  j                  | j                   j                         | j                  |      }| j                  ||      | _        | j                  j                  |j                                | j                  j!                  |j#                         dz
         | j$                  j'                         j)                         }t+        | j                        }| j-                  |||      | _         yyy)z1Replace the last displayed prompt with a new one.Nr   )r9   r&   isValidr   r   rZ   rY   r\   
KeepAnchorr'   r    _insert_html_fetching_plain_textr   r   rehighlightBlock_prompt_cursorsetPositionpositionr]   r   r   r~   r%   )rA   new_prompt_numberr&   ra   rj   r'   s         r    r   zJupyterWidget._update_prompt  s4   $$,))// ==?uzz| &&u-F 1 1 7 7 % 1 1 < < $ 9 9 @ @B ))*;<F@@ DL
 ..v||~> ++FOO,=,AB MM**,668E&F(,(9(9%IZ([D%+  ,?r   c                    |d   }|d   dk(  r&| j                   r| j                   j                  }nd}n|d   }| j                   r1| j                   j                  |k7  r| j                  |       d| _         | j                  |dz          y)r   rF   rk   rl   r   rm   Nr   )r9   r(   r   ro   )rA   rr   rF   previous_prompt_numbers       r    "_show_interpreter_prompt_for_replyz0JupyterWidget._show_interpreter_prompt_for_reply  s     i.8	)(()-)B)B)I)I&)*&%,->%?"$$))004JJ 67(,D% 	%%&<q&@Ar   c                 ^   |j                         }|dk(  r+t        j                  | _        t        j                  | _        y|dk(  r+t        j                  | _        t        j                  | _        y|dk(  r+t        j                  | _        t        j                  | _        yt        d|z        )z Sets the widget style to the class defaults.

        Parameters
        ----------
        colors : str, optional (default lightbg)
            Whether to use the default light background or dark
            background or B&W style.
        lightbglinuxnocolorzNo such color scheme: %sN)lowerr   default_light_style_sheetr;   default_light_syntax_stylesyntax_styledefault_dark_style_sheetdefault_dark_syntax_styledefault_bw_style_sheetdefault_bw_syntax_styleKeyError)rA   colorss     r    r>   zJupyterWidget.set_default_style  s     9%??D & A ADW_%>>D & @ @DY%<<D & > >D5f<==r   c                 8   | j                   r| j                  j                  ||       y
| j                  s| j	                  d       y
	 d|z  }|r*| j
                  r| j
                  j                  ||      }n#	 | j                  j                         }|d|z   z  }	 t        |d       y
# t        $ r | j                  j                  |      }Y 6w xY w# t        $ r d}| j	                  ||z         Y y
w xY w# t        $ r | j	                  d	       Y y
w xY w)z Opens a Python script for editing.

        Parameters
        ----------
        filename : str
            A path to a local system file.

        line : int, optional
            A line of interest in the file.
        z{No default editor available.
Specify a GUI text editor in the `JupyterWidget.editor` configurable to enable the %edit magicz"%s")filenamer    )r   T)shellz)Opening editor with command "%s" failed.
zInvalid editor command.
N)
custom_editcustom_edit_requestedemiteditorr   editor_lineformatr   r   OSError)rA   r   r   commandrr   s        r    _editzJupyterWidget._edit  s     &&++Hd;## %5 6;!H,D,,"..55x;? 6 AG2"&++"4"4"6  3>1;'. $ H"&++"4"4h"4"GH  ;FC++C'M:;  E''(CDEsH   	1C< ;B, C< C ,%CC< CC< C98C9<DDc                     	 | j                   |z  }|r| j                  |z   }d|z  S # t        $ r ddlm}  || j                         }Y 9w xY w)z; Given a prompt number, returns an HTML In prompt.
        r   escape!<span class="in-prompt">%s</span>)	in_prompt	TypeErrorxml.sax.saxutilsr  other_output_prefixrA   r(   r   bodyr  s        r    r   zJupyterWidget._make_in_prompt  sW    	*>>F*D
 ++d2D2T99  	*/$..)D	*   ' !A
Ac                     d}t        |j                  d            t        |      z
  }|r*|t        | j                  j                  d      d         z  }d|z  |z   }d|z  S )zf Given a plain text version of an In prompt, returns an HTML
            continuation prompt.
        z...: r   z&nbsp;r  )r~   lstripr  rsplit)rA   rj   r   	end_charsspace_countr  s         r    r   z'JupyterWidget._make_continuation_prompt  sg     	&---.Y?3t77>>tDRHIIK+%	12T99r   c                     	 | j                   |z  }|r| j                  |z   }d|z  S # t        $ r ddlm}  || j                         }Y 9w xY w)z< Given a prompt number, returns an HTML Out prompt.
        r   r   z"<span class="out-prompt">%s</span>)
out_promptr  r  r  r  r  s        r    r   zJupyterWidget._make_out_prompt  sW    	+??V+D
 ++d2D3d::  	+/$//*D	+r	  c                 4    | j                  |d   |d          y )Nr   line_number)r   rA   r   s     r    r1   z"JupyterWidget._handle_payload_edit-  s    

4
#T-%89r   c                 N    |d   | _         | j                  j                  |        y )N
keepkernel)r:   exit_requestedr   r  s     r    r3   z"JupyterWidget._handle_payload_exit0  s#    $($6!  &r   c                     |d   | _         y )Nr   )rW   r  s     r    r7   z(JupyterWidget._handle_payload_next_input4  s     Lr   c                     |d   }d|v r&| j                   dk(  r| j                  |d   d       y | j                  |d   d       y )Nr   z	text/htmlrichTr   r   F)rn   _page)rA   r   r   s      r    r5   z"JupyterWidget._handle_payload_page7  sJ     F|$499#6JJtK(tJ4JJtL)J6r   r;   c                 8   | j                  | j                         | j                  3| j                  j                         j	                  | j                         | j
                  4| j
                  j                         j	                  | j                         yy)z9 Set the style sheets of the underlying widgets.
        N)setStyleSheetr;   r]   r   setDefaultStyleSheet_page_controlrA   changeds     r    r<   z"JupyterWidget._style_sheet_changedC  sw     	4++,==$MM""$99$:J:JK)'')>>t?O?OP *r   r   c                    | j                   y| j                  rK| j                   j                  | j                         | j                  j	                  | j                         y| j                   j                  | j                         y)z3 Set the style for the syntax highlighter.
        N)r   r   	set_style_ansi_processorset_background_colorset_style_sheetr;   r   s     r    r=   z#JupyterWidget._syntax_style_changedN  sj     $''(9(9:  55d6G6GH--d.>.>?r   r   c                 .    dj                  t              S )NzJupyter QtConsole {version}
)version)r   r   r   s    r    _banner_defaultzJupyterWidget._banner_default]  s    .55k5JJr   )T)N)r   )F)@r   r   r   r   r   r   r   Signalobjectr   r   default_editorr   r   r;   r   default_in_promptr  default_out_promptr  default_input_sepr   default_output_sepr   default_output_sep2r   r   r%   r0   r2   r6   r4   rz   r   r/   rg   rq   r   r   r   r   r   r   r   r   r   ro   r   r   r>   r   r   r   r   r1   r3   r7   r5   r   r<   r=   r   r)  __classcell__rD   s   @r    r"   r"   5   s   0
 u+K)FMM&&9^DF K K $L )$7I+D9J)$7I+D9J-d;K n.KLL'%!1! %I'< 7D/"!B# 	2F00 (2DV2	E4\>B2>4%;N:	:;&:')7 ]Q Q ^
@ 
@ XK Kr   r"   c                   "     e Zd ZdZ fdZ xZS )r   z$Deprecated class; use JupyterWidget.c                 D    t        dt               t        |   |i | y )Nz.IPythonWidget is deprecated; use JupyterWidget)r   DeprecationWarningr.   r/   )rA   arC   rD   s      r    r/   zIPythonWidget.__init__f  s#    =	!!"r"r   )r   r   r   r   r/   r2  r3  s   @r    r   r   d  s    .# #r   ))r   collectionsr   
subprocessr   sysr{   warningsr   qtpyr   r   IPython.lib.lexersr   r	   pygments.lexersr
   pygments.utilr   	qtconsoler   	traitletsr   r   r   r   frontend_widgetr   r   r   r-  r.  r/  r0  r1  zmq_shell_sourceplatform
startswithr,  r   r"   r   r   r    <module>rF     s    #  
    : - ' ! 5 5 +  F G     < <<5!NN?N ?jKM jK^#M #r   