forked from spyder-ide/spyder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.py
1872 lines (1643 loc) · 80.6 KB
/
plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
IPython Console plugin based on QtConsole
"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
# Standard library imports
import atexit
import os
import os.path as osp
import uuid
import sys
import traceback
# Third party imports
from jupyter_client.connect import find_connection_file
from jupyter_core.paths import jupyter_config_dir, jupyter_runtime_dir
from qtconsole.client import QtKernelClient
from qtconsole.manager import QtKernelManager
from qtpy.QtCore import Qt, Signal, Slot
from qtpy.QtWidgets import (QApplication, QGridLayout, QGroupBox, QHBoxLayout,
QLabel, QMessageBox, QTabWidget, QVBoxLayout,
QWidget)
from traitlets.config.loader import Config, load_pyconfig_files
from zmq.ssh import tunnel as zmqtunnel
if not os.name == 'nt':
import pexpect
# Local imports
from spyder import dependencies
from spyder.config.base import _, get_conf_path, get_home_dir
from spyder.config.main import CONF
from spyder.api.plugins import SpyderPluginWidget
from spyder.api.preferences import PluginConfigPage
from spyder.py3compat import is_string, PY2, to_text_string
from spyder.plugins.ipythonconsole.utils.kernelspec import SpyderKernelSpec
from spyder.plugins.ipythonconsole.utils.style import create_qss_style
from spyder.utils.qthelpers import create_action, MENU_SEPARATOR
from spyder.utils import icon_manager as ima
from spyder.utils import encoding, programs, sourcecode
from spyder.utils.programs import get_temp_dir
from spyder.utils.misc import get_error_match, remove_backslashes
from spyder.widgets.findreplace import FindReplace
from spyder.plugins.ipythonconsole.widgets import ClientWidget
from spyder.plugins.ipythonconsole.widgets import KernelConnectionDialog
from spyder.widgets.tabs import Tabs
# Dependencies
SYMPY_REQVER = '>=0.7.3'
dependencies.add("sympy", _("Symbolic mathematics in the IPython Console"),
required_version=SYMPY_REQVER, optional=True)
CYTHON_REQVER = '>=0.21'
dependencies.add("cython", _("Run Cython files in the IPython Console"),
required_version=CYTHON_REQVER, optional=True)
QTCONSOLE_REQVER = ">=4.2.0"
dependencies.add("qtconsole", _("Integrate the IPython console"),
required_version=QTCONSOLE_REQVER)
IPYTHON_REQVER = ">=4.0;<6.0" if PY2 else ">=4.0"
dependencies.add("IPython", _("IPython interactive python environment"),
required_version=IPYTHON_REQVER)
MATPLOTLIB_REQVER = '>=2.0.0'
dependencies.add("matplotlib", _("Display 2D graphics in the IPython Console"),
required_version=MATPLOTLIB_REQVER, optional=True)
#------------------------------------------------------------------------------
# Existing kernels
#------------------------------------------------------------------------------
# Replacing pyzmq openssh_tunnel method to work around the issue
# https://github.com/zeromq/pyzmq/issues/589 which was solved in pyzmq
# https://github.com/zeromq/pyzmq/pull/615
def _stop_tunnel(cmd):
pexpect.run(cmd)
def openssh_tunnel(self, lport, rport, server, remoteip='127.0.0.1',
keyfile=None, password=None, timeout=0.4):
ssh="ssh "
if keyfile:
ssh += "-i " + keyfile
if ':' in server:
server, port = server.split(':')
ssh += " -p %s" % port
cmd = "%s -O check %s" % (ssh, server)
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
if not exitstatus:
pid = int(output[output.find("(pid=")+5:output.find(")")])
cmd = "%s -O forward -L 127.0.0.1:%i:%s:%i %s" % (
ssh, lport, remoteip, rport, server)
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
if not exitstatus:
atexit.register(_stop_tunnel, cmd.replace("-O forward",
"-O cancel",
1))
return pid
cmd = "%s -f -S none -L 127.0.0.1:%i:%s:%i %s sleep %i" % (
ssh, lport, remoteip, rport, server, timeout)
# pop SSH_ASKPASS from env
env = os.environ.copy()
env.pop('SSH_ASKPASS', None)
ssh_newkey = 'Are you sure you want to continue connecting'
tunnel = pexpect.spawn(cmd, env=env)
failed = False
while True:
try:
i = tunnel.expect([ssh_newkey, '[Pp]assword:'], timeout=.1)
if i==0:
host = server.split('@')[-1]
question = _("The authenticity of host <b>%s</b> can't be "
"established. Are you sure you want to continue "
"connecting?") % host
reply = QMessageBox.question(self, _('Warning'), question,
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.Yes:
tunnel.sendline('yes')
continue
else:
tunnel.sendline('no')
raise RuntimeError(
_("The authenticity of the host can't be established"))
if i==1 and password is not None:
tunnel.sendline(password)
except pexpect.TIMEOUT:
continue
except pexpect.EOF:
if tunnel.exitstatus:
raise RuntimeError(_("Tunnel '%s' failed to start") % cmd)
else:
return tunnel.pid
else:
if failed or password is None:
raise RuntimeError(_("Could not connect to remote host"))
# TODO: Use this block when pyzmq bug #620 is fixed
# # Prompt a passphrase dialog to the user for a second attempt
# password, ok = QInputDialog.getText(self, _('Password'),
# _('Enter password for: ') + server,
# echo=QLineEdit.Password)
# if ok is False:
# raise RuntimeError('Could not connect to remote host.')
tunnel.sendline(password)
failed = True
#------------------------------------------------------------------------------
# Config page
#------------------------------------------------------------------------------
class IPythonConsoleConfigPage(PluginConfigPage):
def __init__(self, plugin, parent):
PluginConfigPage.__init__(self, plugin, parent)
self.get_name = lambda: _("IPython console")
def setup_page(self):
newcb = self.create_checkbox
# Interface Group
interface_group = QGroupBox(_("Interface"))
banner_box = newcb(_("Display initial banner"), 'show_banner',
tip=_("This option lets you hide the message shown at\n"
"the top of the console when it's opened."))
pager_box = newcb(_("Use a pager to display additional text inside "
"the console"), 'use_pager',
tip=_("Useful if you don't want to fill the "
"console with long help or completion "
"texts.\n"
"Note: Use the Q key to get out of the "
"pager."))
calltips_box = newcb(_("Display balloon tips"), 'show_calltips')
ask_box = newcb(_("Ask for confirmation before closing"),
'ask_before_closing')
reset_namespace_box = newcb(
_("Ask for confirmation before removing all user-defined "
"variables"),
'show_reset_namespace_warning',
tip=_("This option lets you hide the warning message shown\n"
"when resetting the namespace from Spyder."))
show_time_box = newcb(_("Show elapsed time"), 'show_elapsed_time')
ask_restart_box = newcb(
_("Ask for confirmation before restarting"),
'ask_before_restart',
tip=_("This option lets you hide the warning message shown\n"
"when restarting the kernel."))
interface_layout = QVBoxLayout()
interface_layout.addWidget(banner_box)
interface_layout.addWidget(pager_box)
interface_layout.addWidget(calltips_box)
interface_layout.addWidget(ask_box)
interface_layout.addWidget(reset_namespace_box)
interface_layout.addWidget(show_time_box)
interface_layout.addWidget(ask_restart_box)
interface_group.setLayout(interface_layout)
comp_group = QGroupBox(_("Completion Type"))
comp_label = QLabel(_("Decide what type of completion to use"))
comp_label.setWordWrap(True)
completers = [(_("Graphical"), 0), (_("Terminal"), 1), (_("Plain"), 2)]
comp_box = self.create_combobox(_("Completion:")+" ", completers,
'completion_type')
comp_layout = QVBoxLayout()
comp_layout.addWidget(comp_label)
comp_layout.addWidget(comp_box)
comp_group.setLayout(comp_layout)
# Source Code Group
source_code_group = QGroupBox(_("Source code"))
buffer_spin = self.create_spinbox(
_("Buffer: "), _(" lines"),
'buffer_size', min_=-1, max_=1000000, step=100,
tip=_("Set the maximum number of lines of text shown in the\n"
"console before truncation. Specifying -1 disables it\n"
"(not recommended!)"))
source_code_layout = QVBoxLayout()
source_code_layout.addWidget(buffer_spin)
source_code_group.setLayout(source_code_layout)
# --- Graphics ---
# Pylab Group
pylab_group = QGroupBox(_("Support for graphics (Matplotlib)"))
pylab_box = newcb(_("Activate support"), 'pylab')
autoload_pylab_box = newcb(_("Automatically load Pylab and NumPy "
"modules"),
'pylab/autoload',
tip=_("This lets you load graphics support "
"without importing \nthe commands to do "
"plots. Useful to work with other\n"
"plotting libraries different to "
"Matplotlib or to develop \nGUIs with "
"Spyder."))
autoload_pylab_box.setEnabled(self.get_option('pylab'))
pylab_box.toggled.connect(autoload_pylab_box.setEnabled)
pylab_layout = QVBoxLayout()
pylab_layout.addWidget(pylab_box)
pylab_layout.addWidget(autoload_pylab_box)
pylab_group.setLayout(pylab_layout)
# Pylab backend Group
inline = _("Inline")
automatic = _("Automatic")
backend_group = QGroupBox(_("Graphics backend"))
bend_label = QLabel(_("Decide how graphics are going to be displayed "
"in the console. If unsure, please select "
"<b>%s</b> to put graphics inside the "
"console or <b>%s</b> to interact with "
"them (through zooming and panning) in a "
"separate window.") % (inline, automatic))
bend_label.setWordWrap(True)
backends = [(inline, 0), (automatic, 1), ("Qt5", 2), ("Qt4", 3)]
if sys.platform == 'darwin':
backends.append( ("OS X", 4) )
if sys.platform.startswith('linux'):
backends.append( ("Gtk3", 5) )
backends.append( ("Gtk", 6) )
if PY2:
backends.append( ("Wx", 7) )
backends.append( ("Tkinter", 8) )
backends = tuple(backends)
backend_box = self.create_combobox( _("Backend:")+" ", backends,
'pylab/backend', default=0,
tip=_("This option will be applied the "
"next time a console is opened."))
backend_layout = QVBoxLayout()
backend_layout.addWidget(bend_label)
backend_layout.addWidget(backend_box)
backend_group.setLayout(backend_layout)
backend_group.setEnabled(self.get_option('pylab'))
pylab_box.toggled.connect(backend_group.setEnabled)
# Inline backend Group
inline_group = QGroupBox(_("Inline backend"))
inline_label = QLabel(_("Decide how to render the figures created by "
"this backend"))
inline_label.setWordWrap(True)
formats = (("PNG", 0), ("SVG", 1))
format_box = self.create_combobox(_("Format:")+" ", formats,
'pylab/inline/figure_format',
default=0)
resolution_spin = self.create_spinbox(
_("Resolution:")+" ", " "+_("dpi"),
'pylab/inline/resolution', min_=50, max_=999, step=0.1,
tip=_("Only used when the format is PNG. Default is "
"72"))
width_spin = self.create_spinbox(
_("Width:")+" ", " "+_("inches"),
'pylab/inline/width', min_=2, max_=20, step=1,
tip=_("Default is 6"))
height_spin = self.create_spinbox(
_("Height:")+" ", " "+_("inches"),
'pylab/inline/height', min_=1, max_=20, step=1,
tip=_("Default is 4"))
bbox_inches_box = newcb(
_("Use a tight layout for inline plots"),
'pylab/inline/bbox_inches',
tip=_("Sets bbox_inches to \"tight\" when\n"
"plotting inline with matplotlib.\n"
"When enabled, can cause discrepancies\n"
"between the image displayed inline and\n"
"that created using savefig."))
inline_v_layout = QVBoxLayout()
inline_v_layout.addWidget(inline_label)
inline_layout = QGridLayout()
inline_layout.addWidget(format_box.label, 1, 0)
inline_layout.addWidget(format_box.combobox, 1, 1)
inline_layout.addWidget(resolution_spin.plabel, 2, 0)
inline_layout.addWidget(resolution_spin.spinbox, 2, 1)
inline_layout.addWidget(resolution_spin.slabel, 2, 2)
inline_layout.addWidget(width_spin.plabel, 3, 0)
inline_layout.addWidget(width_spin.spinbox, 3, 1)
inline_layout.addWidget(width_spin.slabel, 3, 2)
inline_layout.addWidget(height_spin.plabel, 4, 0)
inline_layout.addWidget(height_spin.spinbox, 4, 1)
inline_layout.addWidget(height_spin.slabel, 4, 2)
inline_layout.addWidget(bbox_inches_box, 5, 0, 1, 4)
inline_h_layout = QHBoxLayout()
inline_h_layout.addLayout(inline_layout)
inline_h_layout.addStretch(1)
inline_v_layout.addLayout(inline_h_layout)
inline_group.setLayout(inline_v_layout)
inline_group.setEnabled(self.get_option('pylab'))
pylab_box.toggled.connect(inline_group.setEnabled)
# --- Startup ---
# Run lines Group
run_lines_group = QGroupBox(_("Run code"))
run_lines_label = QLabel(_("You can run several lines of code when "
"a console is started. Please introduce "
"each one separated by semicolons and a "
"space, for example:<br>"
"<i>import os; import sys</i>"))
run_lines_label.setWordWrap(True)
run_lines_edit = self.create_lineedit(_("Lines:"), 'startup/run_lines',
'', alignment=Qt.Horizontal)
run_lines_layout = QVBoxLayout()
run_lines_layout.addWidget(run_lines_label)
run_lines_layout.addWidget(run_lines_edit)
run_lines_group.setLayout(run_lines_layout)
# Run file Group
run_file_group = QGroupBox(_("Run a file"))
run_file_label = QLabel(_("You can also run a whole file at startup "
"instead of just some lines (This is "
"similar to have a PYTHONSTARTUP file)."))
run_file_label.setWordWrap(True)
file_radio = newcb(_("Use the following file:"),
'startup/use_run_file', False)
run_file_browser = self.create_browsefile('', 'startup/run_file', '')
run_file_browser.setEnabled(False)
file_radio.toggled.connect(run_file_browser.setEnabled)
run_file_layout = QVBoxLayout()
run_file_layout.addWidget(run_file_label)
run_file_layout.addWidget(file_radio)
run_file_layout.addWidget(run_file_browser)
run_file_group.setLayout(run_file_layout)
# ---- Advanced settings ----
# Enable Jedi completion
jedi_group = QGroupBox(_("Jedi completion"))
jedi_label = QLabel(_("Enable Jedi-based <tt>Tab</tt> completion "
"in the IPython console; similar to the "
"greedy completer, but without evaluating "
"the code.<br>"
"<b>Warning:</b> Slows down your console "
"when working with large dataframes!"))
jedi_label.setWordWrap(True)
jedi_box = newcb(_("Use Jedi completion in the IPython console"),
"jedi_completer",
tip="<b>Warning</b>: "
"Slows down your console when working with "
"large dataframes!<br>"
"Allows completion of nested lists etc.")
jedi_layout = QVBoxLayout()
jedi_layout.addWidget(jedi_label)
jedi_layout.addWidget(jedi_box)
jedi_group.setLayout(jedi_layout)
# Greedy completer group
greedy_group = QGroupBox(_("Greedy completion"))
greedy_label = QLabel(_("Enable <tt>Tab</tt> completion on elements "
"of lists, results of function calls, etc, "
"<i>without</i> assigning them to a variable, "
"like <tt>li[0].<Tab></tt> or "
"<tt>ins.meth().<Tab></tt> <br>"
"<b>Warning:</b> Due to a bug, IPython's "
"greedy completer requires a leading "
"<tt><Space></tt> for some completions; "
"e.g. <tt>np.sin(<Space>np.<Tab>"
"</tt> works while <tt>np.sin(np.<Tab> "
"</tt> doesn't."))
greedy_label.setWordWrap(True)
greedy_box = newcb(_("Use greedy completion in the IPython console"),
"greedy_completer",
tip="<b>Warning</b>: It can be unsafe because the "
"code is actually evaluated when you press "
"<tt>Tab</tt>.")
greedy_layout = QVBoxLayout()
greedy_layout.addWidget(greedy_label)
greedy_layout.addWidget(greedy_box)
greedy_group.setLayout(greedy_layout)
# Autocall group
autocall_group = QGroupBox(_("Autocall"))
autocall_label = QLabel(_("Autocall makes IPython automatically call "
"any callable object even if you didn't "
"type explicit parentheses.<br>"
"For example, if you type <i>str 43</i> it "
"becomes <i>str(43)</i> automatically."))
autocall_label.setWordWrap(True)
smart = _('Smart')
full = _('Full')
autocall_opts = ((_('Off'), 0), (smart, 1), (full, 2))
autocall_box = self.create_combobox(
_("Autocall: "), autocall_opts, 'autocall', default=0,
tip=_("On <b>%s</b> mode, Autocall is not applied if "
"there are no arguments after the callable. On "
"<b>%s</b> mode, all callable objects are "
"automatically called (even if no arguments are "
"present).") % (smart, full))
autocall_layout = QVBoxLayout()
autocall_layout.addWidget(autocall_label)
autocall_layout.addWidget(autocall_box)
autocall_group.setLayout(autocall_layout)
# Sympy group
sympy_group = QGroupBox(_("Symbolic Mathematics"))
sympy_label = QLabel(_("Perfom symbolic operations in the console "
"(e.g. integrals, derivatives, vector calculus, "
"etc) and get the outputs in a beautifully "
"printed style (it requires the Sympy module)."))
sympy_label.setWordWrap(True)
sympy_box = newcb(_("Use symbolic math"), "symbolic_math",
tip=_("This option loads the Sympy library to work "
"with.<br>Please refer to its documentation to "
"learn how to use it."))
sympy_layout = QVBoxLayout()
sympy_layout.addWidget(sympy_label)
sympy_layout.addWidget(sympy_box)
sympy_group.setLayout(sympy_layout)
# Prompts group
prompts_group = QGroupBox(_("Prompts"))
prompts_label = QLabel(_("Modify how Input and Output prompts are "
"shown in the console."))
prompts_label.setWordWrap(True)
in_prompt_edit = self.create_lineedit(_("Input prompt:"),
'in_prompt', '',
_('Default is<br>'
'In [<span class="in-prompt-number">'
'%i</span>]:'),
alignment=Qt.Horizontal)
out_prompt_edit = self.create_lineedit(_("Output prompt:"),
'out_prompt', '',
_('Default is<br>'
'Out[<span class="out-prompt-number">'
'%i</span>]:'),
alignment=Qt.Horizontal)
prompts_layout = QVBoxLayout()
prompts_layout.addWidget(prompts_label)
prompts_g_layout = QGridLayout()
prompts_g_layout.addWidget(in_prompt_edit.label, 0, 0)
prompts_g_layout.addWidget(in_prompt_edit.textbox, 0, 1)
prompts_g_layout.addWidget(out_prompt_edit.label, 1, 0)
prompts_g_layout.addWidget(out_prompt_edit.textbox, 1, 1)
prompts_layout.addLayout(prompts_g_layout)
prompts_group.setLayout(prompts_layout)
# --- Tabs organization ---
tabs = QTabWidget()
tabs.addTab(self.create_tab(interface_group, comp_group,
source_code_group), _("Display"))
tabs.addTab(self.create_tab(pylab_group, backend_group, inline_group),
_("Graphics"))
tabs.addTab(self.create_tab(run_lines_group, run_file_group),
_("Startup"))
tabs.addTab(self.create_tab(jedi_group, greedy_group, autocall_group, sympy_group,
prompts_group), _("Advanced Settings"))
vlayout = QVBoxLayout()
vlayout.addWidget(tabs)
self.setLayout(vlayout)
#------------------------------------------------------------------------------
# Plugin widget
#------------------------------------------------------------------------------
class IPythonConsole(SpyderPluginWidget):
"""
IPython Console plugin
This is a widget with tabs where each one is a ClientWidget
"""
CONF_SECTION = 'ipython_console'
CONFIGWIDGET_CLASS = IPythonConsoleConfigPage
DISABLE_ACTIONS_WHEN_HIDDEN = False
# Signals
focus_changed = Signal()
edit_goto = Signal((str, int, str), (str, int, str, bool))
# Error messages
permission_error_msg = _("The directory {} is not writable and it is "
"required to create IPython consoles. Please "
"make it writable.")
def __init__(self, parent, test_dir=None, test_no_stderr=False,
css_path=None):
"""Ipython Console constructor."""
SpyderPluginWidget.__init__(self, parent)
self.tabwidget = None
self.menu_actions = None
self.master_clients = 0
self.clients = []
self.filenames = []
self.mainwindow_close = False
self.create_new_client_if_empty = True
self.css_path = css_path
self.run_cell_filename = None
# Attrs for testing
self.test_dir = test_dir
self.test_no_stderr = test_no_stderr
# Create temp dir on testing to save kernel errors
if self.test_dir is not None:
if not osp.isdir(osp.join(test_dir)):
os.makedirs(osp.join(test_dir))
layout = QVBoxLayout()
self.tabwidget = Tabs(self, menu=self.options_menu, actions=self.menu_actions,
rename_tabs=True,
split_char='/', split_index=0)
if hasattr(self.tabwidget, 'setDocumentMode')\
and not sys.platform == 'darwin':
# Don't set document mode to true on OSX because it generates
# a crash when the console is detached from the main window
# Fixes Issue 561
self.tabwidget.setDocumentMode(True)
self.tabwidget.currentChanged.connect(self.refresh_plugin)
self.tabwidget.tabBar().tabMoved.connect(self.move_tab)
self.tabwidget.tabBar().sig_change_name.connect(
self.rename_tabs_after_change)
self.tabwidget.set_close_function(self.close_client)
if sys.platform == 'darwin':
tab_container = QWidget()
tab_container.setObjectName('tab-container')
tab_layout = QHBoxLayout(tab_container)
tab_layout.setContentsMargins(0, 0, 0, 0)
tab_layout.addWidget(self.tabwidget)
layout.addWidget(tab_container)
else:
layout.addWidget(self.tabwidget)
# Find/replace widget
self.find_widget = FindReplace(self)
self.find_widget.hide()
self.register_widget_shortcuts(self.find_widget)
layout.addWidget(self.find_widget)
self.setLayout(layout)
# Accepting drops
self.setAcceptDrops(True)
# Initialize plugin
self.initialize_plugin()
#------ SpyderPluginMixin API ---------------------------------------------
def update_font(self):
"""Update font from Preferences"""
font = self.get_plugin_font()
for client in self.clients:
client.set_font(font)
def apply_plugin_settings(self, options):
"""Apply configuration file's plugin settings"""
font_n = 'plugin_font'
font_o = self.get_plugin_font()
help_n = 'connect_to_oi'
help_o = CONF.get('help', 'connect/ipython_console')
color_scheme_n = 'color_scheme_name'
color_scheme_o = CONF.get('appearance', 'selected')
show_time_n = 'show_elapsed_time'
show_time_o = self.get_option(show_time_n)
reset_namespace_n = 'show_reset_namespace_warning'
reset_namespace_o = self.get_option(reset_namespace_n)
ask_before_restart_n = 'ask_before_restart'
ask_before_restart_o = self.get_option(ask_before_restart_n)
for client in self.clients:
control = client.get_control()
if font_n in options:
client.set_font(font_o)
if help_n in options and control is not None:
control.set_help_enabled(help_o)
if color_scheme_n in options:
client.set_color_scheme(color_scheme_o)
if show_time_n in options:
client.show_time_action.setChecked(show_time_o)
client.set_elapsed_time_visible(show_time_o)
if reset_namespace_n in options:
client.reset_warning = reset_namespace_o
if ask_before_restart_n in options:
client.ask_before_restart = ask_before_restart_o
def toggle_view(self, checked):
"""Toggle view"""
if checked:
self.dockwidget.show()
self.dockwidget.raise_()
# Start a client in case there are none shown
if not self.clients:
if self.main.is_setting_up:
self.create_new_client(give_focus=False)
else:
self.create_new_client(give_focus=True)
else:
self.dockwidget.hide()
#------ SpyderPluginWidget API --------------------------------------------
def get_plugin_title(self):
"""Return widget title"""
return _('IPython console')
def get_plugin_icon(self):
"""Return widget icon"""
return ima.icon('ipython_console')
def get_focus_widget(self):
"""
Return the widget to give focus to when
this plugin's dockwidget is raised on top-level
"""
client = self.tabwidget.currentWidget()
if client is not None:
return client.get_control()
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.mainwindow_close = True
for client in self.clients:
client.shutdown()
client.remove_stderr_file()
client.close()
return True
def refresh_plugin(self):
"""Refresh tabwidget"""
client = None
if self.tabwidget.count():
# Give focus to the control widget of the selected tab
client = self.tabwidget.currentWidget()
control = client.get_control()
control.setFocus()
buttons = [[b, -7] for b in client.get_toolbar_buttons()]
buttons = sum(buttons, [])[:-1]
widgets = [client.create_time_label()] + buttons
else:
control = None
widgets = []
self.find_widget.set_editor(control)
self.tabwidget.set_corner_widgets({Qt.TopRightCorner: widgets})
if client:
sw = client.shellwidget
self.main.variableexplorer.set_shellwidget_from_id(id(sw))
self.main.plots.set_shellwidget_from_id(id(sw))
self.main.help.set_shell(sw)
self.update_tabs_text()
self.sig_update_plugin_title.emit()
def get_plugin_actions(self):
"""Return a list of actions related to plugin."""
create_client_action = create_action(
self,
_("New console (default settings)"),
icon=ima.icon('ipython_console'),
triggered=self.create_new_client,
context=Qt.WidgetWithChildrenShortcut)
self.register_shortcut(create_client_action, context="ipython_console",
name="New tab")
create_pylab_action = create_action(
self,
_("New Pylab console (data plotting)"),
icon=ima.icon('ipython_console'),
triggered=self.create_pylab_client,
context=Qt.WidgetWithChildrenShortcut)
create_sympy_action = create_action(
self,
_("New SymPy console (symbolic math)"),
icon=ima.icon('ipython_console'),
triggered=self.create_sympy_client,
context=Qt.WidgetWithChildrenShortcut)
create_cython_action = create_action(
self,
_("New Cython console (Python with "
"C extensions)"),
icon=ima.icon('ipython_console'),
triggered=self.create_cython_client,
context=Qt.WidgetWithChildrenShortcut)
restart_action = create_action(self, _("Restart kernel"),
icon=ima.icon('restart'),
triggered=self.restart_kernel,
context=Qt.WidgetWithChildrenShortcut)
self.register_shortcut(restart_action, context="ipython_console",
name="Restart kernel")
connect_to_kernel_action = create_action(self,
_("Connect to an existing kernel"), None, None,
_("Open a new IPython console connected to an existing kernel"),
triggered=self.create_client_for_kernel)
rename_tab_action = create_action(self, _("Rename tab"),
icon=ima.icon('rename'),
triggered=self.tab_name_editor)
# Add the action to the 'Consoles' menu on the main window
main_consoles_menu = self.main.consoles_menu_actions
main_consoles_menu.insert(0, create_client_action)
main_consoles_menu.insert(1, create_pylab_action)
main_consoles_menu.insert(2, create_sympy_action)
main_consoles_menu.insert(3, create_cython_action)
main_consoles_menu += [MENU_SEPARATOR, restart_action,
connect_to_kernel_action,
MENU_SEPARATOR]
# Plugin actions
self.menu_actions = [create_client_action, create_pylab_action,
create_sympy_action, create_cython_action,
MENU_SEPARATOR,
restart_action, connect_to_kernel_action,
MENU_SEPARATOR, rename_tab_action,
MENU_SEPARATOR]
# Check for a current client. Since it manages more actions.
client = self.get_current_client()
if client:
return client.get_options_menu()
return self.menu_actions
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.main.add_dockwidget(self)
self.focus_changed.connect(self.main.plugin_focus_changed)
self.edit_goto.connect(self.main.editor.load)
self.edit_goto[str, int, str, bool].connect(
lambda fname, lineno, word, processevents:
self.main.editor.load(fname, lineno, word,
processevents=processevents))
self.main.editor.breakpoints_saved.connect(self.set_spyder_breakpoints)
self.main.editor.run_in_current_ipyclient.connect(self.run_script)
self.main.editor.run_cell_in_ipyclient.connect(self.run_cell)
self.main.workingdirectory.set_current_console_wd.connect(
self.set_current_client_working_directory)
self.tabwidget.currentChanged.connect(self.update_working_directory)
self._remove_old_stderr_files()
#------ Public API (for clients) ------------------------------------------
def get_clients(self):
"""Return clients list"""
return [cl for cl in self.clients if isinstance(cl, ClientWidget)]
def get_focus_client(self):
"""Return current client with focus, if any"""
widget = QApplication.focusWidget()
for client in self.get_clients():
if widget is client or widget is client.get_control():
return client
def get_current_client(self):
"""Return the currently selected client"""
client = self.tabwidget.currentWidget()
if client is not None:
return client
def get_current_shellwidget(self):
"""Return the shellwidget of the current client"""
client = self.get_current_client()
if client is not None:
return client.shellwidget
def run_script(self, filename, wdir, args, debug, post_mortem,
current_client, clear_variables):
"""Run script in current or dedicated client"""
norm = lambda text: remove_backslashes(to_text_string(text))
# Run Cython files in a dedicated console
is_cython = osp.splitext(filename)[1] == '.pyx'
if is_cython:
current_client = False
# Select client to execute code on it
is_new_client = False
if current_client:
client = self.get_current_client()
else:
client = self.get_client_for_file(filename)
if client is None:
self.create_client_for_file(filename, is_cython=is_cython)
client = self.get_current_client()
is_new_client = True
if client is not None:
# Internal kernels, use runfile
if client.get_kernel() is not None:
line = "%s('%s'" % ('debugfile' if debug else 'runfile',
norm(filename))
if args:
line += ", args='%s'" % norm(args)
if wdir:
line += ", wdir='%s'" % norm(wdir)
if post_mortem:
line += ", post_mortem=True"
line += ")"
else: # External kernels, use %run
line = "%run "
if debug:
line += "-d "
line += "\"%s\"" % to_text_string(filename)
if args:
line += " %s" % norm(args)
try:
if client.shellwidget._executing:
# Don't allow multiple executions when there's
# still an execution taking place
# Fixes issue 7293
pass
elif client.shellwidget._reading:
client.shellwidget._append_html(
_("<br><b>Please exit from debugging before trying to "
"run a file in this console.</b>\n<hr><br>"),
before_prompt=True)
return
elif current_client:
self.execute_code(line, current_client, clear_variables)
else:
if is_new_client:
client.shellwidget.silent_execute('%clear')
else:
client.shellwidget.execute('%clear')
client.shellwidget.sig_prompt_ready.connect(
lambda: self.execute_code(line, current_client,
clear_variables))
except AttributeError:
pass
self.switch_to_plugin()
else:
#XXX: not sure it can really happen
QMessageBox.warning(self, _('Warning'),
_("No IPython console is currently available to run <b>%s</b>."
"<br><br>Please open a new one and try again."
) % osp.basename(filename), QMessageBox.Ok)
def run_cell(self, code, cell_name, filename, run_cell_copy):
"""Run cell in current or dedicated client."""
def norm(text):
return remove_backslashes(to_text_string(text))
self.run_cell_filename = filename
# Select client to execute code on it
client = self.get_client_for_file(filename)
if client is None:
client = self.get_current_client()
is_internal_kernel = False
if client is not None:
# Internal kernels, use runcell
if client.get_kernel() is not None and not run_cell_copy:
line = (to_text_string("{}('{}','{}')")
.format(to_text_string('runcell'),
(to_text_string(cell_name).replace("\\","\\\\")
.replace("'", r"\'")),
norm(filename).replace("'", r"\'")))
is_internal_kernel = True
# External kernels and run_cell_copy, just execute the code
else:
line = code.strip()
try:
if client.shellwidget._executing:
# Don't allow multiple executions when there's
# still an execution taking place
# Fixes issue 7293
pass
elif client.shellwidget._reading:
client.shellwidget._append_html(
_("<br><b>Exit the debugger before trying to "
"run a cell in this console.</b>\n<hr><br>"),
before_prompt=True)
return
else:
if is_internal_kernel:
client.shellwidget.silent_execute(
to_text_string('get_ipython().cell_code = '
'"""{}"""')
.format(to_text_string(code)
.replace('\\', r'\\')
.replace('"""', r'\"\"\"')))
self.execute_code(line)
except AttributeError:
pass
self.visibility_changed(True)
self.raise_()
else:
# XXX: not sure it can really happen
QMessageBox.warning(self, _('Warning'),
_("No IPython console is currently available "
"to run <b>{}</b>.<br><br>Please open a new "
"one and try again."
).format(osp.basename(filename)),
QMessageBox.Ok)
def set_current_client_working_directory(self, directory):
"""Set current client working directory."""
shellwidget = self.get_current_shellwidget()
if shellwidget is not None:
shellwidget.set_cwd(directory)
def set_working_directory(self, dirname):
"""Set current working directory.
In the workingdirectory and explorer plugins.
"""
if dirname:
self.main.workingdirectory.chdir(dirname, refresh_explorer=True,
refresh_console=False)
def update_working_directory(self):
"""Update working directory to console cwd."""
shellwidget = self.get_current_shellwidget()
if shellwidget is not None:
shellwidget.get_cwd()
def execute_code(self, lines, current_client=True, clear_variables=False):
"""Execute code instructions."""
sw = self.get_current_shellwidget()
if sw is not None:
if sw._reading:
pass
else:
if not current_client:
# Clear console and reset namespace for
# dedicated clients
# See issue 5748
try:
sw.sig_prompt_ready.disconnect()
except TypeError:
pass
sw.reset_namespace(warning=False)
elif current_client and clear_variables:
sw.reset_namespace(warning=False)
# Needed to handle an error when kernel_client is none
# See issue 6308
try:
sw.execute(to_text_string(lines))
except AttributeError:
pass