forked from spyder-ide/spyder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.py
3002 lines (2685 loc) · 137 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)
"""Editor Plugin"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
# Standard library imports
import logging
import os
import os.path as osp
import re
import time
# Third party imports
from qtpy import API
from qtpy.compat import from_qvariant, getopenfilenames, to_qvariant
from qtpy.QtCore import QByteArray, Qt, Signal, Slot
from qtpy.QtGui import QKeySequence
from qtpy.QtPrintSupport import QAbstractPrintDialog, QPrintDialog, QPrinter
from qtpy.QtWidgets import (QAction, QActionGroup, QApplication, QDialog,
QFileDialog, QGridLayout, QGroupBox, QHBoxLayout,
QInputDialog, QLabel, QMenu, QSplitter, QTabWidget,
QToolBar, QVBoxLayout, QWidget)
# Local imports
from spyder import dependencies
from spyder.config.base import _, get_conf_path, running_under_pytest
from spyder.config.main import (CONF, RUN_CELL_SHORTCUT,
RUN_CELL_AND_ADVANCE_SHORTCUT)
from spyder.config.utils import (get_edit_filetypes, get_edit_filters,
get_filter)
from spyder.py3compat import PY2, qbytearray_to_str, to_text_string
from spyder.utils import codeanalysis, encoding, programs, sourcecode
from spyder.utils import icon_manager as ima
from spyder.utils.qthelpers import create_action, add_actions, MENU_SEPARATOR
from spyder.utils.misc import getcwd_or_home
from spyder.widgets.findreplace import FindReplace
from spyder.plugins.editor.widgets.editor import (EditorMainWindow, Printer,
EditorSplitter, EditorStack,)
from spyder.plugins.editor.widgets.codeeditor import CodeEditor
from spyder.widgets.status import (CursorPositionStatus, EncodingStatus,
EOLStatus, ReadWriteStatus)
from spyder.api.plugins import SpyderPluginWidget
from spyder.api.preferences import PluginConfigPage
from spyder.preferences.runconfig import (ALWAYS_OPEN_FIRST_RUN_OPTION,
get_run_configuration,
RunConfigDialog, RunConfigOneDialog)
from spyder.plugins.editor.lsp import LSPEventTypes
logger = logging.getLogger(__name__)
# Dependencies
PYLS_REQVER = '>=0.19.0'
dependencies.add('pyls',
_("Editor's code completion, go-to-definition, help and "
"real-time code analysis"),
required_version=PYLS_REQVER)
NBCONVERT_REQVER = ">=4.0"
dependencies.add("nbconvert", _("Manipulate Jupyter notebooks on the Editor"),
required_version=NBCONVERT_REQVER)
def _load_all_breakpoints():
bp_dict = CONF.get('run', 'breakpoints', {})
for filename in list(bp_dict.keys()):
if not osp.isfile(filename):
bp_dict.pop(filename)
return bp_dict
def load_breakpoints(filename):
breakpoints = _load_all_breakpoints().get(filename, [])
if breakpoints and isinstance(breakpoints[0], int):
# Old breakpoints format
breakpoints = [(lineno, None) for lineno in breakpoints]
return breakpoints
def save_breakpoints(filename, breakpoints):
if not osp.isfile(filename):
return
bp_dict = _load_all_breakpoints()
bp_dict[filename] = breakpoints
CONF.set('run', 'breakpoints', bp_dict)
def clear_all_breakpoints():
CONF.set('run', 'breakpoints', {})
def clear_breakpoint(filename, lineno):
breakpoints = load_breakpoints(filename)
if breakpoints:
for breakpoint in breakpoints[:]:
if breakpoint[0] == lineno:
breakpoints.remove(breakpoint)
save_breakpoints(filename, breakpoints)
WINPDB_PATH = programs.find_program('winpdb')
class EditorConfigPage(PluginConfigPage):
def get_name(self):
return _("Editor")
def get_icon(self):
return ima.icon('edit')
def setup_page(self):
template_btn = self.create_button(_("Edit template for new modules"),
self.plugin.edit_template)
interface_group = QGroupBox(_("Interface"))
newcb = self.create_checkbox
showtabbar_box = newcb(_("Show tab bar"), 'show_tab_bar')
showclassfuncdropdown_box = newcb(
_("Show selector for classes and functions"),
'show_class_func_dropdown')
showindentguides_box = newcb(_("Show Indent Guides"),
'indent_guides')
interface_layout = QVBoxLayout()
interface_layout.addWidget(showtabbar_box)
interface_layout.addWidget(showclassfuncdropdown_box)
interface_layout.addWidget(showindentguides_box)
interface_group.setLayout(interface_layout)
display_group = QGroupBox(_("Source code"))
linenumbers_box = newcb(_("Show line numbers"), 'line_numbers')
blanks_box = newcb(_("Show blank spaces"), 'blank_spaces')
edgeline_box = newcb(_("Show vertical lines after"), 'edge_line')
edgeline_edit = self.create_lineedit("", 'edge_line_columns',
tip=("Enter values separated by "
"commas ','"),
alignment=Qt.Horizontal,
regex="[0-9]+(,[0-9]+)*")
edgeline_edit_label = QLabel(_("characters"))
edgeline_box.toggled.connect(edgeline_edit.setEnabled)
edgeline_box.toggled.connect(edgeline_edit_label.setEnabled)
edgeline_edit.setEnabled(self.get_option('edge_line'))
edgeline_edit_label.setEnabled(self.get_option('edge_line'))
currentline_box = newcb(_("Highlight current line"),
'highlight_current_line')
currentcell_box = newcb(_("Highlight current cell"),
'highlight_current_cell')
occurrence_box = newcb(_("Highlight occurrences after"),
'occurrence_highlighting')
occurrence_spin = self.create_spinbox(
"", _(" ms"),
'occurrence_highlighting/timeout',
min_=100, max_=1000000, step=100)
occurrence_box.toggled.connect(occurrence_spin.spinbox.setEnabled)
occurrence_box.toggled.connect(occurrence_spin.slabel.setEnabled)
occurrence_spin.spinbox.setEnabled(
self.get_option('occurrence_highlighting'))
occurrence_spin.slabel.setEnabled(
self.get_option('occurrence_highlighting'))
wrap_mode_box = newcb(_("Wrap lines"), 'wrap')
scroll_past_end_box = newcb(_("Scroll past the end"),
'scroll_past_end')
display_layout = QGridLayout()
display_layout.addWidget(linenumbers_box, 0, 0)
display_layout.addWidget(blanks_box, 1, 0)
display_layout.addWidget(edgeline_box, 2, 0)
display_layout.addWidget(edgeline_edit, 2, 1)
display_layout.addWidget(edgeline_edit_label, 2, 2)
display_layout.addWidget(currentline_box, 3, 0)
display_layout.addWidget(currentcell_box, 4, 0)
display_layout.addWidget(occurrence_box, 5, 0)
display_layout.addWidget(occurrence_spin.spinbox, 5, 1)
display_layout.addWidget(occurrence_spin.slabel, 5, 2)
display_layout.addWidget(wrap_mode_box, 6, 0)
display_layout.addWidget(scroll_past_end_box, 7, 0)
display_h_layout = QHBoxLayout()
display_h_layout.addLayout(display_layout)
display_h_layout.addStretch(1)
display_group.setLayout(display_h_layout)
run_group = QGroupBox(_("Run"))
saveall_box = newcb(_("Save all files before running script"),
'save_all_before_run')
run_selection_group = QGroupBox(_("Run selection"))
focus_box = newcb(_("Maintain focus in the Editor after running cells "
"or selections"), 'focus_to_editor')
run_cell_box = newcb(_("Copy full cell contents to the console when "
"running code cells"), 'run_cell_copy')
introspection_group = QGroupBox(_("Introspection"))
rope_is_installed = programs.is_module_installed('rope')
if rope_is_installed:
completion_box = newcb(_("Automatic code completion"),
'codecompletion/auto')
case_comp_box = newcb(_("Case sensitive code completion"),
'codecompletion/case_sensitive')
comp_enter_box = newcb(_("Enter key selects completion"),
'codecompletion/enter_key')
calltips_box = newcb(_("Display balloon tips"), 'calltips')
gotodef_box = newcb(
_("Link to object definition"),
'go_to_definition',
tip=_("If this option is enabled, clicking on an object\n"
"name (left-click + Ctrl key) will go to this object\n"
"definition (if resolved)."))
else:
rope_label = QLabel(_("<b>Warning:</b><br>"
"The Python module <i>rope</i> is not "
"installed on this computer: calltips, "
"code completion and go-to-definition "
"features won't be available."))
rope_label.setWordWrap(True)
sourcecode_group = QGroupBox(_("Source code"))
closepar_box = newcb(_("Automatic insertion of parentheses, braces "
"and brackets"),
'close_parentheses')
close_quotes_box = newcb(_("Automatic insertion of closing quotes"),
'close_quotes')
add_colons_box = newcb(_("Automatic insertion of colons after 'for', "
"'if', 'def', etc"),
'add_colons')
autounindent_box = newcb(_("Automatic indentation after 'else', "
"'elif', etc."), 'auto_unindent')
indent_chars_box = self.create_combobox(_("Indentation characters: "),
((_("2 spaces"), '* *'),
(_("3 spaces"), '* *'),
(_("4 spaces"), '* *'),
(_("5 spaces"), '* *'),
(_("6 spaces"), '* *'),
(_("7 spaces"), '* *'),
(_("8 spaces"), '* *'),
(_("Tabulations"), '*\t*')),
'indent_chars')
tabwidth_spin = self.create_spinbox(_("Tab stop width:"), _("spaces"),
'tab_stop_width_spaces',
4, 1, 8, 1)
def enable_tabwidth_spin(index):
if index == 7: # Tabulations
tabwidth_spin.plabel.setEnabled(True)
tabwidth_spin.spinbox.setEnabled(True)
else:
tabwidth_spin.plabel.setEnabled(False)
tabwidth_spin.spinbox.setEnabled(False)
indent_chars_box.combobox.currentIndexChanged.connect(
enable_tabwidth_spin)
tab_mode_box = newcb(
_("Tab always indent"),
'tab_always_indent', default=False,
tip=_("If enabled, pressing Tab will always indent,\n"
"even when the cursor is not at the beginning\n"
"of a line (when this option is enabled, code\n"
"completion may be triggered using the alternate\n"
"shortcut: Ctrl+Space)"))
ibackspace_box = newcb(_("Intelligent backspace"),
'intelligent_backspace', default=True)
removetrail_box = newcb(_("Automatically remove trailing spaces "
"when saving files"),
'always_remove_trailing_spaces', default=False)
analysis_group = QGroupBox(_("Analysis"))
pep_url = '<a href="https://www.python.org/dev/peps/pep-0008">PEP8</a>'
pep8_label = QLabel(_("<i>(Refer to the {} page)</i>").format(pep_url))
pep8_label.setOpenExternalLinks(True)
is_pyflakes = codeanalysis.is_pyflakes_installed()
is_pep8 = codeanalysis.get_checker_executable(
'pycodestyle') is not None
pyflakes_box = newcb(
_("Real-time code analysis"),
'code_analysis/pyflakes', default=True,
tip=_("<p>If enabled, Python source code will be analyzed "
"using pyflakes, and lines containing errors or "
"warnings will be highlighted.</p>"
"<p><u>Note</u>: Add <b>analysis:ignore</b> in a "
"comment to ignore code analysis warnings.</p>"))
pyflakes_box.setEnabled(is_pyflakes)
if not is_pyflakes:
pyflakes_box.setToolTip(_("Code analysis requires pyflakes %s+") %
codeanalysis.PYFLAKES_REQVER)
pep8_box = newcb(
_("Real-time code style analysis"),
'code_analysis/pep8', default=False,
tip=_("<p>If enabled, Python source code will be analyzed "
"using pycodestyle, and lines that are not following "
"the PEP 8 style guide will be highlighted.</p>"
"<p><u>Note</u>: Add <b>analysis:ignore</b> in a "
"comment to ignore style analysis warnings.</p>"))
pep8_box.setEnabled(is_pep8)
todolist_box = newcb(_("Code annotations (TODO, FIXME, XXX, HINT, TIP,"
" @todo, HACK, BUG, OPTIMIZE, !!!, ???)"),
'todo_list', default=True)
realtime_radio = self.create_radiobutton(
_("Perform analysis when "
"saving file and every"),
'realtime_analysis', True)
saveonly_radio = self.create_radiobutton(
_("Perform analysis only "
"when saving file"),
'onsave_analysis')
af_spin = self.create_spinbox("", _(" ms"),
'realtime_analysis/timeout',
min_=100, max_=1000000, step=100)
af_layout = QHBoxLayout()
af_layout.addWidget(realtime_radio)
af_layout.addWidget(af_spin)
run_layout = QVBoxLayout()
run_layout.addWidget(saveall_box)
run_group.setLayout(run_layout)
run_selection_layout = QVBoxLayout()
run_selection_layout.addWidget(focus_box)
run_selection_layout.addWidget(run_cell_box)
run_selection_group.setLayout(run_selection_layout)
introspection_layout = QVBoxLayout()
if rope_is_installed:
introspection_layout.addWidget(calltips_box)
introspection_layout.addWidget(completion_box)
introspection_layout.addWidget(case_comp_box)
introspection_layout.addWidget(comp_enter_box)
introspection_layout.addWidget(gotodef_box)
else:
introspection_layout.addWidget(rope_label)
introspection_group.setLayout(introspection_layout)
analysis_layout = QVBoxLayout()
analysis_layout.addWidget(pyflakes_box)
analysis_pep_layout = QHBoxLayout()
analysis_pep_layout.addWidget(pep8_box)
analysis_pep_layout.addWidget(pep8_label)
analysis_layout.addLayout(analysis_pep_layout)
analysis_layout.addWidget(todolist_box)
analysis_layout.addLayout(af_layout)
analysis_layout.addWidget(saveonly_radio)
analysis_group.setLayout(analysis_layout)
sourcecode_layout = QVBoxLayout()
sourcecode_layout.addWidget(closepar_box)
sourcecode_layout.addWidget(autounindent_box)
sourcecode_layout.addWidget(add_colons_box)
sourcecode_layout.addWidget(close_quotes_box)
indent_tab_layout = QHBoxLayout()
indent_tab_grid_layout = QGridLayout()
indent_tab_grid_layout.addWidget(indent_chars_box.label, 0, 0)
indent_tab_grid_layout.addWidget(indent_chars_box.combobox, 0, 1)
indent_tab_grid_layout.addWidget(tabwidth_spin.plabel, 1, 0)
indent_tab_grid_layout.addWidget(tabwidth_spin.spinbox, 1, 1)
indent_tab_grid_layout.addWidget(tabwidth_spin.slabel, 1, 2)
indent_tab_layout.addLayout(indent_tab_grid_layout)
indent_tab_layout.addStretch(1)
sourcecode_layout.addLayout(indent_tab_layout)
sourcecode_layout.addWidget(tab_mode_box)
sourcecode_layout.addWidget(ibackspace_box)
sourcecode_layout.addWidget(removetrail_box)
sourcecode_group.setLayout(sourcecode_layout)
eol_group = QGroupBox(_("End-of-line characters"))
eol_label = QLabel(_("When opening a text file containing "
"mixed end-of-line characters (this may "
"raise syntax errors in the consoles "
"on Windows platforms), Spyder may fix the "
"file automatically."))
eol_label.setWordWrap(True)
check_eol_box = newcb(_("Fix automatically and show warning "
"message box"),
'check_eol_chars', default=True)
convert_eol_on_save_box = newcb(_("On Save: convert EOL characters"
" to"),
'convert_eol_on_save', default=False)
eol_combo_choices = ((_("LF (UNIX)"), 'LF'),
(_("CRLF (Windows)"), 'CRLF'),
(_("CR (Mac)"), 'CR'),
)
convert_eol_on_save_combo = self.create_combobox("",
eol_combo_choices,
('convert_eol_on_'
'save_to'),
)
convert_eol_on_save_box.toggled.connect(
convert_eol_on_save_combo.setEnabled)
convert_eol_on_save_combo.setEnabled(
self.get_option('convert_eol_on_save'))
eol_on_save_layout = QHBoxLayout()
eol_on_save_layout.addWidget(convert_eol_on_save_box)
eol_on_save_layout.addWidget(convert_eol_on_save_combo)
eol_layout = QVBoxLayout()
eol_layout.addWidget(eol_label)
eol_layout.addWidget(check_eol_box)
eol_layout.addLayout(eol_on_save_layout)
eol_group.setLayout(eol_layout)
tabs = QTabWidget()
tabs.addTab(self.create_tab(interface_group, display_group),
_("Display"))
tabs.addTab(self.create_tab(introspection_group, analysis_group),
_("Code Introspection/Analysis"))
tabs.addTab(self.create_tab(template_btn, run_group,
run_selection_group,
sourcecode_group, eol_group),
_("Advanced settings"))
vlayout = QVBoxLayout()
vlayout.addWidget(tabs)
self.setLayout(vlayout)
class Editor(SpyderPluginWidget):
"""
Multi-file Editor widget
"""
CONF_SECTION = 'editor'
CONFIGWIDGET_CLASS = EditorConfigPage
TEMPFILE_PATH = get_conf_path('temp.py')
TEMPLATE_PATH = get_conf_path('template.py')
DISABLE_ACTIONS_WHEN_HIDDEN = False # SpyderPluginWidget class attribute
# Signals
run_in_current_ipyclient = Signal(str, str, str, bool, bool, bool, bool)
run_cell_in_ipyclient = Signal(str, str, str, bool)
exec_in_extconsole = Signal(str, bool)
redirect_stdio = Signal(bool)
open_dir = Signal(str)
breakpoints_saved = Signal()
run_in_current_extconsole = Signal(str, str, str, bool, bool)
open_file_update = Signal(str)
sig_lsp_notification = Signal(dict, str)
def __init__(self, parent, ignore_last_opened_files=False):
SpyderPluginWidget.__init__(self, parent)
self.__set_eol_chars = True
# Creating template if it doesn't already exist
if not osp.isfile(self.TEMPLATE_PATH):
if os.name == "nt":
shebang = []
else:
shebang = ['#!/usr/bin/env python' + ('2' if PY2 else '3')]
header = shebang + [
'# -*- coding: utf-8 -*-',
'"""', 'Created on %(date)s', '',
'@author: %(username)s', '"""', '', '']
try:
encoding.write(os.linesep.join(header), self.TEMPLATE_PATH,
'utf-8')
except EnvironmentError:
pass
self.projects = None
self.outlineexplorer = None
self.help = None
self.file_dependent_actions = []
self.pythonfile_dependent_actions = []
self.dock_toolbar_actions = None
self.edit_menu_actions = None #XXX: find another way to notify Spyder
self.stack_menu_actions = None
self.checkable_actions = {}
self.__first_open_files_setup = True
self.editorstacks = []
self.last_focus_editorstack = {}
self.editorwindows = []
self.editorwindows_to_be_created = []
self.toolbar_list = None
self.menu_list = None
# Initialize plugin
self.initialize_plugin()
self.options_button.hide()
# Configuration dialog size
self.dialog_size = None
statusbar = self.main.statusBar()
self.readwrite_status = ReadWriteStatus(self, statusbar)
self.eol_status = EOLStatus(self, statusbar)
self.encoding_status = EncodingStatus(self, statusbar)
self.cursorpos_status = CursorPositionStatus(self, statusbar)
layout = QVBoxLayout()
self.dock_toolbar = QToolBar(self)
add_actions(self.dock_toolbar, self.dock_toolbar_actions)
layout.addWidget(self.dock_toolbar)
self.last_edit_cursor_pos = None
self.cursor_pos_history = []
self.cursor_pos_index = None
self.__ignore_cursor_position = True
# LSP setup
self.sig_lsp_notification.connect(self.document_server_settings)
self.lsp_editor_settings = {}
# Setup new windows:
self.main.all_actions_defined.connect(self.setup_other_windows)
# Change module completions when PYTHONPATH changes
self.main.sig_pythonpath_changed.connect(self.set_path)
# Find widget
self.find_widget = FindReplace(self, enable_replace=True)
self.find_widget.hide()
self.find_widget.visibility_changed.connect(
lambda vs: self.rehighlight_cells())
self.register_widget_shortcuts(self.find_widget)
# Tabbed editor widget + Find/Replace widget
editor_widgets = QWidget(self)
editor_layout = QVBoxLayout()
editor_layout.setContentsMargins(0, 0, 0, 0)
editor_widgets.setLayout(editor_layout)
self.editorsplitter = EditorSplitter(self, self,
self.stack_menu_actions, first=True)
editor_layout.addWidget(self.editorsplitter)
editor_layout.addWidget(self.find_widget)
# Splitter: editor widgets (see above) + outline explorer
self.splitter = QSplitter(self)
self.splitter.setContentsMargins(0, 0, 0, 0)
self.splitter.addWidget(editor_widgets)
self.splitter.setStretchFactor(0, 5)
self.splitter.setStretchFactor(1, 1)
layout.addWidget(self.splitter)
self.setLayout(layout)
self.setFocusPolicy(Qt.ClickFocus)
# Editor's splitter state
state = self.get_option('splitter_state', None)
if state is not None:
self.splitter.restoreState( QByteArray().fromHex(
str(state).encode('utf-8')) )
self.recent_files = self.get_option('recent_files', [])
self.untitled_num = 0
# Parameters of last file execution:
self.__last_ic_exec = None # internal console
self.__last_ec_exec = None # external console
# File types and filters used by the Open dialog
self.edit_filetypes = None
self.edit_filters = None
self.__ignore_cursor_position = False
current_editor = self.get_current_editor()
if current_editor is not None:
filename = self.get_current_filename()
position = current_editor.get_position('cursor')
self.add_cursor_position_to_history(filename, position)
self.update_cursorpos_actions()
self.set_path()
def set_projects(self, projects):
self.projects = projects
@Slot()
def show_hide_projects(self):
if self.projects is not None:
dw = self.projects.dockwidget
if dw.isVisible():
dw.hide()
else:
dw.show()
dw.raise_()
self.switch_to_plugin()
def set_outlineexplorer(self, outlineexplorer):
self.outlineexplorer = outlineexplorer
for editorstack in self.editorstacks:
# Pass the OutlineExplorer widget to the stacks because they
# don't need the plugin
editorstack.set_outlineexplorer(self.outlineexplorer.explorer)
self.editorstacks[0].initialize_outlineexplorer()
self.outlineexplorer.explorer.edit_goto.connect(
lambda filenames, goto, word:
self.load(filenames=filenames, goto=goto, word=word,
editorwindow=self))
self.outlineexplorer.explorer.edit.connect(
lambda filenames:
self.load(filenames=filenames, editorwindow=self))
def set_help(self, help_plugin):
self.help = help_plugin
for editorstack in self.editorstacks:
editorstack.set_help(self.help)
#------ Private API --------------------------------------------------------
def restore_scrollbar_position(self):
"""Restoring scrollbar position after main window is visible"""
# Widget is now visible, we may center cursor on top level editor:
try:
self.get_current_editor().centerCursor()
except AttributeError:
pass
@Slot(dict)
def report_open_file(self, options):
"""Request to start a LSP server to attend a language."""
filename = options['filename']
logger.debug('Call LSP for %s' % filename)
language = options['language']
callback = options['codeeditor']
stat = self.main.lspmanager.start_lsp_client(language.lower())
self.main.lspmanager.register_file(
language.lower(), filename, callback)
if stat:
if language.lower() in self.lsp_editor_settings:
self.lsp_server_ready(
language.lower(), self.lsp_editor_settings[
language.lower()])
else:
editor = self.get_current_editor()
editor.lsp_ready = False
@Slot(dict, str)
def document_server_settings(self, settings, language):
"""Update LSP server settings for textDocument requests."""
self.lsp_editor_settings[language] = settings
logger.debug('LSP Language Settings: %r' % self.lsp_editor_settings)
self.lsp_server_ready(language, self.lsp_editor_settings[language])
def lsp_server_ready(self, language, configuration):
"""Notify all stackeditors about LSP server availability."""
for editorstack in self.editorstacks:
editorstack.notify_server_ready(language, configuration)
def send_lsp_request(self, language, request, params):
logger.debug("LSP request: %r" %request)
self.main.lspmanager.send_request(language, request, params)
#------ SpyderPluginWidget API ---------------------------------------------
def get_plugin_title(self):
"""Return widget title"""
title = _('Editor')
if self.dockwidget:
filename = self.get_current_filename()
if self.dockwidget.dock_tabbar:
if filename and self.dockwidget.dock_tabbar.count() < 2:
title += ' - ' + to_text_string(filename)
else:
title += ' - ' + to_text_string(filename)
return title
def get_plugin_icon(self):
"""Return widget icon."""
return ima.icon('edit')
def get_focus_widget(self):
"""
Return the widget to give focus to.
This happens when plugin's dockwidget is raised on top-level.
"""
return self.get_current_editor()
def visibility_changed(self, enable):
"""DockWidget visibility has changed"""
SpyderPluginWidget.visibility_changed(self, enable)
if self.dockwidget is None:
return
if self.dockwidget.isWindow():
self.dock_toolbar.show()
else:
self.dock_toolbar.hide()
if enable:
self.refresh_plugin()
self.sig_update_plugin_title.emit()
def refresh_plugin(self):
"""Refresh editor plugin"""
editorstack = self.get_current_editorstack()
editorstack.refresh()
self.refresh_save_all_action()
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
state = self.splitter.saveState()
self.set_option('splitter_state', qbytearray_to_str(state))
filenames = []
editorstack = self.editorstacks[0]
active_project_path = None
if self.projects is not None:
active_project_path = self.projects.get_active_project_path()
if not active_project_path:
self.set_open_filenames()
else:
self.projects.set_project_filenames(
[finfo.filename for finfo in editorstack.data])
self.set_option('layout_settings',
self.editorsplitter.get_layout_settings())
self.set_option('windows_layout_settings',
[win.get_layout_settings() for win in self.editorwindows])
# self.set_option('filenames', filenames)
self.set_option('recent_files', self.recent_files)
try:
if not editorstack.save_if_changed(cancelable) and cancelable:
return False
else:
for win in self.editorwindows[:]:
win.close()
return True
except IndexError:
return True
def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
# ---- File menu and toolbar ----
self.new_action = create_action(
self,
_("&New file..."),
icon=ima.icon('filenew'), tip=_("New file"),
triggered=self.new,
context=Qt.WidgetShortcut
)
self.register_shortcut(self.new_action, context="Editor",
name="New file", add_sc_to_tip=True)
self.open_last_closed_action = create_action(
self,
_("O&pen last closed"),
tip=_("Open last closed"),
triggered=self.open_last_closed
)
self.register_shortcut(self.open_last_closed_action, context="Editor",
name="Open last closed")
self.open_action = create_action(self, _("&Open..."),
icon=ima.icon('fileopen'), tip=_("Open file"),
triggered=self.load,
context=Qt.WidgetShortcut)
self.register_shortcut(self.open_action, context="Editor",
name="Open file", add_sc_to_tip=True)
self.revert_action = create_action(self, _("&Revert"),
icon=ima.icon('revert'), tip=_("Revert file from disk"),
triggered=self.revert)
self.save_action = create_action(self, _("&Save"),
icon=ima.icon('filesave'), tip=_("Save file"),
triggered=self.save,
context=Qt.WidgetShortcut)
self.register_shortcut(self.save_action, context="Editor",
name="Save file", add_sc_to_tip=True)
self.save_all_action = create_action(self, _("Sav&e all"),
icon=ima.icon('save_all'), tip=_("Save all files"),
triggered=self.save_all,
context=Qt.WidgetShortcut)
self.register_shortcut(self.save_all_action, context="Editor",
name="Save all", add_sc_to_tip=True)
save_as_action = create_action(self, _("Save &as..."), None,
ima.icon('filesaveas'), tip=_("Save current file as..."),
triggered=self.save_as,
context=Qt.WidgetShortcut)
self.register_shortcut(save_as_action, "Editor", "Save As")
save_copy_as_action = create_action(self, _("Save copy as..."), None,
ima.icon('filesaveas'), _("Save copy of current file as..."),
triggered=self.save_copy_as)
print_preview_action = create_action(self, _("Print preview..."),
tip=_("Print preview..."), triggered=self.print_preview)
self.print_action = create_action(self, _("&Print..."),
icon=ima.icon('print'), tip=_("Print current file..."),
triggered=self.print_file)
# Shortcut for close_action is defined in widgets/editor.py
self.close_action = create_action(self, _("&Close"),
icon=ima.icon('fileclose'), tip=_("Close current file"),
triggered=self.close_file)
self.close_all_action = create_action(self, _("C&lose all"),
icon=ima.icon('filecloseall'), tip=_("Close all opened files"),
triggered=self.close_all_files,
context=Qt.WidgetShortcut)
self.register_shortcut(self.close_all_action, context="Editor",
name="Close all")
# ---- Find menu and toolbar ----
_text = _("&Find text")
find_action = create_action(self, _text, icon=ima.icon('find'),
tip=_text, triggered=self.find,
context=Qt.WidgetShortcut)
self.register_shortcut(find_action, context="_",
name="Find text", add_sc_to_tip=True)
find_next_action = create_action(self, _("Find &next"),
icon=ima.icon('findnext'),
triggered=self.find_next,
context=Qt.WidgetShortcut)
self.register_shortcut(find_next_action, context="_",
name="Find next")
find_previous_action = create_action(self, _("Find &previous"),
icon=ima.icon('findprevious'),
triggered=self.find_previous,
context=Qt.WidgetShortcut)
self.register_shortcut(find_previous_action, context="_",
name="Find previous")
_text = _("&Replace text")
replace_action = create_action(self, _text, icon=ima.icon('replace'),
tip=_text, triggered=self.replace,
context=Qt.WidgetShortcut)
self.register_shortcut(replace_action, context="_",
name="Replace text")
# ---- Debug menu and toolbar ----
set_clear_breakpoint_action = create_action(self,
_("Set/Clear breakpoint"),
icon=ima.icon('breakpoint_big'),
triggered=self.set_or_clear_breakpoint,
context=Qt.WidgetShortcut)
self.register_shortcut(set_clear_breakpoint_action, context="Editor",
name="Breakpoint")
set_cond_breakpoint_action = create_action(self,
_("Set/Edit conditional breakpoint"),
icon=ima.icon('breakpoint_cond_big'),
triggered=self.set_or_edit_conditional_breakpoint,
context=Qt.WidgetShortcut)
self.register_shortcut(set_cond_breakpoint_action, context="Editor",
name="Conditional breakpoint")
clear_all_breakpoints_action = create_action(self,
_('Clear breakpoints in all files'),
triggered=self.clear_all_breakpoints)
self.winpdb_action = create_action(self, _("Debug with winpdb"),
triggered=self.run_winpdb)
self.winpdb_action.setEnabled(WINPDB_PATH is not None and PY2)
# --- Debug toolbar ---
debug_action = create_action(self, _("&Debug"),
icon=ima.icon('debug'),
tip=_("Debug file"),
triggered=self.debug_file)
self.register_shortcut(debug_action, context="_", name="Debug",
add_sc_to_tip=True)
debug_next_action = create_action(self, _("Step"),
icon=ima.icon('arrow-step-over'), tip=_("Run current line"),
triggered=lambda: self.debug_command("next"))
self.register_shortcut(debug_next_action, "_", "Debug Step Over",
add_sc_to_tip=True)
debug_continue_action = create_action(self, _("Continue"),
icon=ima.icon('arrow-continue'),
tip=_("Continue execution until next breakpoint"),
triggered=lambda: self.debug_command("continue"))
self.register_shortcut(debug_continue_action, "_", "Debug Continue",
add_sc_to_tip=True)
debug_step_action = create_action(self, _("Step Into"),
icon=ima.icon('arrow-step-in'),
tip=_("Step into function or method of current line"),
triggered=lambda: self.debug_command("step"))
self.register_shortcut(debug_step_action, "_", "Debug Step Into",
add_sc_to_tip=True)
debug_return_action = create_action(self, _("Step Return"),
icon=ima.icon('arrow-step-out'),
tip=_("Run until current function or method returns"),
triggered=lambda: self.debug_command("return"))
self.register_shortcut(debug_return_action, "_", "Debug Step Return",
add_sc_to_tip=True)
debug_exit_action = create_action(self, _("Stop"),
icon=ima.icon('stop_debug'), tip=_("Stop debugging"),
triggered=lambda: self.debug_command("exit"))
self.register_shortcut(debug_exit_action, "_", "Debug Exit",
add_sc_to_tip=True)
# --- Run toolbar ---
run_action = create_action(self, _("&Run"), icon=ima.icon('run'),
tip=_("Run file"),
triggered=self.run_file)
self.register_shortcut(run_action, context="_", name="Run",
add_sc_to_tip=True)
configure_action = create_action(self, _("&Configuration per file..."),
icon=ima.icon('run_settings'),
tip=_("Run settings"),
menurole=QAction.NoRole,
triggered=self.edit_run_configurations)
self.register_shortcut(configure_action, context="_",
name="Configure", add_sc_to_tip=True)
re_run_action = create_action(self, _("Re-run &last script"),
icon=ima.icon('run_again'),
tip=_("Run again last file"),
triggered=self.re_run_file)
self.register_shortcut(re_run_action, context="_",
name="Re-run last script",
add_sc_to_tip=True)
run_selected_action = create_action(self, _("Run &selection or "
"current line"),
icon=ima.icon('run_selection'),
tip=_("Run selection or "
"current line"),
triggered=self.run_selection,
context=Qt.WidgetShortcut)
self.register_shortcut(run_selected_action, context="Editor",
name="Run selection", add_sc_to_tip=True)
run_cell_action = create_action(self,
_("Run cell"),
icon=ima.icon('run_cell'),
shortcut=QKeySequence(RUN_CELL_SHORTCUT),
tip=_("Run current cell (Ctrl+Enter)\n"
"[Use #%% to create cells]"),
triggered=self.run_cell,
context=Qt.WidgetShortcut)
run_cell_advance_action = create_action(self,
_("Run cell and advance"),
icon=ima.icon('run_cell_advance'),
shortcut=QKeySequence(RUN_CELL_AND_ADVANCE_SHORTCUT),
tip=_("Run current cell and go to the next one "
"(Shift+Enter)"),
triggered=self.run_cell_and_advance,
context=Qt.WidgetShortcut)
re_run_last_cell_action = create_action(self,
_("Re-run last cell"),
tip=_("Re run last cell "),
triggered=self.re_run_last_cell,
context=Qt.WidgetShortcut)
self.register_shortcut(re_run_last_cell_action,
context="Editor",
name='re-run last cell',
add_sc_to_tip=True)
# --- Source code Toolbar ---
self.todo_list_action = create_action(self,
_("Show todo list"), icon=ima.icon('todo_list'),
tip=_("Show comments list (TODO/FIXME/XXX/HINT/TIP/@todo/"
"HACK/BUG/OPTIMIZE/!!!/???)"),
triggered=self.go_to_next_todo)
self.todo_menu = QMenu(self)
self.todo_list_action.setMenu(self.todo_menu)
self.todo_menu.aboutToShow.connect(self.update_todo_menu)
self.warning_list_action = create_action(self,
_("Show warning/error list"), icon=ima.icon('wng_list'),
tip=_("Show code analysis warnings/errors"),
triggered=self.go_to_next_warning)
self.warning_menu = QMenu(self)
self.warning_list_action.setMenu(self.warning_menu)
self.warning_menu.aboutToShow.connect(self.update_warning_menu)
self.previous_warning_action = create_action(self,
_("Previous warning/error"), icon=ima.icon('prev_wng'),
tip=_("Go to previous code analysis warning/error"),
triggered=self.go_to_previous_warning,
context=Qt.WidgetShortcut)
self.register_shortcut(self.previous_warning_action,
context="Editor",
name="Previous warning",
add_sc_to_tip=True)
self.next_warning_action = create_action(self,
_("Next warning/error"), icon=ima.icon('next_wng'),
tip=_("Go to next code analysis warning/error"),
triggered=self.go_to_next_warning,
context=Qt.WidgetShortcut)
self.register_shortcut(self.next_warning_action,
context="Editor",
name="Next warning",
add_sc_to_tip=True)
self.previous_edit_cursor_action = create_action(self,
_("Last edit location"), icon=ima.icon('last_edit_location'),
tip=_("Go to last edit location"),
triggered=self.go_to_last_edit_location,
context=Qt.WidgetShortcut)
self.register_shortcut(self.previous_edit_cursor_action,
context="Editor",
name="Last edit location",
add_sc_to_tip=True)
self.previous_cursor_action = create_action(self,
_("Previous cursor position"), icon=ima.icon('prev_cursor'),
tip=_("Go to previous cursor position"),
triggered=self.go_to_previous_cursor_position,