
    G@d                     H   d Z ddlZddlmZ ddlZddl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mZmZ ddlmZ dd	lmZmZmZmZ dd
l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l+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 dZ6 G d de4e3e1e2          Z7dS )z&
Shell Widget for the IPython Console
    N)dedent)Lock)SignalQThreadSlot)QMessageBox)QtCore	QtWidgetsQtGui)observe)_
is_pynsistrunning_in_mac_apprunning_under_pytest)get_color_schemeis_dark_interface)to_text_string)QStylePaletteSpyderPalette)CLIPBOARD_HELPER)syntaxhighlighters)create_qss_stylecreate_style_class)MessageCheckBox)
KernelComm)ControlWidgetDebuggingWidgetFigureBrowserWidget
HelpWidgetNamepaceBrowserWidgetPageControlWidgetz?https://docs.spyder-ide.org/5/faq.html#using-packages-installerc                       e Zd ZdZ ee          Z ee          Z eee          Z	 eee
          Z eee          Z e            Z e            Z e            Z ee          Z ee          Z e            Z e            Z e            Z ee          Z ee          Zg Zed             Zed             Z fdZd ZdP fd	Z	 	 dQd
Z d Z!d Z" fdZ#dR fd	Z$d Z%d Z&d Z'd Z(dSdZ)d Z*d Z+d Z,d Z-dPdZ.d Z/d Z0d Z1d Z2d Z3d Z4d Z5d  Z6d! Z7d" Z8dSd#Z9d$ Z:d% Z;d& Z<d' Z=d( Z>d) Z?d* Z@d+ ZAd, ZBd- ZC eD            d.             ZEdTd/ZFd0 ZGd1 ZHd2 ZId3 ZJd4 ZKd5 ZLd6 ZMd7 ZNd8 ZO	 	 dUd:ZPd; ZQd< ZRd= ZSeTjU        jV        fd>ZWd? ZXd@ ZY fdAZZ fdBZ[dC Z\ fdDZ]dE Z^dPdFZ_ fdGZ` eadH          dVdI            ZbdJ ZcdK Zd fdLZe fdMZf fdNZg fdOZh xZiS )WShellWidgetzb
    Shell widget for the IPython Console

    This is the widget in charge of executing code
    c                     g }| j         D ]<}	 |                                r|                    |           -# t          $ r Y 9w xY w|| _         dS )zRemove shutdown threads.N)shutdown_thread_list	isRunningappendRuntimeError)clspruned_shutdown_thread_listts      Klib/python3.11/site-packages/spyder/plugins/ipythonconsole/widgets/shell.pyprune_shutdown_thread_listz&ShellWidget.prune_shutdown_thread_listU   st     ')#) 	 	A;;== :/66q999   #>   s   )7
AAc                     | j         D ]i}|                                rS	 |j                                         n# t          $ r Y nw xY w|                                 |                                 jg | _         dS )zWait for shutdown to finish.N)r%   r&   kernel_manager_kill_kernel	Exceptionquitwait)r)   threads     r,   wait_all_shutdownzShellWidget.wait_all_shutdowna   s     . 	 	F!! )668888    D#%   s   9
AAc                 p   t           | _        t          | _        d| _        t                      | _        | j        j                            | j                    t          t          |           j        |i | || _        || _        || _        || _        || _        d| _        |                                 | _        |                     | j                   d| _        d | _        d | _        |                    | j        | j        | j        | j        | j        | j        | j         | j!        | j"        d	           |D ]#}	| j        #                    |	||	                    $g | _$        | j%                            | j&                   tO                      ptQ                      | _)        tU                      | _+        d S )NT F)		pdb_statepdb_executeshow_pdb_outputget_pdb_settingsset_debug_stateupdate_syspathdo_where	pdb_inputrequest_interrupt_eventloop),r   custom_controlr!   custom_page_controlcustom_editr   spyder_kernel_commsig_exception_occurredconnectsuperr#   __init__	ipyclientadditional_optionsinterpreter_versionsis_external_kernelis_spyder_kernel_cwdcreate_shortcuts	shortcuts set_bracket_matcher_color_schemesyntax_styleshutting_downr/   kernel_clientupdateset_pdb_stater9   r:   r;   r<   r=   r>   r?   r@   register_call_handler_execute_queueexecutedpop_execute_queuer   r   show_modules_messager   shutdown_lock)selfrI   rJ   rK   rL   rM   handlersargskw
request_id	__class__s             r,   rH   zShellWidget.__init__n   s    ,#4 ",,,6>>'	) 	) 	))k4  )462666""4$8!"4 0	 ..00
 	--d.?@@@""!++#3 $ 5#3"1+/+K

 

 
	 
	 
	 # 	2 	2J#99HZ02 2 2 2 !d4555 %/LL$H4F4H4H!!VV    c                     | j         5  | j        j        r	 ddd           dS d| j        _        ddd           n# 1 swxY w Y   	 | j                                         dS # t          $ r Y dS w xY w)zShutdown kernel.NT)r\   r/   rS   shutdown_kernelr1   r]   s    r,   re   zShellWidget.shutdown_kernel   s     	5 	5 "0 		5 	5 	5 	5 	5 	5 	5 	5
 15D-	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5	//11111 	 	 	DD	s#   ;;??A" "
A0/A0Tc                    | j         rdS d| _         |r| j        sdS |                                  | j        r| j                                         | j                                         | j        | j                                         | j        rUt          d          }| j        |_        | j	        |_
        | j                            |           |                                 n;| j                            d           | j        | j                                         |                                  t          t           |                                            dS )zShutdown connection and kernel.NTF)shutdown_channel)rS   r/   interrupt_kernelstop_restarterrD   closerT   stop_channelsr   re   runr%   r'   startr-   rG   r#   shutdown)r]   re   shutdown_threadrb   s      r,   ro   zShellWidget.shutdown   sZ    	F! 	3& !!###" 5#22444#))+++!-"00222" (")$--151D.&*&:#)00AAA%%'''#))5)AAA!-"00222'')))k4  ))+++++rc   FNc                 @    | j                             |||||          S )a=  
        Send message to Spyder kernel connected to this console.

        Parameters
        ----------
        interrupt: bool
            Interrupt the kernel while running or in Pdb to perform
            the call.
        blocking: bool
            Make a blocking call, i.e. wait on this side until the
            kernel sends its response.
        callback: callable
            Callable to process the response sent from the kernel
            on the Spyder side.
        timeout: int or None
            Maximum time (in seconds) before giving up when making a
            blocking call to the kernel. If None, a default timeout
            (defined in commbase.py, present in spyder-kernels) is
            used.
        display_error: bool
            If an error occurs, should it be printed to the console.
        )	interruptblockingcallbacktimeoutdisplay_error)rD   remote_call)r]   rr   rs   rt   ru   rv   s         r,   call_kernelzShellWidget.call_kernel   s3    0 &22' 3 
 
 	
rc   c                     || _         || _        | j        r| j                            |           |                     | j                   dS )z!Set the kernel client and managerN)r/   rT   rM   rD   	open_comm_redefine_complete_for_dbg)r]   rT   r/   s      r,   set_kernel_client_and_managerz)ShellWidget.set_kernel_client_and_manager   sS    ,*  	=#--m<<< 	''(:;;;;;rc   c                 \    | j         r$ | j        | j                             d            dS dS )zPop one waiting instruction.r   N)rX   executepoprf   s    r,   rZ   zShellWidget.pop_execute_queue   s=     	6DL$-11!445555	6 	6rc   c                     g | _         | j        r5| j        j        r)t          t          |                                            dS |                     t          d                     dS )z)Attempts to interrupt the running kernel.zq<br><br>The kernel appears to be dead, so it can't be interrupted. Please open a new console to keep working.<br>N)rX   r/   
has_kernelrG   r#   ri   _append_htmlr   r]   rb   s    r,   ri   zShellWidget.interrupt_kernel   s}     !
  	4#6#A 	+t$$5577777 ! " "    rc   c                     | j         dS | j        r| j                            |||f           dS t	          t
          |                               |||           dS )za
        Executes source or the input buffer, possibly prompting for more
        input.
        N)rT   
_executingrX   r'   rG   r#   r~   )r]   sourcehiddeninteractiverb   s       r,   r~   zShellWidget.execute  sh     %F? 	&&'DEEEFk4  ((EEEEErc   c                 R    |                                                                   dS )z8Send a message to the kernel to interrupt the eventloop.N)rx   _interrupt_eventlooprf   s    r,   r@   z'ShellWidget.request_interrupt_eventloop  s&    //11111rc   c                 N    | j                             | j        j                   dS )z!Set exit callback for this shell.N)exit_requestedrF   rI   exit_callbackrf   s    r,   set_exit_callbackzShellWidget.set_exit_callback#  s$    ##DN$@AAAAArc   c                 0    | j         | j         j        rdS dS )NTF)rT   channels_runningrf   s    r,   
is_runningzShellWidget.is_running'  s#    )


- *45rc   c                 F    d}| j         rdS |                     |           dS )z'Determine if the kernel is from Spyder.z1getattr(get_ipython().kernel, 'set_value', False)N)_readingsilent_exec_methodr]   codes     r,   check_spyder_kernelzShellWidget.check_spyder_kernel.  s0    C= 	*F##D)))))rc   c                 4   t           j        dk    rt          j        |          }| j        j        e|                     |                                                               |           || _	        |r#| j
                            | j	                   dS dS dS )aN  
        Set shell current working directory.

        Parameters
        ----------
        dirname: str
            Path to the new current working directory.
        emit_cwd_change: bool
            Whether to emit a Qt signal that informs other panes in Spyder that
            the current working directory has changed.
        ntNrr   )osnameospnormpathrI   hostnamerx   is_debuggingset_cwdrN   sig_working_directory_changedemit)r]   dirnameemit_cwd_changes      r,   r   zShellWidget.set_cwd6  s     7d?? l7++G>"*t'8'8':':;;CCGLLLDI C277	BBBBB	 +*C Crc   c                     | j         S )a_  
        Get current working directory.

        Notes
        -----
        * This doesn't ask the kernel for its working directory. Instead, it
          returns the last value of it saved here.
        * We do it for performance reasons because we call this method when
          switching consoles to update the Working Directory toolbar.
        )rN   rf   s    r,   get_cwdzShellWidget.get_cwdM  s     yrc   c                 r    | j         dS |                     | j                                                   dS )ze
        Update working directory in Spyder after getting its value from the
        kernel.
        N)rt   )rT   rx   on_getting_cwdr   rf   s    r,   
update_cwdzShellWidget.update_cwdZ  s>    
 %F$"566>>@@@@@rc   c                 l    || j         k    r(|| _         | j                            | j                    dS dS )zg
        If necessary, notify that the working directory was changed to other
        plugins.
        N)rN   r   r   )r]   cwds     r,   r   zShellWidget.on_getting_cwdc  s?    
 $)DI.33DI>>>>> rc   c                     t          j        | |          }|                                }| j        j                            |           dS )z)Set color scheme for matched parentheses.)parentcolor_schemeN)shBaseSHget_matched_p_color_bracket_matcherformatsetBackground)r]   r   bshmpcolors       r,   rQ   z,ShellWidget.set_bracket_matcher_color_schemel  sG    it,???))++$227;;;;;rc   c                    |                      |           t          |          \  | _        }|| _        |                                  |                                  |r|                     d           |s?|                     d           |                                 	                    d           dS |                     d           |                                 	                    d           dS )	zSet color scheme of the shell.T)clearz%colors linuxdark)background_colorz%colors lightbglightN)
rQ   r   style_sheetrR   _style_sheet_changed_syntax_style_changedresetsilent_executerx   set_sympy_forecolor)r]   r   r   
dark_colors       r,   set_color_schemezShellWidget.set_color_schemer  s    --l;;;'7'E'E$*(!!###""$$$ 	#JJTJ""" 	M00022F2KKKKK 122222G2LLLLLrc   c                 \    |                      dd                              ||           dS )z#Update sys.path contents on kernel.TFrr   rs   N)rx   r=   )r]   	path_dictnew_path_dicts      r,   r=   zShellWidget.update_syspath  s8     	 	 	*N9mDDDDDrc   c                 l    |                      d| j        j                                                   dS )z%Ask the kernel for sys.path contents.Trr   rt   N)rx   sig_show_syspathr   get_syspathrf   s    r,   request_syspathzShellWidget.request_syspath  s6    T%:%? 	 	A 	AALrc   c                 l    |                      d| j        j                                                   dS )z)Ask the kernel for environment variables.Tr   N)rx   sig_show_envr   get_envrf   s    r,   request_envzShellWidget.request_env  s4    T%6%; 	 	= 	==DWYYYYYrc   c                     || _         dS )z Enable/Disable showing calltips.N)enable_calltips)r]   show_calltipss     r,   set_show_calltipszShellWidget.set_show_calltips  s    ,rc   c                     || _         dS )zSet buffer size for the shell.N)buffer_size)r]   r   s     r,   set_buffer_sizezShellWidget.set_buffer_size  s    &rc   c                     || _         dS )z?Set completion type (Graphical, Terminal, Plain) for the shell.N)gui_completion)r]   completion_types     r,   set_completion_typezShellWidget.set_completion_type  s    -rc   c                     || _         dS )z Set appereance of the In prompt.N)	in_prompt)r]   r   s     r,   set_in_promptzShellWidget.set_in_prompt  s    "rc   c                     || _         dS )z!Set appereance of the Out prompt.N)
out_prompt)r]   r   s     r,   set_out_promptzShellWidget.set_out_prompt  s    $rc   c                 T    |                      dd                                          S )z#Call kernel to get current backend.Tr   )rx   get_matplotlib_backendrf   s    r,   r   z"ShellWidget.get_matplotlib_backend  s1        1133	4rc   c                 T    |                      dd                                          S )z/Call kernel to get current interactive backend.Tr   )rx   get_mpl_interactive_backendrf   s    r,   r   z'ShellWidget.get_mpl_interactive_backend  s1        6688	9rc   c                 `    d}|                      |                    ||          d           dS )z,Set matplotlib backend given a backend name.z5get_ipython().kernel.set_matplotlib_backend('{}', {})Tr   Nr~   r   )r]   backend_optionpylabcmds       r,   set_matplotlib_backendz"ShellWidget.set_matplotlib_backend  s1    ESZZ66tDDDDDrc   c                 ^    d}|                      |                    |          d           dS )z$Set matplotlib inline figure format.z7get_ipython().kernel.set_mpl_inline_figure_format('{}')Tr   Nr   )r]   figure_formatr   s      r,   set_mpl_inline_figure_formatz(ShellWidget.set_mpl_inline_figure_format  s/    GSZZ..t<<<<<rc   c                 ^    d}|                      |                    |          d           dS ):Set matplotlib inline resolution (savefig.dpi/figure.dpi).z2get_ipython().kernel.set_mpl_inline_resolution({})Tr   Nr   )r]   
resolutionr   s      r,   set_mpl_inline_resolutionz%ShellWidget.set_mpl_inline_resolution  s/    BSZZ
++D99999rc   c                 `    d}|                      |                    ||          d           dS )r   z7get_ipython().kernel.set_mpl_inline_figure_size({}, {})Tr   Nr   )r]   widthheightr   s       r,   set_mpl_inline_figure_sizez&ShellWidget.set_mpl_inline_figure_size  s1    GSZZv..t<<<<<rc   c                 ^    d}|                      |                    |          d           dS )z@Set matplotlib inline print figure bbox_inches ('tight' or not).z3get_ipython().kernel.set_mpl_inline_bbox_inches({})Tr   Nr   )r]   bbox_inchesr   s      r,   set_mpl_inline_bbox_inchesz&ShellWidget.set_mpl_inline_bbox_inches  s/    CSZZ,,T:::::rc   c                 ^    d}|                      |                    |          d           dS )z'Set if jedi completions should be used.z+get_ipython().kernel.set_jedi_completer({})Tr   Nr   )r]   use_jedir   s      r,   set_jedi_completerzShellWidget.set_jedi_completer  s/    ;SZZ))$77777rc   c                 ^    d}|                      |                    |          d           dS )z)Set if greedy completions should be used.z-get_ipython().kernel.set_greedy_completer({})Tr   Nr   )r]   
use_greedyr   s      r,   set_greedy_completerz ShellWidget.set_greedy_completer  s/    =SZZ
++D99999rc   c                 ^    d}|                      |                    |          d           dS )z0Set if autocall functionality is enabled or not.z%get_ipython().kernel.set_autocall({})Tr   Nr   )r]   autocallr   s      r,   set_autocallzShellWidget.set_autocall  s/    5SZZ))$77777rc   c                 :   | j         d                             d          d         }| j         d         }d|z  ddd|z  g}d	                    |          }| j        d
         }| j        d         }|r	|rd}||z   }| j        d         }|rd}	||	z   }|r	|rd}	||	z   }|S )z+Banner for clients with additional content.python_version
r   ipython_versionz
Python %s
z>Type "copyright", "credits" or "license" for more information.z

z.IPython %s -- An enhanced Interactive Python.
r7   r   autoload_pylabz@
Populating the interactive namespace from numpy and matplotlib
sympyz
These commands were executed:
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
z
Warning: pylab (numpy and matplotlib) and symbolic math (sympy) are both
enabled at the same time. Some pylab functions are going to be overrided by
the sympy module (e.g. plot)
)rK   splitjoinrJ   )
r]   py_veripy_verbanner_partsbannerpylab_oautoload_pylab_opylab_messagesympy_oliness
             r,   long_bannerzShellWidget.long_banner  s     *+;<BB4HHK+,=> F"L=G	
 && )'223CD 	,' 	,6Mm+F )'2 	$E e^F 	$ 	$E
 e^Frc   c                 |    | j         d                             d          d         }| j         d         }d|d|}|S )z3Short banner with Python and IPython versions only.r   r   r  zPython z -- IPython )rK   r  )r]   r  r  r  s       r,   short_bannerzShellWidget.short_banner  sH    *+;<BB3GGJ+,=>.4ffgg>rc   c                 >    |                      d           d| _        d S )Nz%clearF)r~   r   rf   s    r,   clear_consolezShellWidget.clear_console  s    Xrc   c                 \    |                      d          }|                     |           d S )Nshow_reset_namespace_warning)warning)get_confreset_namespace)r]   r  s     r,   _reset_namespacezShellWidget._reset_namespace  s1    -- >??W-----rc   c                     t                      rd}|r/t          d          }t          d          }t          t          j                                       |                               t          j        t          j        z             	                    t          j                   
                    t          d                                         d                               d                               |           j                             fd                                            dS                                 dS )	z>Reset the namespace by removing all names defined by the user.FzRemove all variableszMAll user-defined variables will be removed. Are you sure you want to proceed?)iconr   zDon't show again.Tc                 2                         |           S N)handle_reset_message_answer)buttonboxmessager]   s    r,   <lambda>z-ShellWidget.reset_namespace.<locals>.<lambda>.  s    t?? *  * rc   N)r   r   r   r   WarningsetWindowTitlesetStandardButtonsYesNosetDefaultButtonset_checkbox_textset_checkedset_check_visiblesetTextbuttonClickedrF   show_perform_reset)r]   r  r)  	reset_strwarn_strr(  s   ` `  @r,   r   zShellWidget.reset_namespace  s[     !! 	G 	)011I = > >H!{':4HHHCy)))"";?[^#CDDD  111!!!$7"8"8999OOE"""!!$'''KK!!!%%* * * * * *   HHJJJJJ(((((rc   c                     |                     |          t          j        k    r,|                     |           |                     |           dS |                     |           dS )a  
        Handle the answer of the reset namespace message box.

        Parameters
        ----------
        message_box
            Instance of the message box shown to the user.
        button: QPushButton
            Instance of the button clicked by the user on the dialog.
        message: bool
            Whether to show a message in the console telling users the
            namespace was reset.
        N)
buttonRoler   YesRole_update_reset_optionsr7  )r]   message_boxr'  r)  s       r,   r&  z'ShellWidget.handle_reset_message_answer5  sh     !!&))[-@@@&&{333(((((&&{33333rc   c                 L   	 | j         j        j        }n# t          $ r i }Y nw xY w	 |                                 r|                     d           dS |rL|                                  |                     t          d          d           | 	                                 | 
                    d           |                    d          dk    r| 
                    d           |                    d          dk    r$d	}| 
                    t          |                     |                    d
          dk    r| 
                    d           |                     d           | j        r(|                                                                  dS dS # t          $ r Y dS w xY w)z
        Perform the reset namespace operation.

        Parameters
        ----------
        message: bool
            Whether to show a message in the console telling users the
            namespace was reset.
        z	%reset -fz%<br><br>Removing all variables...<br>Fbefore_promptSPY_AUTOLOAD_PYLAB_OTruezfrom pylab import *SPY_SYMPY_Oa  
                        from sympy import *
                        x, y, z, t = symbols('x y z t')
                        k, m, n = symbols('k m n', integer=True)
                        f, g, h = symbols('f g h', cls=Function)
                        init_printing()SPY_RUN_CYTHONz%reload_ext Cythonr   N)r/   _kernel_specenvAttributeErroris_waiting_pdb_inputr~   r   r   r   insert_horizontal_rulerr   getr   refresh_namespacebrowserrM   rx   close_all_mpl_figures)r]   r)  
kernel_env
sympy_inits       r,   r7  zShellWidget._perform_resetI  s   	,9=JJ 	 	 	JJJ	!	((** ?[))))) 3JJLLL%%ABB&+ &    00222##K000>>"899VCC''(=>>>>>-00F::"+J ''z(:(:;;;>>"233v==''(<===
 --->>>( ?$$&&<<>>>>>? ? 	 	 	DD	s$    ##)F D?F 
F#"F#c                     |                      d|                                            |                                 | j        _        dS )z
        Update options and variables based on the interaction in the
        reset warning message box shown to the user.
        r  N)set_conf
is_checkedrI   reset_warning)r]   r>  s     r,   r=  z!ShellWidget._update_reset_options~  sP    
 	*&&(((	
 	
 	
 ,7+A+A+C+C'C$$$rc   c                 (   |                      | j        j        dd|           }|                      | j        dd|           }|                      | j        j        dd|           }|                      | j        dd|           }|                      | j        dd|           }|                      | j        j        dd|           }|                      | j        j	        dd	|           }|                      | j        j
        dd
|           }||||||||gS )z Create shortcuts for ipyconsole.ipython_consolezInspect current object)contextr   r   zClear shellzRestart kernelznew tabzreset namespacezenter array inlinezenter array tablez
clear line)config_shortcut_controlinspect_current_objectr  rI   restart_kernelsig_new_clientr!  enter_array_inlineenter_array_table
clear_line)	r]   inspectr  rZ  new_tabr   array_inlinearray_tabler^  s	            r,   rO   zShellWidget.create_shortcuts  s   &&M0%)	 '   ,,%	 -   --N)%!	 .   &&%	 '   ..!%"	 /   ++M,%%	 ,   **M+%$	 +   ))N%%	 *  
 {JH 	Hrc   c                     	 |                                  r|                     |d           dS | j                            t	          |          d           dS # t
          $ r Y dS w xY w)z8Execute code in the kernel without increasing the promptTr   )silentN)r   r9   rT   r~   r   rH  r   s     r,   r   zShellWidget.silent_execute  s    	  "" N  d 33333"**>$+?+?*MMMMM 	 	 	DD	s   +A )A 
A('A(c                    t          t          j                              }t          |          }| j        dS | j                            dd||i          }|| j        |<   |                     |dd          | j        d         |<   dS )a  Silently execute a kernel method and save its reply

        The methods passed here **don't** involve getting the value
        of a variable but instead replies that can be handled by
        ast.literal_eval.

        To get a value see `get_value`

        Parameters
        ----------
        code : string
            Code that contains the kernel method as part of its
            string

        See Also
        --------
        handle_exec_method : Method that deals with the reply

        Note
        ----
        This is based on the _silent_exec_callback method of
        RichJupyterWidget. Therefore this is licensed BSD
        Nr7   T)rd  user_expressionsr   Fr~   )r   uuiduuid1rT   r~   _kernel_methods_ExecutionRequest_request_info)r]   r   
local_uuidmsg_ids       r,   r   zShellWidget.silent_exec_method  s    4 $DJLL11
d##%F#++t($/ , 1 1 ,0Z(040F0F 1 19%f---rc   c                 V   |d                              d          }|sdS |D ]}|| j        v r{| j        |         }||         }|                     d          }d|v r3|1d|v r-|d         }d|v r!d| _        | j                            |            | j                            |           dS )	z
        Handle data returned by silent executions of kernel methods

        This is based on the _handle_exec_callback of RichJupyterWidget.
        Therefore this is licensed BSD.
        contentrf  Ndatagetattrz
text/plainSpyderKernelT)rK  ri  rM   sig_is_spykernelr   r   )r]   msguser_exp
expressionmethodreplyrp  rM   s           r,   handle_exec_methodzShellWidget.handle_exec_method  s     y>%%&899 	F" 	5 	5JT111-j9 ,yy((&&'LD,@,@+/+=()-===48D1 166t<<< $((444	5 	5rc   c                     d}|                                 }|D ]#}|                    d          sd|v sd|v rd} n$|r>t          d          }|                     |dz              |                     d           d	S d	S )
zy
        Mayavi plots require the Qt backend, so we try to detect if one is
        generated to change backends
        F#zimport mayavizfrom mayaviTz!Changing backend to Qt for Mayavir  z%gui inline
%gui qtN)
splitlines
startswithr   _append_plain_textr   )r]   commandcalling_mayavir  liner)  s         r,   set_backend_for_mayaviz"ShellWidget.set_backend_for_mayavi  s    
 ""$$ 	 	D??3'' "d**mt.C.C%)NE 	8;<<G##GdN333 677777	8 	8rc   c                     |                     d          r@t          |                                          dk    rd|vr|                     |           dS dS dS dS )z
        If the user is trying to change Matplotlib backends with
        %matplotlib, send the same command again to the kernel to
        correctly change it.

        Fixes spyder-ide/spyder#4002.
        z%matplotlib   inlineN)r}  lenr|  r   )r]   r  s     r,   change_mpl_backendzShellWidget.change_mpl_backend  st     }-- 	-G&&(())Q..w&&##G,,,,,	- 	-..&&rc   r  c                    d}|dk    rt          d          }t          j        }nt          d          }t          j        }t	                      rt
          j        }nd}|                     d| d| d| d	| d
| d|           dS )a3  
        Append an html message enclosed in a box.

        Parameters
        ----------
        before_prompt: bool
            Whether to add the message before the next prompt.
        msg_type: str
            Type of message to be showm. Possible values are
            'warning' and 'error'.
        z5border='0.5'width='90%'cellpadding='8'cellspacing='0'errorError	Importantwhitez<div align='center'><table z><tr><th bgcolor='z'><font color='z'>z</th></tr><tr><td>z</td></tr></table></div>r@  N)r   r   COLOR_ERROR_2COLOR_WARN_1r   r   COLOR_TEXT_1r   )r]   htmlrA  msg_typetable_propertiesheaderbgcolor
font_colors           r,   append_html_messagezShellWidget.append_html_message)  s     	 wwZZF#1GG{^^F#0G  	!&3JJ J	&	 	 !(	 	 9C	 	 		 	 	 	 	 ( 	 	
 	
 	
 	
 	
rc   c                 8    | j                                          dS )z
        Insert a horizontal ruler at the current cursor position.

        Notes
        -----
        This only works when adding a single horizontal line to a
        message. For more complex messages, please use
        append_html_message.
        N)rX  rJ  rf   s    r,   rJ  z#ShellWidget.insert_horizontal_rulerZ  s     	--/////rc   c                 8    | j                                          dS )z0Reimplemented to call our own restart mechanism.N)rI   rZ  rf   s    r,   request_restart_kernelz"ShellWidget.request_restart_kernelg  s    %%'''''rc   c                     |dk    s|dk    r|S |dk    rd|z  |z   S t          j        |          }t          ||           }||d         S )zAdjust indentation.r   r7   r  N)r   get_line_indentationmin)r]   r  indent_adjustment
max_indents       r,   adjust_indentationzShellWidget.adjust_indentationk  sl    !!TRZZKq  **T11%:4@@

->,>??%&&''rc   c                 <     j                                         t          j        j        z  rm                                   j                                         }t          j        	                                
                    |                                          }t          |                                          dk    rht          j                                                   d}||z                                   ^}} fd|D             }|                    |g|          }|                                                                 z
  }|                    d|z            r
||d         }                     |t-          |                     dS dS )a   Paste the contents of the clipboard into the input region.

        Parameters
        ----------
        mode : QClipboard::Mode, optional [default QClipboard::Clipboard]

            Controls which part of the system clipboard is used. This can be
            used to access the selection clipboard in X11 and the Find buffer
            in Mac OS. By default, the regular clipboard is used.
        r  r  c                 <    g | ]}                     |          S  )r  ).0r  lines_adjustmentr]   s     r,   
<listcomp>z%ShellWidget.paste.<locals>.<listcomp>  s:     #1 #1 #1 ++D2BCC#1 #1 #1rc   r  N)rX  textInteractionFlagsr	   QtTextEditable_keep_cursor_in_buffer
textCursorr
   QApplication	clipboardtextrstripr  r|  r   remaining_lines_adjustment_get_preceding_textr  position_get_line_start_posr}  _insert_plain_text_into_bufferr   )	r]   modecursorr  	eol_chars
first_lineremaining_linescursor_offsetr  s	   `       @r,   pastezShellWidget.pastex  s    =--//&)2HH 	F'')))]--//F )3355::4@@GGIID 4??$$%%))#3#N,,..$0 $0  	04y0@/L/L/N/N,
_#1 #1 #1 #1 #1 /#1 #1 #1 !~~z&DO&DEE #OO--0H0H0J0JJMs]233 ,MNN+//tEEEEE9	F 	Frc   c                    | j                                         }|                                                                }|dk    rdS |                                d         }|                    |                                           |                    |                                                                t          j
        j                   |                                                                }||z   }t          |          }| j                            |          }| j                            |          }|t          |          z
  }|t          |          k    rdS ||d         S )zGet preciding text.r7   r   N)rX  r  	selectiontoPlainTextr|  setPositionselectionStartblockr  r   QTextCursor
KeepAnchorr  _highlightertransform_classic_prompttransform_ipy_prompt)r]   r  r  first_line_selectionpreceding_textr  len_with_prompt
prompt_lens           r,   r  zShellWidget._get_preceding_text  sB   ))++!!--//2::2#003600223336<<>>2244 ,7	9 	9 	9))++7799#&::
j//&??
KK
&;;JGG
$s:6
^,,,,2jkk**rc   c                 T    t          j        |                                 d           dS )zx
        Save the indentation corresponding to the clipboard data.

        Must be called right after copying.
           N)r   save_indentationr  rf   s    r,   _save_clipboard_indentationz'ShellWidget._save_clipboard_indentation  s)     	)$*B*B*D*DaHHHHHrc   c                 p    t                                                       |                                  dS )zD
        Copy the currently selected text to the clipboard.
        N)rG   copyr  r   s    r,   r  zShellWidget.copy  s.     	((*****rc   c                 p    t                                                       |                                  dS )zz
        Copy the currently selected text to the clipboard and delete it
        if it's inside the input buffer.
        N)rG   cutr  r   s    r,   r  zShellWidget.cut  s.    
 	((*****rc   c                 0    |                      |           dS )zV
        Reimplemented to reset the prompt if the error comes after the reply
        N)_process_execute_error)r]   rt  s     r,   _handle_errorzShellWidget._handle_error  s     	##C(((((rc   c                     t          t          |                               |          }| j                            |          S )z$Reimplement the IPython context menu)rG   r#   _context_menu_makerI   add_actions_to_context_menu)r]   posmenurb   s      r,   r  zShellWidget._context_menu_make  s6    [$''::3??~99$???rc   c                     | j         rdS | j        d         }|r|                                 S |                                 S )zh
        Reimplement banner creation to let the user decide if he wants a
        banner or not
        r7   show_banner)rL   rJ   r  r  )r]   show_banner_os     r,   _banner_defaultzShellWidget._banner_default  sM     " 	2/> 	'##%%%$$&&&rc   c                 z    |rt          d          nt          d          }| j                            |           d S )NzKernel died, restartingzKernel restarting)r   sig_kernel_restarted_messager   )r]   diedrt  s      r,   _kernel_restarted_messagez%ShellWidget._kernel_restarted_message  s@    .2Na)***:M8N8N)..s33333rc   c                 z     t          t          |           j        |i | | j                                         d S r%  )rG   r#   _handle_kernel_restartedsig_kernel_restartedr   )r]   r_   kwargsrb   s      r,   r  z$ShellWidget._handle_kernel_restarted  s@    9k4  94J6JJJ!&&(((((rc   rR   c                     | j         dS | j        r9t          | j                  | j         _        | j                                          dS | j                             | j                   dS )z@Refresh the highlighting with the current syntax style by class.N)r  rR   r   _style_clear_cachesset_style_sheetr   )r]   changeds     r,   r   z!ShellWidget._syntax_style_changed  so     $F 	@'9$:K'L'LD$++-------d.>?????rc   c                     t          | j                  }t          |d         |d         |d         d                   |         S )zr
        Get a color as qtconsole.styles._get_color() would return from
        a builtin Pygments style.
        
backgroundnormalr   )r  selectfgcolor)r   rR   dict)r]   colorr   s      r,   
_get_colorzShellWidget._get_color  sR    
 ((9:: .- *1-/ / / 056 	6rc   c                 b    | j         s'd| j        _        | j                                         dS dS )z'Emit a signal when the prompt is ready.TN)r   r  highlighting_onsig_prompt_readyr   rf   s    r,   _prompt_started_hookz ShellWidget._prompt_started_hook  s<    } 	)04D-!&&(((((	) 	)rc   c                     t          t          |                               |           | j                                         dS )zHandle an execute_input messageN)rG   r#   _handle_execute_inputsig_remote_executer   )r]   rt  rb   s     r,   r  z!ShellWidget._handle_execute_input  s<    k4  66s;;;$$&&&&&rc   c                 >   t          t          |                               |           | j        rl|d         d         }t	          d |D                       r<|                     t          d                              t                    d           d| _        dS dS )	z
        Display a message when using our installers to explain users
        how to use modules that doesn't come with them.
        ro  	tracebackc                     g | ]
}d |v pd|v S )ModuleNotFoundErrorImportErrorr  )r  frames     r,   r  z6ShellWidget._process_execute_error.<locals>.<listcomp>  s7     ( ( ( *U2Lmu6L ( ( (rc   zIt seems you're trying to use a module that doesn't come with our installer. Check <a href='{}'>this FAQ</a> in our docs to learn how to do this.Tr@  FN)	rG   r#   r  r[   anyr  r   r   MODULES_FAQ_URL)r]   rt  r  rb   s      r,   r  z"ShellWidget._process_execute_error  s    
 	k4  77<<<$ 	.	N;/E ( (!&( ( ( ) ) (( $ % % &,VO%<%<"& )    ).D%%%	. 	.rc   c                     | j                                          t          t          |                               |          S z7Reimplement Qt method to send focus change notification)sig_focus_changedr   rG   r#   focusInEventr]   eventrb   s     r,   r  zShellWidget.focusInEvent'  s6    ##%%%[$''44U;;;rc   c                     | j                                          t          t          |                               |          S r  )r  r   rG   r#   focusOutEventr  s     r,   r	  zShellWidget.focusOutEvent,  s6    ##%%%[$''55e<<<rc   )T)FFNNF)NFF)F)FF)Fr  r%  )j__name__
__module____qualname____doc__r   objectr   r   strsig_new_inline_figureintsig_pdb_stepboolr  sig_pdb_state_changedsig_pdb_prompt_readyr  r[  rs  r  r  r  r  r   rE   r%   classmethodr-   r5   rH   re   ro   rx   r|   rZ   ri   r~   r@   r   r   r   r   r   r   r   rQ   r   r=   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r   r!  r   r&  r7  r=  rO   r   r   ry  r  r  r  rJ  r  r  r   
QClipboard	Clipboardr  r  r  r  r  r  r  r  r  r  r   r   r  r  r  r  r  r	  __classcell__)rb   s   @r,   r#   r#   -   s         vf~~6&>>L #F63// 6#s##L"F4..!688 VXXNvf~~#)6#;; !688vxx %+F3KK! $VD\\ 	? 	? [	? 
& 
& [
&2$ 2$ 2$ 2$ 2$j  , , , , , ,: EI05
 
 
 
@< < <6 6 6    $F F F F F F2 2 2B B B  * * *C C C C.  A A A? ? ?< < <M M M M"E E EO O O
G G G
- - -' ' '. . .# # #% % %4 4 49 9 9E E E E
= = =
: : :
= = =
; ; ;
8 8 8
: : :
8 8 8) ) )V    
 
TVV. . V.) ) ) )84 4 4(3 3 3j	D 	D 	D3H 3H 3Hl  & & &P5 5 548 8 8"- - - 7<%./
 /
 /
 /
b
0 
0 
0( ( (( ( ( )3 'F 'F 'F 'FR+ + +.I I I+ + + + ++ + + + +) ) )@ @ @ @ @
' ' '4 4 4 4) ) ) ) ) W^	@ 	@ 	@ 	@	6 	6 	6) ) )' ' ' ' '
. . . . .(< < < < <
= = = = = = = = =rc   r#   )8r  r   os.pathpathr   rg  textwrapr   	threadingr   qtpy.QtCorer   r   r   qtpy.QtWidgetsr   qtpyr	   r
   r   	traitletsr   spyder.config.baser   r   r   r   spyder.config.guir   r   spyder.py3compatr   spyder.utils.paletter   r   spyder.utils.clipboard_helperr   spyder.utilsr   r   )spyder.plugins.ipythonconsole.utils.styler   r   spyder.widgets.helperwidgetsr   .spyder.plugins.ipythonconsole.comms.kernelcommr   %spyder.plugins.ipythonconsole.widgetsr   r   r   r   r    r!   r  r#   r  rc   r,   <module>r,     sJ   
 
			                    . - - - - - - - - - & & & & & & ) ) ) ) ) ) ) ) ) )      = = = = = = = = = = = = A A A A A A A A + + + + + + = = = = = = = = : : : : : : 1 1 1 1 1 1* * * * * * * * 8 8 8 8 8 8 E E E E E E. . . . . . . . . . . . . . . . F B= B= B= B= B='_%B= B= B= B= B=rc   