/
plugin.py
3766 lines (3312 loc) · 151 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
from datetime import datetime
import logging
import os
import os.path as osp
from pathlib import Path
import re
import sys
import time
from typing import Dict, Optional
import uuid
# Third party imports
from qtpy.compat import from_qvariant, getopenfilenames, to_qvariant
from qtpy.QtCore import QByteArray, Qt, Signal, Slot, QDir
from qtpy.QtGui import QTextCursor
from qtpy.QtPrintSupport import QAbstractPrintDialog, QPrintDialog, QPrinter
from qtpy.QtWidgets import (QAction, QActionGroup, QApplication, QDialog,
QFileDialog, QInputDialog, QMenu, QSplitter,
QToolBar, QVBoxLayout, QWidget)
# Local imports
from spyder.api.config.decorators import on_conf_change
from spyder.api.config.mixins import SpyderConfigurationObserver
from spyder.api.plugins import Plugins, SpyderPluginWidget
from spyder.api.widgets.menus import SpyderMenu
from spyder.config.base import _, get_conf_path, running_under_pytest
from spyder.config.utils import (get_edit_filetypes, get_edit_filters,
get_filter)
from spyder.plugins.editor.api.panel import Panel
from spyder.py3compat import qbytearray_to_str, to_text_string
from spyder.utils import encoding, programs, sourcecode
from spyder.utils.icon_manager import 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.api.run import (
EditorRunConfiguration, FileRun, SelectionRun, CellRun,
SelectionContextModificator, ExtraAction)
from spyder.plugins.editor.confpage import EditorConfigPage
from spyder.plugins.editor.utils.autosave import AutosaveForPlugin
from spyder.plugins.editor.utils.switcher_manager import EditorSwitcherManager
from spyder.plugins.editor.widgets.codeeditor import CodeEditor
from spyder.plugins.editor.widgets.editorstack import EditorStack
from spyder.plugins.editor.widgets.splitter import EditorSplitter
from spyder.plugins.editor.widgets.window import EditorMainWindow
from spyder.plugins.editor.utils.bookmarks import (load_bookmarks,
update_bookmarks)
from spyder.plugins.editor.widgets.status import (CursorPositionStatus,
EncodingStatus, EOLStatus,
ReadWriteStatus, VCSStatus)
from spyder.plugins.mainmenu.api import (
ApplicationMenus, EditMenuSections, SearchMenuSections, SourceMenuSections
)
from spyder.plugins.run.api import (
RunContext, RunConfigurationMetadata, RunConfiguration,
SupportedExtensionContexts, ExtendedContext)
from spyder.plugins.toolbar.api import ApplicationToolbars
from spyder.utils.stylesheet import AppStyle
from spyder.widgets.mixins import BaseEditMixin
from spyder.widgets.printer import SpyderPrinter, SpyderPrintPreviewDialog
from spyder.widgets.simplecodeeditor import SimpleCodeEditor
logger = logging.getLogger(__name__)
class Editor(SpyderPluginWidget, SpyderConfigurationObserver):
"""
Multi-file Editor widget
"""
CONF_SECTION = 'editor'
CONFIGWIDGET_CLASS = EditorConfigPage
CONF_FILE = False
TEMPFILE_PATH = get_conf_path('temp.py')
TEMPLATE_PATH = get_conf_path('template.py')
DISABLE_ACTIONS_WHEN_HIDDEN = False # SpyderPluginWidget class attribute
# This is required for the new API
NAME = 'editor'
REQUIRES = [Plugins.Console]
OPTIONAL = [Plugins.Completions, Plugins.OutlineExplorer]
# Signals
redirect_stdio = Signal(bool)
sig_dir_opened = Signal(str)
"""
This signal is emitted when the editor changes the current directory.
Parameters
----------
new_working_directory: str
The new working directory path.
Notes
-----
This option is available on the options menu of the editor plugin
"""
sig_file_opened_closed_or_updated = Signal(str, str)
"""
This signal is emitted when a file is opened, closed or updated,
including switching among files.
Parameters
----------
filename: str
Name of the file that was opened, closed or updated.
language: str
Name of the programming language of the file that was opened,
closed or updated.
"""
# This signal is fired for any focus change among all editor stacks
sig_editor_focus_changed = Signal()
# This signal is used to communicate with the run plugin
sig_editor_focus_changed_uuid = Signal(str)
sig_help_requested = Signal(dict)
"""
This signal is emitted to request help on a given object `name`.
Parameters
----------
help_data: dict
Dictionary required by the Help pane to render a docstring.
Examples
--------
>>> help_data = {
'obj_text': str,
'name': str,
'argspec': str,
'note': str,
'docstring': str,
'force_refresh': bool,
'path': str,
}
See Also
--------
:py:meth:spyder.plugins.editor.widgets.editorstack.EditorStack.send_to_help
"""
sig_open_files_finished = Signal()
"""
This signal is emitted when the editor finished to open files.
"""
sig_codeeditor_created = Signal(object)
"""
This signal is emitted when a codeeditor is created.
Parameters
----------
codeeditor: spyder.plugins.editor.widgets.codeeditor.CodeEditor
The codeeditor.
"""
sig_codeeditor_deleted = Signal(object)
"""
This signal is emitted when a codeeditor is closed.
Parameters
----------
codeeditor: spyder.plugins.editor.widgets.codeeditor.CodeEditor
The codeeditor.
"""
sig_codeeditor_changed = Signal(object)
"""
This signal is emitted when the current codeeditor changes.
Parameters
----------
codeeditor: spyder.plugins.editor.widgets.codeeditor.CodeEditor
The codeeditor.
"""
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 python3']
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.pending_run_files = set({})
self.run_configurations_per_origin = {}
self.supported_run_configurations = {}
self.file_per_id = {}
self.id_per_file = {}
self.metadata_per_id: Dict[str, RunConfigurationMetadata] = {}
self.projects = None
self.outlineexplorer = None
self.file_dependent_actions = []
self.pythonfile_dependent_actions = []
self.dock_toolbar_actions = None
self.stack_menu_actions = None
self.checkable_actions = {}
self.__first_open_files_setup = True
self.editorstacks = []
self.last_focused_editorstack = {}
self.editorwindows = []
self.editorwindows_to_be_created = []
self.toolbar_list = None
self.menu_list = None
# We need to call this here to create self.dock_toolbar_actions,
# which is used below.
self._setup()
self.options_button.hide()
# Configuration dialog size
self.dialog_size = None
self.vcs_status = VCSStatus(self)
self.cursorpos_status = CursorPositionStatus(self)
self.encoding_status = EncodingStatus(self)
self.eol_status = EOLStatus(self)
self.readwrite_status = ReadWriteStatus(self)
# TODO: temporal fix while editor uses new API
statusbar = self.main.get_plugin(Plugins.StatusBar, error=False)
if statusbar:
statusbar.add_status_widget(self.readwrite_status)
statusbar.add_status_widget(self.eol_status)
statusbar.add_status_widget(self.encoding_status)
statusbar.add_status_widget(self.cursorpos_status)
statusbar.add_status_widget(self.vcs_status)
self.supported_run_extensions = [
{
'input_extension': ['py', 'ipy'],
'contexts': [
{'context': {'name': 'File'}, 'is_super': True},
{'context': {'name': 'Selection'}, 'is_super': False},
{'context': {'name': 'Cell'}, 'is_super': False}
]
},
]
run = self.main.get_plugin(Plugins.Run, error=False)
if run:
self.sig_editor_focus_changed_uuid.connect(
run.switch_focused_run_configuration)
run.register_run_configuration_provider(
self.NAME, self.supported_run_extensions)
run.create_run_button(
RunContext.Cell,
_("Run cell"),
icon=ima.icon('run_cell'),
tip=_("Run current cell\n[Use #%% to create cells]"),
shortcut_context=self.NAME,
register_shortcut=True,
add_to_toolbar=True,
add_to_menu=True
)
run.create_run_button(
RunContext.Cell,
_("Run cell and advance"),
icon=ima.icon('run_cell_advance'),
tip=_("Run current cell and go to the next one"),
shortcut_context=self.NAME,
register_shortcut=True,
add_to_toolbar=True,
add_to_menu=True,
extra_action_name=ExtraAction.Advance
)
run.create_run_button(
RunContext.Cell,
_("Re-run last cell"),
tip=_("Re run last cell "),
shortcut_context=self.NAME,
register_shortcut=True,
add_to_menu=True,
re_run=True
)
run.create_run_button(
RunContext.Selection,
_("Run &selection or current line"),
icon=ima.icon('run_selection'),
tip=_("Run selection or current line"),
shortcut_context=self.NAME,
register_shortcut=True,
add_to_toolbar=True,
add_to_menu=True,
extra_action_name=ExtraAction.Advance,
)
run.create_run_button(
RunContext.Selection,
_("Run &to line"),
tip=_("Run selection up to the current line"),
shortcut_context=self.NAME,
register_shortcut=True,
add_to_toolbar=False,
add_to_menu=True,
context_modificator=SelectionContextModificator.ToLine
)
run.create_run_button(
RunContext.Selection,
_("Run &from line"),
tip=_("Run selection from the current line"),
shortcut_context=self.NAME,
register_shortcut=True,
add_to_toolbar=False,
add_to_menu=True,
context_modificator=SelectionContextModificator.FromLine
)
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_undo_history = []
self.cursor_redo_history = []
self.__ignore_cursor_history = True
# Completions setup
self.completion_capabilities = {}
# Setup new windows:
self.main.sig_setup_finished.connect(self.setup_other_windows)
# Find widget
self.find_widget = FindReplace(self, enable_replace=True)
self.find_widget.hide()
self.register_widget_shortcuts(self.find_widget)
# TODO: This is a hack! Remove it after migrating to the new API
self.find_widget.layout().setContentsMargins(
2 * AppStyle.MarginSize,
AppStyle.MarginSize,
2 * AppStyle.MarginSize,
AppStyle.MarginSize
)
# Start autosave component
# (needs to be done before EditorSplitter)
self.autosave = AutosaveForPlugin(self)
self.autosave.try_recover_from_autosave()
# Multiply by 1000 to convert seconds to milliseconds
self.autosave.interval = self.get_option('autosave_interval') * 1000
self.autosave.enabled = self.get_option('autosave_enabled')
# SimpleCodeEditor instance used to print file contents
self._print_editor = self._create_print_editor()
self._print_editor.hide()
# Tabbed editor widget + Find/Replace widget
editor_widgets = QWidget(self)
editor_layout = QVBoxLayout()
editor_layout.setSpacing(0)
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)
editor_layout.addWidget(self._print_editor)
# 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_history = False
current_editor = self.get_current_editor()
if current_editor is not None:
filename = self.get_current_filename()
cursor = current_editor.textCursor()
self.add_cursor_to_history(filename, cursor)
self.update_cursorpos_actions()
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.get_widget())
self.outlineexplorer.get_widget().edit_goto.connect(
lambda filenames, goto, word:
self.load(filenames=filenames, goto=goto, word=word,
editorwindow=self))
self.outlineexplorer.get_widget().edit.connect(
lambda filenames:
self.load(filenames=filenames, editorwindow=self))
#------ 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
def update_run_focus_file(self):
"""
Inform other plugins that the current editor with focus has changed.
"""
filename = self.get_current_filename()
file_id = self.id_per_file.get(filename, None)
self.sig_editor_focus_changed_uuid.emit(file_id)
def register_file_run_metadata(self, filename):
"""Register opened files with the Run plugin."""
all_uuids = self.get_conf('file_uuids', default={})
file_id = all_uuids.get(filename, str(uuid.uuid4()))
all_uuids[filename] = file_id
self.set_conf('file_uuids', all_uuids)
metadata: RunConfigurationMetadata = {
'name': filename,
'source': self.NAME,
'path': filename,
'datetime': datetime.now(),
'uuid': file_id,
'context': {
'name': 'File'
},
'input_extension': osp.splitext(filename)[1][1:]
}
self.file_per_id[file_id] = filename
self.id_per_file[filename] = file_id
self.metadata_per_id[file_id] = metadata
run = self.main.get_plugin(Plugins.Run, error=False)
if run:
run.register_run_configuration_metadata(self, metadata)
def deregister_file_run_metadata(self, filename):
"""Unregister files with the Run plugin."""
if filename not in self.id_per_file:
return
file_id = self.id_per_file.pop(filename)
self.file_per_id.pop(file_id)
self.metadata_per_id.pop(file_id)
run = self.main.get_plugin(Plugins.Run, error=False)
if run is not None:
run.deregister_run_configuration_metadata(file_id)
def change_register_file_run_metadata(self, old_filename, new_filename):
"""Change registered run metadata when renaming files."""
is_selected = False
run = self.main.get_plugin(Plugins.Run, error=False)
if run is not None:
is_selected = (
run.get_currently_selected_configuration()
== self.id_per_file.get(old_filename, None)
)
self.deregister_file_run_metadata(old_filename)
# This avoids to register the run metadata of new_filename twice, which
# can happen for some rename operations.
if not self.id_per_file.get(new_filename):
self.register_file_run_metadata(new_filename)
if is_selected:
run.switch_focused_run_configuration(
self.id_per_file[new_filename])
@Slot(dict)
def report_open_file(self, options):
"""Report that a file was opened to other plugins."""
filename = options['filename']
language = options['language']
codeeditor = options['codeeditor']
__, filename_ext = osp.splitext(filename)
filename_ext = filename_ext[1:]
able_to_run_file = False
if filename_ext in self.supported_run_configurations:
ext_contexts = self.supported_run_configurations[filename_ext]
if (
filename not in self.id_per_file
and RunContext.File in ext_contexts
):
self.register_file_run_metadata(filename)
able_to_run_file = True
if not able_to_run_file:
self.pending_run_files |= {(filename, filename_ext)}
status = None
if self.main.get_plugin(Plugins.Completions, error=False):
status = (
self.main.completions.start_completion_services_for_language(
language.lower()))
self.main.completions.register_file(
language.lower(), filename, codeeditor)
if status:
if language.lower() in self.completion_capabilities:
# When this condition is True, it means there's a server
# that can provide completion services for this file.
codeeditor.register_completion_capabilities(
self.completion_capabilities[language.lower()])
codeeditor.start_completion_services()
elif self.main.completions.is_fallback_only(language.lower()):
# This is required to use fallback completions for files
# without a language server.
codeeditor.start_completion_services()
else:
if codeeditor.language == language.lower():
logger.debug('Setting {0} completions off'.format(filename))
codeeditor.completions_available = False
@Slot(dict, str)
def register_completion_capabilities(self, capabilities, language):
"""
Register completion server capabilities in all editorstacks.
Parameters
----------
capabilities: dict
Capabilities supported by a language server.
language: str
Programming language for the language server (it has to be
in small caps).
"""
logger.debug(
'Completion server capabilities for {!s} are: {!r}'.format(
language, capabilities)
)
# This is required to start workspace before completion
# services when Spyder starts with an open project.
# TODO: Find a better solution for it in the future!!
projects = self.main.get_plugin(Plugins.Projects, error=False)
if projects:
projects.start_workspace_services()
self.completion_capabilities[language] = dict(capabilities)
for editorstack in self.editorstacks:
editorstack.register_completion_capabilities(
capabilities, language)
self.start_completion_services(language)
def start_completion_services(self, language):
"""Notify all editorstacks about LSP server availability."""
for editorstack in self.editorstacks:
editorstack.start_completion_services(language)
def stop_completion_services(self, language):
"""Notify all editorstacks about LSP server unavailability."""
for editorstack in self.editorstacks:
editorstack.stop_completion_services(language)
def send_completion_request(self, language, request, params):
logger.debug("Perform request {0} for: {1}".format(
request, params['file']))
try:
self.main.completions.send_request(language, request, params)
except AttributeError:
# Completions was closed
pass
@Slot(str, tuple, dict)
def _rpc_call(self, method, args, kwargs):
meth = getattr(self, method)
meth(*args, **kwargs)
#------ SpyderPluginWidget API ---------------------------------------------
@staticmethod
def get_plugin_title():
"""Return widget title"""
# TODO: This is a temporary measure to get the title of this plugin
# without creating an instance
title = _('Editor')
return title
# TODO: Remove when the editor is migrated to the new API
get_name = get_plugin_title
@staticmethod
def get_description():
return _(
"Edit Python, Markdown, Cython and many other types of text files."
)
@classmethod
def get_plugin_icon(cls):
"""Return widget icon."""
return ima.icon('edit')
# TODO: Remove when the editor is migrated to the new API
get_icon = get_plugin_icon
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))
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:
filenames = self.get_open_filenames()
self.set_option('filenames', 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)
# Stop autosave timer before closing windows
self.autosave.stop_autosave_timer()
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_shortcut_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_shortcut_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_shortcut_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_shortcut_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")
self.find_action = create_action(
self, _text,
icon=ima.icon('find'),
tip=_text,
triggered=self.find,
context=Qt.WidgetShortcut
)
self.register_shortcut(self.find_action, context="find_replace",
name="Find text", add_shortcut_to_tip=True)
self.find_next_action = create_action(
self, _("Find &next"),
icon=ima.icon('findnext'),
triggered=self.find_next,
context=Qt.WidgetShortcut
)
self.register_shortcut(self.find_next_action, context="find_replace",
name="Find next")
self.find_previous_action = create_action(
self, _("Find &previous"),
icon=ima.icon('findprevious'),
triggered=self.find_previous,
context=Qt.WidgetShortcut
)
self.register_shortcut(
self.find_previous_action,
context="find_replace",
name="Find previous"
)
_text = _("&Replace text")
self.replace_action = create_action(
self,
_text,
icon=ima.icon('replace'),
tip=_text,
triggered=self.replace,
context=Qt.WidgetShortcut
)
self.register_shortcut(self.replace_action, context="find_replace",
name="Replace text")
# --- Run toolbar ---
# --- 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_menu.setStyleSheet("QMenu {menu-scrollable: 1;}")
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_menu.setStyleSheet("QMenu {menu-scrollable: 1;}")
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_shortcut_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_shortcut_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_shortcut_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,
context=Qt.WidgetShortcut)
self.register_shortcut(self.previous_cursor_action,
context="Editor",
name="Previous cursor position",
add_shortcut_to_tip=True)
self.next_cursor_action = create_action(self,
_("Next cursor position"), icon=ima.icon('next_cursor'),
tip=_("Go to next cursor position"),
triggered=self.go_to_next_cursor_position,
context=Qt.WidgetShortcut)
self.register_shortcut(self.next_cursor_action,
context="Editor",
name="Next cursor position",
add_shortcut_to_tip=True)
# --- Edit Toolbar ---
create_new_cell = create_action(self, _("Create new cell at the "
"current line"),
icon=ima.icon('new_cell'),
tip=_("Create new cell"),
triggered=self.create_cell,
context=Qt.WidgetShortcut)
self.register_shortcut(create_new_cell, context="Editor",
name="create_new_cell")
self.toggle_comment_action = create_action(self,
_("Comment")+"/"+_("Uncomment"), icon=ima.icon('comment'),
tip=_("Comment current line or selection"),
triggered=self.toggle_comment, context=Qt.WidgetShortcut)
self.register_shortcut(self.toggle_comment_action, context="Editor",
name="Toggle comment")
blockcomment_action = create_action(self, _("Add &block comment"),
tip=_("Add block comment around "
"current line or selection"),
triggered=self.blockcomment, context=Qt.WidgetShortcut)
self.register_shortcut(blockcomment_action, context="Editor",
name="Blockcomment")
unblockcomment_action = create_action(self,
_("R&emove block comment"),
tip = _("Remove comment block around "
"current line or selection"),
triggered=self.unblockcomment, context=Qt.WidgetShortcut)
self.register_shortcut(unblockcomment_action, context="Editor",
name="Unblockcomment")
# ----------------------------------------------------------------------
# The following action shortcuts are hard-coded in CodeEditor
# keyPressEvent handler (the shortcut is here only to inform user):
# (context=Qt.WidgetShortcut -> disable shortcut for other widgets)
self.indent_action = create_action(self,
_("Indent"), "Tab", icon=ima.icon('indent'),
tip=_("Indent current line or selection"),
triggered=self.indent, context=Qt.WidgetShortcut)
self.unindent_action = create_action(self,
_("Unindent"), "Shift+Tab", icon=ima.icon('unindent'),
tip=_("Unindent current line or selection"),
triggered=self.unindent, context=Qt.WidgetShortcut)
self.text_uppercase_action = create_action(self,
_("Toggle Uppercase"), icon=ima.icon('toggle_uppercase'),
tip=_("Change to uppercase current line or selection"),
triggered=self.text_uppercase, context=Qt.WidgetShortcut)
self.register_shortcut(self.text_uppercase_action, context="Editor",
name="transform to uppercase")
self.text_lowercase_action = create_action(self,
_("Toggle Lowercase"), icon=ima.icon('toggle_lowercase'),
tip=_("Change to lowercase current line or selection"),
triggered=self.text_lowercase, context=Qt.WidgetShortcut)
self.register_shortcut(self.text_lowercase_action, context="Editor",
name="transform to lowercase")
# ----------------------------------------------------------------------
self.win_eol_action = create_action(
self,
_("CRLF (Windows)"),
toggled=lambda checked: self.toggle_eol_chars('nt', checked)
)
self.linux_eol_action = create_action(
self,
_("LF (Unix)"),
toggled=lambda checked: self.toggle_eol_chars('posix', checked)
)
self.mac_eol_action = create_action(
self,
_("CR (macOS)"),
toggled=lambda checked: self.toggle_eol_chars('mac', checked)
)
eol_action_group = QActionGroup(self)
eol_actions = (self.win_eol_action, self.linux_eol_action,
self.mac_eol_action)
add_actions(eol_action_group, eol_actions)
eol_menu = SpyderMenu(parent=self, title=_("Convert end-of-line characters"))
add_actions(eol_menu, eol_actions)