def _get_credentials_from_settings(self): """Get the stored credentials if any.""" remember_token = CONF.get('main', 'report_error/remember_token') return remember_token
Signal, Slot) from qtpy.QtGui import QStandardItem, QStandardItemModel from qtpy.QtWidgets import (QApplication, QDialog, QLineEdit, QListWidgetItem, QVBoxLayout, QListView) # Local imports from spyder.config.base import _ from spyder.config.manager import CONF from spyder.config.utils import is_ubuntu from spyder.py3compat import TEXT_TYPES, to_text_string from spyder.utils import icon_manager as ima from spyder.utils.stringmatching import get_search_scores from spyder.widgets.helperwidgets import HTMLDelegate # Style dict constants FONT_SIZE = CONF.get('appearance', 'rich_font/size', 10) ITEM_STYLES = { 'title_color': ima.MAIN_FG_COLOR, 'description_color': 'rgb(153, 153, 153)', 'section_color': 'rgb(70, 179, 239)', 'shortcut_color': 'rgb(153, 153, 153)', 'title_font_size': FONT_SIZE, 'description_font_size': FONT_SIZE, 'section_font_size': FONT_SIZE, 'shortcut_font_size': FONT_SIZE, } ITEM_SEPARATOR_STYLES = { 'color': ima.MAIN_FG_COLOR, 'font_size': FONT_SIZE, }
def toggle_show_comments(self, state): if CONF.get('outline_explorer', 'show_comments') != state: CONF.set('outline_explorer', 'show_comments', state) self.show_comments = state self.sig_update_configuration.emit() self.update_all_editors(reset_info=True)
def _load_all_breakpoints(self): 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 setup_completion(self): size = CONF.get('main', 'completion/size') font = get_font() self.completion_widget.setup_appearance(size, font)
def _get_option(self, option, default=NoDefault, section=None): """Get option from spyder.ini.""" section = self.CONF_SECTION if section is None else section return CONF.get(section, option, default)
def main(): #========================================================================== # Proper high DPI scaling is available in Qt >= 5.6.0. This attribute must # be set before creating the application. #========================================================================== if CONF.get('main', 'high_dpi_custom_scale_factor'): factors = str(CONF.get('main', 'high_dpi_custom_scale_factors')) f = list(filter(None, factors.split(';'))) if len(f) == 1: os.environ['QT_SCALE_FACTOR'] = f[0] else: os.environ['QT_SCREEN_SCALE_FACTORS'] = factors else: os.environ['QT_SCALE_FACTOR'] = '' os.environ['QT_SCREEN_SCALE_FACTORS'] = '' # Splash screen # ------------------------------------------------------------------------- # Start Qt Splash to inform the user of the current status app = qapplication() restarter = Restarter() if PYQT5: APP_ICON = QIcon(get_image_path("spyder.svg")) else: APP_ICON = QIcon(get_image_path("spyder.png")) app.setWindowIcon(APP_ICON) restarter.set_splash_message(_('Closing Spyder')) # Get variables # Note: Variables defined in app/mainwindow.py 'restart()' method spyder_args = os.environ.pop('SPYDER_ARGS', None) pid = os.environ.pop('SPYDER_PID', None) is_bootstrap = os.environ.pop('SPYDER_IS_BOOTSTRAP', None) reset = os.environ.pop('SPYDER_RESET', None) # Get the spyder base folder based on this file this_folder = osp.split(osp.dirname(osp.abspath(__file__)))[0] spyder_folder = osp.split(this_folder)[0] if not any([spyder_args, pid, is_bootstrap, reset]): error = "This script can only be called from within a Spyder instance" raise RuntimeError(error) # Variables were stored as string literals in the environment, so to use # them we need to parse them in a safe manner. is_bootstrap = ast.literal_eval(is_bootstrap) pid = ast.literal_eval(pid) args = ast.literal_eval(spyder_args) reset = ast.literal_eval(reset) # Enforce the --new-instance flag when running spyder if '--new-instance' not in args: if is_bootstrap and '--' not in args: args = args + ['--', '--new-instance'] else: args.append('--new-instance') # Create the arguments needed for resetting if '--' in args: args_reset = ['--', '--reset'] else: args_reset = ['--reset'] # Arrange arguments to be passed to the restarter and reset subprocess args = ' '.join(args) args_reset = ' '.join(args_reset) # Get python executable running this script python = sys.executable # Build the command if is_bootstrap: spyder = osp.join(spyder_folder, 'bootstrap.py') else: spyderdir = osp.join(spyder_folder, 'spyder') spyder = osp.join(spyderdir, 'app', 'start.py') command = '"{0}" "{1}" {2}'.format(python, spyder, args) # Adjust the command and/or arguments to subprocess depending on the OS shell = not IS_WINDOWS # Before launching a new Spyder instance we need to make sure that the # previous one has closed. We wait for a fixed and "reasonable" amount of # time and check, otherwise an error is launched wait_time = 90 if IS_WINDOWS else 30 # Seconds for counter in range(int(wait_time / SLEEP_TIME)): if not is_pid_running(pid): break time.sleep(SLEEP_TIME) # Throttling control QApplication.processEvents() # Needed to refresh the splash else: # The old spyder instance took too long to close and restart aborts restarter.launch_error_message(error_type=CLOSE_ERROR) env = os.environ.copy() # Reset Spyder (if required) # ------------------------------------------------------------------------- if reset: restarter.set_splash_message(_('Resetting Spyder to defaults')) command_reset = '"{0}" "{1}" {2}'.format(python, spyder, args_reset) try: p = subprocess.Popen(command_reset, shell=shell, env=env) except Exception as error: restarter.launch_error_message(error_type=RESET_ERROR, error=error) else: p.communicate() pid_reset = p.pid # Before launching a new Spyder instance we need to make sure that the # reset subprocess has closed. We wait for a fixed and "reasonable" # amount of time and check, otherwise an error is launched. wait_time = 20 # Seconds for counter in range(int(wait_time / SLEEP_TIME)): if not is_pid_running(pid_reset): break time.sleep(SLEEP_TIME) # Throttling control QApplication.processEvents() # Needed to refresh the splash else: # The reset subprocess took too long and it is killed try: p.kill() except OSError as error: restarter.launch_error_message(error_type=RESET_ERROR, error=error) else: restarter.launch_error_message(error_type=RESET_ERROR) # Restart # ------------------------------------------------------------------------- restarter.set_splash_message(_('Restarting')) try: subprocess.Popen(command, shell=shell, env=env) except Exception as error: restarter.launch_error_message(error_type=RESTART_ERROR, error=error)
def load(self): if self.language is not None: state = CONF.get('lsp-server', self.language.lower()) self.__dict__.update(state)
def _get_option(self, option, default=NoDefault): """Get option from spyder.ini.""" return CONF.get(self.CONF_SECTION, option, default)
def set_pdb_execute_events(self): """Set pdb_execute_events into a debugging session""" self.call_kernel(interrupt=True).set_pdb_execute_events( CONF.get('run', 'pdb_execute_events', True))
def __init__(self, parent, language=None, cmd='', host='127.0.0.1', port=2084, args='', external=False, stdio=False, configurations={}, **kwargs): super(LSPServerEditor, self).__init__(parent) description = _( "To create a new server configuration, you need to select a " "programming language, set the command to start its associated " "server and enter any arguments that should be passed to it on " "startup. Additionally, you can set the server's hostname and " "port if connecting to an external server, " "or to a local one using TCP instead of stdio pipes." "<br><br>" "<i>Note</i>: You can use the placeholders <tt>{host}</tt> and " "<tt>{port}</tt> in the server arguments field to automatically " "fill in the respective values.<br>" ) self.parent = parent self.external = external # Widgets self.server_settings_description = QLabel(description) self.lang_cb = QComboBox(self) self.external_cb = QCheckBox(_('External server'), self) self.host_label = QLabel(_('Host:')) self.host_input = QLineEdit(self) self.port_label = QLabel(_('Port:')) self.port_spinner = QSpinBox(self) self.cmd_label = QLabel(_('Command:')) self.cmd_input = QLineEdit(self) self.args_label = QLabel(_('Arguments:')) self.args_input = QLineEdit(self) self.json_label = QLabel(self.JSON_VALID, self) self.conf_label = QLabel(_('<b>Server Configuration:</b>')) self.conf_input = SimpleCodeEditor(None) self.bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = self.bbox.button(QDialogButtonBox.Ok) self.button_cancel = self.bbox.button(QDialogButtonBox.Cancel) # Widget setup self.setMinimumSize(self.MIN_SIZE) self.setWindowTitle(_('LSP server editor')) self.server_settings_description.setWordWrap(True) self.lang_cb.setToolTip( _('Programming language provided by the LSP server')) self.lang_cb.addItem(_('Select a language')) self.lang_cb.addItems(LSP_LANGUAGES) self.button_ok.setEnabled(False) if language is not None: idx = LSP_LANGUAGES.index(language) self.lang_cb.setCurrentIndex(idx + 1) self.button_ok.setEnabled(True) self.host_input.setPlaceholderText('127.0.0.1') self.host_input.setText(host) self.host_input.textChanged.connect(lambda _: self.validate()) self.port_spinner.setToolTip(_('TCP port number of the server')) self.port_spinner.setMinimum(1) self.port_spinner.setMaximum(60000) self.port_spinner.setValue(port) self.port_spinner.valueChanged.connect(lambda _: self.validate()) self.cmd_input.setText(cmd) self.cmd_input.setPlaceholderText('/absolute/path/to/command') self.args_input.setToolTip( _('Additional arguments required to start the server')) self.args_input.setText(args) self.args_input.setPlaceholderText(r'--host {host} --port {port}') self.conf_input.setup_editor( language='json', color_scheme=CONF.get('appearance', 'selected'), wrap=False, highlight_current_line=True, font=get_font() ) self.conf_input.set_language('json') self.conf_input.setToolTip(_('Additional LSP server configuration ' 'set at runtime. JSON required')) try: conf_text = json.dumps(configurations, indent=4, sort_keys=True) except Exception: conf_text = '{}' self.conf_input.set_text(conf_text) self.external_cb.setToolTip( _('Check if the server runs on a remote location')) self.external_cb.setChecked(external) self.stdio_cb = QCheckBox(_('Use stdio pipes for communication'), self) self.stdio_cb.setToolTip(_('Check if the server communicates ' 'using stdin/out pipes')) self.stdio_cb.setChecked(stdio) # Layout setup hlayout = QHBoxLayout() general_vlayout = QVBoxLayout() general_vlayout.addWidget(self.server_settings_description) vlayout = QVBoxLayout() lang_group = QGroupBox(_('Language')) lang_layout = QVBoxLayout() lang_layout.addWidget(self.lang_cb) lang_group.setLayout(lang_layout) vlayout.addWidget(lang_group) server_group = QGroupBox(_('Language server')) server_layout = QGridLayout() server_layout.addWidget(self.cmd_label, 0, 0) server_layout.addWidget(self.cmd_input, 0, 1) server_layout.addWidget(self.args_label, 1, 0) server_layout.addWidget(self.args_input, 1, 1) server_group.setLayout(server_layout) vlayout.addWidget(server_group) address_group = QGroupBox(_('Server address')) host_layout = QVBoxLayout() host_layout.addWidget(self.host_label) host_layout.addWidget(self.host_input) port_layout = QVBoxLayout() port_layout.addWidget(self.port_label) port_layout.addWidget(self.port_spinner) conn_info_layout = QHBoxLayout() conn_info_layout.addLayout(host_layout) conn_info_layout.addLayout(port_layout) address_group.setLayout(conn_info_layout) vlayout.addWidget(address_group) advanced_group = QGroupBox(_('Advanced')) advanced_layout = QVBoxLayout() advanced_layout.addWidget(self.external_cb) advanced_layout.addWidget(self.stdio_cb) advanced_group.setLayout(advanced_layout) vlayout.addWidget(advanced_group) conf_layout = QVBoxLayout() conf_layout.addWidget(self.conf_label) conf_layout.addWidget(self.conf_input) conf_layout.addWidget(self.json_label) vlayout.addStretch() hlayout.addLayout(vlayout, 2) hlayout.addLayout(conf_layout, 3) general_vlayout.addLayout(hlayout) general_vlayout.addWidget(self.bbox) self.setLayout(general_vlayout) self.form_status(False) # Signals if not external: self.cmd_input.textChanged.connect(lambda x: self.validate()) self.external_cb.stateChanged.connect(self.set_local_options) self.stdio_cb.stateChanged.connect(self.set_stdio_options) self.lang_cb.currentIndexChanged.connect(self.lang_selection_changed) self.conf_input.textChanged.connect(self.validate) self.bbox.accepted.connect(self.accept) self.bbox.rejected.connect(self.reject) # Final setup if language is not None: self.form_status(True) self.validate() if stdio: self.set_stdio_options(True) if external: self.set_local_options(True)
def set_pdb_ignore_lib(self): """Set pdb_ignore_lib into a debugging session""" self.call_kernel(interrupt=True).set_pdb_ignore_lib( CONF.get('run', 'pdb_ignore_lib', False))
def set_spyder_breakpoints(self): """Set Spyder breakpoints into a debugging session""" self.call_kernel(interrupt=True).set_breakpoints( CONF.get('run', 'breakpoints', {}))
def update_configuration(self): enable_code_snippets = CONF.get('lsp-server', 'code_snippets') self.client.enable_code_snippets = enable_code_snippets
def _reset_namespace(self): warning = CONF.get('ipython_console', 'show_reset_namespace_warning') self.reset_namespace(warning=warning)
def get_option(self, option, default=NoDefault): return CONF.get(self.CONF_SECTION, option, default)
def _get_color_scheme(self): """Get the current color scheme.""" return get_color_scheme(CONF.get('appearance', 'selected'))
def _set_run_configurations(configurations): history_count = CONF.get('run', 'history', 20) CONF.set('run', 'configurations', configurations[:history_count])
def toggle_variables(self, state): if CONF.get('outline_explorer', 'display_variables') != state: CONF.set('outline_explorer', 'display_variables', state) self.display_variables = state for editor in self.editor_ids.keys(): self.update_editor(editor.info, editor)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.dir = None self.runconf = RunConfiguration() firstrun_o = CONF.get('run', ALWAYS_OPEN_FIRST_RUN_OPTION, False) # --- Interpreter --- interpreter_group = QGroupBox(_("Console")) interpreter_layout = QVBoxLayout() interpreter_group.setLayout(interpreter_layout) self.current_radio = QRadioButton(CURRENT_INTERPRETER) interpreter_layout.addWidget(self.current_radio) self.dedicated_radio = QRadioButton(DEDICATED_INTERPRETER) interpreter_layout.addWidget(self.dedicated_radio) self.systerm_radio = QRadioButton(SYSTERM_INTERPRETER) interpreter_layout.addWidget(self.systerm_radio) # --- General settings ---- common_group = QGroupBox(_("General settings")) common_layout = QGridLayout() common_group.setLayout(common_layout) self.clear_var_cb = QCheckBox(CLEAR_ALL_VARIABLES) common_layout.addWidget(self.clear_var_cb, 0, 0) self.console_ns_cb = QCheckBox(CONSOLE_NAMESPACE) common_layout.addWidget(self.console_ns_cb, 1, 0) self.post_mortem_cb = QCheckBox(POST_MORTEM) common_layout.addWidget(self.post_mortem_cb, 2, 0) self.clo_cb = QCheckBox(_("Command line options:")) common_layout.addWidget(self.clo_cb, 3, 0) self.clo_edit = QLineEdit() self.clo_cb.toggled.connect(self.clo_edit.setEnabled) self.clo_edit.setEnabled(False) common_layout.addWidget(self.clo_edit, 3, 1) # --- Working directory --- wdir_group = QGroupBox(_("Working directory settings")) wdir_layout = QVBoxLayout() wdir_group.setLayout(wdir_layout) self.file_dir_radio = QRadioButton(FILE_DIR) wdir_layout.addWidget(self.file_dir_radio) self.cwd_radio = QRadioButton(CW_DIR) wdir_layout.addWidget(self.cwd_radio) fixed_dir_layout = QHBoxLayout() self.fixed_dir_radio = QRadioButton(FIXED_DIR) fixed_dir_layout.addWidget(self.fixed_dir_radio) self.wd_edit = QLineEdit() self.fixed_dir_radio.toggled.connect(self.wd_edit.setEnabled) self.wd_edit.setEnabled(False) fixed_dir_layout.addWidget(self.wd_edit) browse_btn = QPushButton(ima.icon('DirOpenIcon'), '', self) browse_btn.setToolTip(_("Select directory")) browse_btn.clicked.connect(self.select_directory) fixed_dir_layout.addWidget(browse_btn) wdir_layout.addLayout(fixed_dir_layout) # --- System terminal --- external_group = QGroupBox(_("External system terminal")) external_group.setDisabled(True) self.systerm_radio.toggled.connect(external_group.setEnabled) external_layout = QGridLayout() external_group.setLayout(external_layout) self.interact_cb = QCheckBox(INTERACT) external_layout.addWidget(self.interact_cb, 1, 0, 1, -1) self.pclo_cb = QCheckBox(_("Command line options:")) external_layout.addWidget(self.pclo_cb, 3, 0) self.pclo_edit = QLineEdit() self.pclo_cb.toggled.connect(self.pclo_edit.setEnabled) self.pclo_edit.setEnabled(False) self.pclo_edit.setToolTip( _("<b>-u</b> is added to the " "other options you set here")) external_layout.addWidget(self.pclo_edit, 3, 1) # Checkbox to preserve the old behavior, i.e. always open the dialog # on first run hline = QFrame() hline.setFrameShape(QFrame.HLine) hline.setFrameShadow(QFrame.Sunken) self.firstrun_cb = QCheckBox(ALWAYS_OPEN_FIRST_RUN % _("this dialog")) self.firstrun_cb.clicked.connect(self.set_firstrun_o) self.firstrun_cb.setChecked(firstrun_o) layout = QVBoxLayout() layout.addWidget(interpreter_group) layout.addWidget(common_group) layout.addWidget(wdir_group) layout.addWidget(external_group) layout.addWidget(hline) layout.addWidget(self.firstrun_cb) self.setLayout(layout)
def get_spyder_breakpoints(self): """Get spyder breakpoints.""" return CONF.get('run', 'breakpoints', {})
def main(): """ Start Spyder application. If single instance mode is turned on (default behavior) and an instance of Spyder is already running, this will just parse and send command line options to the application. """ # Parse command line options options, args = (CLI_OPTIONS, CLI_ARGS) # This is to allow reset without reading our conf file if options.reset_config_files: # <!> Remove all configuration files! reset_config_files() return from spyder.config.manager import CONF # Store variable to be used in self.restart (restart spyder instance) os.environ['SPYDER_ARGS'] = str(sys.argv[1:]) #========================================================================== # Proper high DPI scaling is available in Qt >= 5.6.0. This attibute must # be set before creating the application. #========================================================================== if CONF.get('main', 'high_dpi_custom_scale_factor'): factors = str(CONF.get('main', 'high_dpi_custom_scale_factors')) f = list(filter(None, factors.split(';'))) if len(f) == 1: os.environ['QT_SCALE_FACTOR'] = f[0] else: os.environ['QT_SCREEN_SCALE_FACTORS'] = factors else: os.environ['QT_SCALE_FACTOR'] = '' os.environ['QT_SCREEN_SCALE_FACTORS'] = '' if sys.platform == 'darwin': # Prevent Spyder from crashing in macOS if locale is not defined LANG = os.environ.get('LANG') LC_ALL = os.environ.get('LC_ALL') if bool(LANG) and not bool(LC_ALL): LC_ALL = LANG elif not bool(LANG) and bool(LC_ALL): LANG = LC_ALL else: LANG = LC_ALL = 'en_US.UTF-8' os.environ['LANG'] = LANG os.environ['LC_ALL'] = LC_ALL # Don't show useless warning in the terminal where Spyder # was started. # See spyder-ide/spyder#3730. os.environ['EVENT_NOKQUEUE'] = '1' else: # Prevent our kernels to crash when Python fails to identify # the system locale. # Fixes spyder-ide/spyder#7051. try: from locale import getlocale getlocale() except ValueError: # This can fail on Windows. See spyder-ide/spyder#6886. try: os.environ['LANG'] = 'C' os.environ['LC_ALL'] = 'C' except Exception: pass if options.debug_info: levels = {'minimal': '2', 'verbose': '3'} os.environ['SPYDER_DEBUG'] = levels[options.debug_info] if options.paths: from spyder.config.base import get_conf_paths sys.stdout.write('\nconfig:' + '\n') for path in reversed(get_conf_paths()): sys.stdout.write('\t' + path + '\n') sys.stdout.write('\n' ) return if (CONF.get('main', 'single_instance') and not options.new_instance and not options.reset_config_files and not running_in_mac_app()): # Minimal delay (0.1-0.2 secs) to avoid that several # instances started at the same time step in their # own foots while trying to create the lock file time.sleep(random.randrange(1000, 2000, 90)/10000.) # Lock file creation lock_file = get_conf_path('spyder.lock') lock = lockfile.FilesystemLock(lock_file) # Try to lock spyder.lock. If it's *possible* to do it, then # there is no previous instance running and we can start a # new one. If *not*, then there is an instance already # running, which is locking that file try: lock_created = lock.lock() except: # If locking fails because of errors in the lockfile # module, try to remove a possibly stale spyder.lock. # This is reported to solve all problems with lockfile. # See spyder-ide/spyder#2363. try: if os.name == 'nt': if osp.isdir(lock_file): import shutil shutil.rmtree(lock_file, ignore_errors=True) else: if osp.islink(lock_file): os.unlink(lock_file) except: pass # Then start Spyder as usual and *don't* continue # executing this script because it doesn't make # sense from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main(options, args) else: mainwindow.main(options, args) return if lock_created: # Start a new instance from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main(options, args) else: mainwindow.main(options, args) else: # Pass args to Spyder or print an informative # message if args: send_args_to_spyder(args) else: print("Spyder is already running. If you want to open a new \n" "instance, please pass to it the --new-instance option") else: from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main(options, args) else: mainwindow.main(options, args)
def reset_namespace(self): warning = CONF.get('ipython_console', 'show_reset_namespace_warning') self.shellwidget.reset_namespace(warning=warning, message=True) self.editor.automatic_column_width = True
def __init__(self, parent=None): super(BasePluginWidgetMixin, self).__init__() # Actions to add to the Options menu self._plugin_actions = None # Attribute to keep track if the plugin is undocked in a # separate window self._undocked_window = None self._ismaximized = False self._default_margins = None self._isvisible = False # Options buttons self.options_button = create_toolbutton(self, text=_('Options'), icon=ima.icon('tooloptions')) self.options_button.setPopupMode(QToolButton.InstantPopup) # Don't show menu arrow and remove padding if is_dark_interface(): self.options_button.setStyleSheet( ("QToolButton::menu-indicator{image: none;}\n" "QToolButton{padding: 3px;}")) else: self.options_button.setStyleSheet( "QToolButton::menu-indicator{image: none;}") # Options menu self._options_menu = QMenu(self) # NOTE: Don't use the default option of CONF.get to assign a # None shortcut to plugins that don't have one. That will mess # the creation of our Keyboard Shortcuts prefs page try: self.shortcut = CONF.get('shortcuts', '_/switch to %s' % self.CONF_SECTION) except configparser.NoOptionError: pass # We decided to create our own toggle action instead of using # the one that comes with dockwidget because it's not possible # to raise and focus the plugin with it. self._toggle_view_action = None # Default actions for Options menu self._dock_action = create_action(self, _("Dock"), icon=ima.icon('dock'), tip=_("Dock the pane"), triggered=self._close_window) self._undock_action = create_action(self, _("Undock"), icon=ima.icon('undock'), tip=_("Undock the pane"), triggered=self._create_window) self._close_plugin_action = create_action( self, _("Close"), icon=ima.icon('close_pane'), tip=_("Close the pane"), triggered=self._plugin_closed)
def update_configuration(self): self.client.enable_code_snippets = CONF.get('lsp-server', 'code_snippets') self.enabled = self.get_option('enable') self._show_onboarding = self.get_option('show_onboarding')
def get_option(self, option): """Get an option from our config system.""" return CONF.get(self.CONF_SECTION, option)
def get_option(self, option, default=NoDefault, section=None): section = self.CONF_SECTION if section is None else section return CONF.get(section, option, default)
"""Editor config page.""" from qtpy.QtCore import Qt from qtpy.QtWidgets import (QGridLayout, QGroupBox, QHBoxLayout, QLabel, QTabWidget, QVBoxLayout, QWidget) from spyder.api.preferences import PluginConfigPage from spyder.config.base import _ from spyder.config.manager import CONF import spyder.utils.icon_manager as ima NUMPYDOC = "https://numpydoc.readthedocs.io/en/latest/format.html" GOOGLEDOC = "https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html" DOCSTRING_SHORTCUT = CONF.get('shortcuts', 'editor/docstring') class EditorConfigPage(PluginConfigPage): def get_name(self): return _("Editor") def get_icon(self): return ima.icon('edit') def setup_page(self): newcb = self.create_checkbox # --- Display tab --- showtabbar_box = newcb(_("Show tab bar"), 'show_tab_bar') showclassfuncdropdown_box = newcb(
def toggle_group_cells(self, state): if CONF.get('outline_explorer', 'group_cells') != state: CONF.set('outline_explorer', 'group_cells', state) self.group_cells = state self.sig_update_configuration.emit() self.update_all_editors(reset_info=True)
def create_new_client(self, give_focus=True, filename='', is_cython=False, **kwargs): """Create a new client Copied and modified from spyder.plugins.ipythonconsole.IPythonConsole """ ipycon = self.main.ipyconsole ipycon.master_clients += 1 client_id = dict(int_id=to_text_string(ipycon.master_clients), str_id='A') cf = ipycon._new_connection_file() show_elapsed_time = ipycon.get_option('show_elapsed_time') reset_warning = ipycon.get_option('show_reset_namespace_warning') client_kwargs = { "ask_before_restart": ipycon.get_option('ask_before_restart'), "options_button": ipycon.options_button, "css_path": ipycon.css_path } if spyder.version_info > (4, 2, 0): client_kwargs["ask_before_closing"] = ipycon.get_option( 'ask_before_closing') if "given_name" in kwargs: client_kwargs["given_name"] = kwargs["given_name"] addops = {} if "is_pylab" in kwargs: addops["is_pylab"] = kwargs["is_pylab"] if "is_sympy" in kwargs: addops["is_sympy"] = kwargs["is_sympy"] client = MxClientWidget( ipycon, id_=client_id, history_filename=get_conf_path('history.py'), config_options=ipycon.config_options(), additional_options=ipycon.additional_options(**addops), interpreter_versions=ipycon.interpreter_versions(), connection_file=cf, menu_actions=self.menu_actions, show_elapsed_time=show_elapsed_time, reset_warning=reset_warning, **client_kwargs) # Change stderr_dir if requested testing = (ipycon.test_dir is not None) if testing: client.stderr_dir = ipycon.test_dir ipycon.add_tab(client, name=client.get_name(), filename=filename) if cf is None: error_msg = ipycon.permission_error_msg.format( jupyter_runtime_dir()) client.show_kernel_error(error_msg) return # Check if ipykernel is present in the external interpreter. # Else we won't be able to create a client if not CONF.get('main_interpreter', 'default'): pyexec = CONF.get('main_interpreter', 'executable') has_ipykernel = programs.is_module_installed( "spyder_kernels", interpreter=pyexec) # missing version param testcond = has_ipykernel if not testcond: client.show_kernel_error( _("Your Python environment or " "installation doesn't " "have the <tt>ipykernel</tt> and " "<tt>cloudpickle</tt> modules " "installed on it. Without these modules " "is not possible for Spyder to create a " "console for you.<br><br>" "You can install them by running " "in a system terminal:<br><br>" "<tt>pip install ipykernel cloudpickle</tt>" "<br><br>" "or<br><br>" "<tt>conda install ipykernel cloudpickle</tt>")) return self.connect_client_to_kernel(client, is_cython=is_cython) if client.shellwidget.kernel_manager is None: return ipycon.register_client(client)