def setup_workingdirectory(qtbot, request, tmpdir): """Setup working directory plugin.""" CONF.reset_to_defaults() use_startup_wdir = request.node.get_closest_marker('use_startup_wdir') use_cli_wdir = request.node.get_closest_marker('use_cli_wdir') # Setting default options CONF.set('workingdir', 'startup/use_project_or_home_directory', True) CONF.set('workingdir', 'startup/use_fixed_directory', False) # Create main window and new directory main_window = MainWindow() if use_startup_wdir: new_wdir = tmpdir.mkdir(NEW_DIR + '_startup') CONF.set('workingdir', 'startup/use_project_or_home_directory', False) CONF.set('workingdir', 'startup/use_fixed_directory', True) CONF.set('workingdir', 'startup/fixed_directory', str(new_wdir)) elif use_cli_wdir: new_wdir = tmpdir.mkdir(NEW_DIR + '_cli') main_window._cli_options.working_directory = str(new_wdir) workingdirectory = WorkingDirectory(main_window, configuration=CONF) workingdirectory.on_initialize() workingdirectory.close = lambda: True return workingdirectory
def setup_completion(self): size = CONF.get('main', 'completion/size') font = get_font() self.completion_widget.setup_appearance(size, font)
def ipyconsole(qtbot, request): """IPython console fixture.""" class MainWindowMock(QMainWindow): def __getattr__(self, attr): if attr == 'consoles_menu_actions': return [] else: return Mock() # Tests assume inline backend CONF.set('ipython_console', 'pylab/backend', 0) # Start in a new working directory the console use_startup_wdir = request.node.get_closest_marker('use_startup_wdir') if use_startup_wdir: new_wdir = osp.join(os.getcwd(), NEW_DIR) if not osp.exists(new_wdir): os.mkdir(new_wdir) CONF.set('workingdir', 'console/use_fixed_directory', True) CONF.set('workingdir', 'console/fixed_directory', new_wdir) # Test the console with a non-ascii temp dir non_ascii_dir = request.node.get_closest_marker('non_ascii_dir') if non_ascii_dir: test_dir = NON_ASCII_DIR else: test_dir = None # Instruct the console to not use a stderr file no_stderr_file = request.node.get_closest_marker('no_stderr_file') if no_stderr_file: test_no_stderr = True else: test_no_stderr = False # Use the automatic backend if requested auto_backend = request.node.get_closest_marker('auto_backend') if auto_backend: CONF.set('ipython_console', 'pylab/backend', 1) # Start a Pylab client if requested pylab_client = request.node.get_closest_marker('pylab_client') is_pylab = True if pylab_client else False # Start a Sympy client if requested sympy_client = request.node.get_closest_marker('sympy_client') is_sympy = True if sympy_client else False # Start a Cython client if requested cython_client = request.node.get_closest_marker('cython_client') is_cython = True if cython_client else False # Create the console and a new client window = MainWindowMock() console = IPythonConsole(parent=window, testing=True, test_dir=test_dir, test_no_stderr=test_no_stderr) console.dockwidget = Mock() console._toggle_view_action = Mock() console.create_new_client(is_pylab=is_pylab, is_sympy=is_sympy, is_cython=is_cython) window.setCentralWidget(console) # Close callback def close_console(): console.closing_plugin() console.close() request.addfinalizer(close_console) qtbot.addWidget(window) window.show() return console
def _dismiss_forever(self): self.hide() self._enabled = False CONF.set('completions', 'kite_call_to_action', False)
def test_code_snippets(lsp_codeeditor, qtbot): assert rtree_available code_editor, lsp = lsp_codeeditor completion = code_editor.completion_widget snippets = code_editor.editor_extensions.get('SnippetsExtension') CONF.set('lsp-server', 'code_snippets', True) lsp.update_configuration() code_editor.toggle_automatic_completions(False) code_editor.toggle_code_snippets(True) # Set cursor to start code_editor.go_to_line(1) text = """ def test_func(xlonger, y1, some_z): pass """ text = textwrap.dedent(text) code_editor.insert_text(text) with qtbot.waitSignal(code_editor.lsp_response_signal, timeout=30000): code_editor.document_did_change() qtbot.keyPress(code_editor, Qt.Key_Enter, delay=300) qtbot.keyPress(code_editor, Qt.Key_Enter, delay=300) qtbot.keyClicks(code_editor, 'test_') with qtbot.waitSignal(completion.sig_show_completions, timeout=10000) as sig: qtbot.keyPress(code_editor, Qt.Key_Tab) assert 'test_func(xlonger, y1, some_z)' in { x['label'] for x in sig.args[0] } expected_insert = 'test_func(${1:xlonger}, ${2:y1}, ${3:some_z})$0' insert = sig.args[0][0] assert expected_insert == insert['insertText'] assert snippets.is_snippet_active assert code_editor.has_selected_text() # Rotate through snippet regions cursor = code_editor.textCursor() arg1 = cursor.selectedText() assert 'xlonger' == arg1 assert snippets.active_snippet == 1 qtbot.keyPress(code_editor, Qt.Key_Tab) cursor = code_editor.textCursor() arg2 = cursor.selectedText() assert 'y1' == arg2 assert snippets.active_snippet == 2 qtbot.keyPress(code_editor, Qt.Key_Tab) cursor = code_editor.textCursor() arg2 = cursor.selectedText() assert 'some_z' == arg2 assert snippets.active_snippet == 3 qtbot.keyPress(code_editor, Qt.Key_Tab) assert not snippets.is_snippet_active qtbot.keyPress(code_editor, Qt.Key_Enter, delay=300) qtbot.keyClicks(code_editor, 'test_') with qtbot.waitSignal(completion.sig_show_completions, timeout=10000) as sig: qtbot.keyPress(code_editor, Qt.Key_Tab) # Replace selection qtbot.keyClicks(code_editor, 'arg1') qtbot.wait(5000) # Snippets are disabled when there are no more left for _ in range(0, 3): qtbot.keyPress(code_editor, Qt.Key_Tab) assert not snippets.is_snippet_active cursor = code_editor.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cursor.movePosition(QTextCursor.EndOfBlock, mode=QTextCursor.KeepAnchor) text1 = cursor.selectedText() assert text1 == 'test_func(arg1, y1, some_z)' qtbot.keyPress(code_editor, Qt.Key_Enter, delay=300) qtbot.keyClicks(code_editor, 'test_') with qtbot.waitSignal(completion.sig_show_completions, timeout=10000) as sig: qtbot.keyPress(code_editor, Qt.Key_Tab) qtbot.keyPress(code_editor, Qt.Key_Tab) assert snippets.active_snippet == 2 # Extend text from right qtbot.keyPress(code_editor, Qt.Key_Right, delay=300) qtbot.keyClicks(code_editor, '_var') qtbot.keyPress(code_editor, Qt.Key_Up, delay=300) qtbot.keyPress(code_editor, Qt.Key_Down, delay=300) cursor = code_editor.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cursor.movePosition(QTextCursor.EndOfBlock, mode=QTextCursor.KeepAnchor) text1 = cursor.selectedText() assert text1 == 'test_func(xlonger, y1_var, some_z)' cursor.movePosition(QTextCursor.EndOfBlock) code_editor.setTextCursor(cursor) qtbot.keyPress(code_editor, Qt.Key_Enter, delay=300) qtbot.keyClicks(code_editor, 'test_') with qtbot.waitSignal(completion.sig_show_completions, timeout=10000) as sig: qtbot.keyPress(code_editor, Qt.Key_Tab) for _ in range(0, 2): qtbot.keyPress(code_editor, Qt.Key_Tab) assert snippets.active_snippet == 3 # Extend text from left qtbot.keyPress(code_editor, Qt.Key_Left, delay=300) qtbot.keyClicks(code_editor, 's') qtbot.keyPress(code_editor, Qt.Key_Tab) assert not snippets.is_snippet_active cursor = code_editor.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cursor.movePosition(QTextCursor.EndOfBlock, mode=QTextCursor.KeepAnchor) text1 = cursor.selectedText() assert text1 == 'test_func(xlonger, y1, ssome_z)' qtbot.keyPress(code_editor, Qt.Key_Enter, delay=300) qtbot.keyClicks(code_editor, 'test_') with qtbot.waitSignal(completion.sig_show_completions, timeout=10000) as sig: qtbot.keyPress(code_editor, Qt.Key_Tab) assert snippets.active_snippet == 1 # Delete snippet region qtbot.keyPress(code_editor, Qt.Key_Left, delay=300) qtbot.keyPress(code_editor, Qt.Key_Backspace, delay=300) assert len(snippets.snippets_map) == 3 qtbot.keyPress(code_editor, Qt.Key_Tab) cursor = code_editor.textCursor() arg1 = cursor.selectedText() assert 'some_z' == arg1 # Undo action with qtbot.waitSignal(code_editor.sig_undo, timeout=10000) as sig: code_editor.undo() assert len(snippets.snippets_map) == 4 for _ in range(0, 2): qtbot.keyPress(code_editor, Qt.Key_Tab) cursor = code_editor.textCursor() arg1 = cursor.selectedText() assert 'some_z' == arg1 with qtbot.waitSignal(code_editor.sig_redo, timeout=10000) as sig: code_editor.redo() assert len(snippets.snippets_map) == 3 for _ in range(0, 3): qtbot.keyPress(code_editor, Qt.Key_Tab) qtbot.keyPress(code_editor, Qt.Key_Right) qtbot.keyPress(code_editor, Qt.Key_Enter) qtbot.keyPress(code_editor, Qt.Key_Backspace) qtbot.keyClicks(code_editor, 'test_') with qtbot.waitSignal(completion.sig_show_completions, timeout=10000) as sig: qtbot.keyPress(code_editor, Qt.Key_Tab) # Delete text qtbot.keyPress(code_editor, Qt.Key_Left, delay=300) qtbot.keyPress(code_editor, Qt.Key_Right, delay=300) qtbot.keyPress(code_editor, Qt.Key_Backspace) for _ in range(0, 3): qtbot.keyPress(code_editor, Qt.Key_Tab) cursor = code_editor.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cursor.movePosition(QTextCursor.EndOfBlock, mode=QTextCursor.KeepAnchor) text1 = cursor.selectedText() assert text1 == 'test_func(longer, y1, some_z)' CONF.set('lsp-server', 'code_snippets', False) lsp.update_configuration() code_editor.toggle_automatic_completions(True) code_editor.toggle_code_snippets(True)
def _reset_namespace(self): warning = CONF.get('ipython_console', 'show_reset_namespace_warning') self.reset_namespace(warning=warning)
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 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'] = '' if sys.platform == 'darwin': # Fixes launching issues with Big Sur (spyder-ide/spyder#14222) os.environ['QT_MAC_WANTS_LAYER'] = '1' # 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 set_option(self, option, value, section=None, recursive_notification=False): section = self.CONF_SECTION if section is None else section CONF.set(section, option, value, recursive_notification=recursive_notification)
def _get_option(self, option, default=NoDefault): """Get option from spyder.ini.""" return CONF.get(self.CONF_SECTION, option, default)
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 _set_option(self, option, value): """Set option in spyder.ini""" CONF.set(self.CONF_SECTION, str(option), value)
def _get_color_scheme(self): """Get the current color scheme.""" return get_color_scheme(CONF.get('appearance', 'selected'))
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 set_option(self, option, value, section=None): section = self.CONF_SECTION if section is None else section CONF.set(section, option, value)
def remove_option(self, option, section=None): section = self.CONF_SECTION if section is None else section CONF.remove_option(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)
def load(self): self.key = CONF.get_shortcut(self.context, self.name)
def reset_namespace(self, warning=False, message=False): """Reset the namespace by removing all names defined by the user.""" reset_str = _("Remove all variables") warn_str = _("All user-defined variables will be removed. " "Are you sure you want to proceed?") # This is necessary to make resetting variables work in external # kernels. # See spyder-ide/spyder#9505. try: kernel_env = self.kernel_manager._kernel_spec.env except AttributeError: kernel_env = {} if warning: box = MessageCheckBox(icon=QMessageBox.Warning, parent=self) box.setWindowTitle(reset_str) box.set_checkbox_text(_("Don't show again.")) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.Yes) box.set_checked(False) box.set_check_visible(True) box.setText(warn_str) answer = box.exec_() # Update checkbox based on user interaction CONF.set('ipython_console', 'show_reset_namespace_warning', not box.is_checked()) self.ipyclient.reset_warning = not box.is_checked() if answer != QMessageBox.Yes: return try: if self.is_waiting_pdb_input(): self.dbg_exec_magic('reset', '-f') else: if message: self.reset() self._append_html(_("<br><br>Removing all variables..." "\n<hr>"), before_prompt=False) self.silent_execute("%reset -f") if kernel_env.get('SPY_AUTOLOAD_PYLAB_O') == 'True': self.silent_execute("from pylab import *") if kernel_env.get('SPY_SYMPY_O') == 'True': sympy_init = """ from __future__ import division from sympy import * x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) init_printing()""" self.silent_execute(dedent(sympy_init)) if kernel_env.get('SPY_RUN_CYTHON') == 'True': self.silent_execute("%reload_ext Cython") self.refresh_namespacebrowser() if not self.external_kernel: self.call_kernel().close_all_mpl_figures() except AttributeError: pass
def save(self): CONF.set_shortcut(self.context, self.name, self.key)
def create_action(self, name, text, icon=None, icon_text='', tip=None, toggled=None, triggered=None, shortcut_context=None, context=Qt.WidgetWithChildrenShortcut, initial=None, register_shortcut=False, section=None, option=None, parent=None): """ name: str unique identifiable name for the action text: str Localized text for the action icon: QIcon, Icon for the action when applied to menu or toolbutton. icon_text: str Icon for text in toolbars. If True, this will also disable the tooltip on this toolbutton if part of a toolbar. tip: str Tooltip to define for action on menu or toolbar. toggled: Optional[Union[Callable, bool]] If True, then the action modifies the configuration option on the section specified. Otherwise, it should be a callable to use when toggling this action. If None, then the action does not behave like a checkbox. triggered: callable The callable to use when triggering this action. shortcut_context: str Set the `str` context of the shortcut. context: Qt.ShortcutContext Set the context for the shortcut. initial: object Sets the initial state of a togglable action. This does not emit the toggled signal. section: Optional[str] Name of the configuration section whose option is going to be modified. If None, and `option` is not None, then it defaults to the class `CONF_SECTION` attribute. option: ConfigurationKey Name of the configuration option whose value is reflected and affected by the action. register_shortcut: bool, optional If True, main window will expose the shortcut in Preferences. The default value is `False`. parent: QWidget (None) Define the parent of the widget. Use `self` if not provided. Notes ----- There is no need to set shortcuts right now. We only create actions with this (and similar methods) and these are then exposed as possible shortcuts on plugin registration in the main window with the register_shortcut argument. If icon_text is True, this will also disable the tooltip. If a shortcut is found in the default config then it is assigned, otherwise it's left blank for the user to define one for it. """ if triggered is None and toggled is None: raise SpyderAPIError( 'Action must provide the toggled or triggered parameters!') if parent is None: parent = self if toggled and not callable(toggled): toggled = lambda value: None if toggled is not None: if section is None and option is not None: section = self.CONF_SECTION action = create_action(parent, text=text, icon=icon, tip=tip, toggled=toggled, triggered=triggered, context=context, section=section, option=option, id_=name, plugin=self.PLUGIN_NAME, context_name=self.CONTEXT_NAME, register_action=True) action.name = name if icon_text: action.setIconText(icon_text) action.text_beside_icon = bool(icon_text) action.shortcut_context = shortcut_context action.register_shortcut = register_shortcut action.tip = tip if initial is not None: if toggled: action.setChecked(initial) elif triggered: raise SpyderAPIError( 'Initial values can only apply to togglable actions!') else: if toggled: if section is not None and option is not None: value = CONF.get(section, option) action.setChecked(value) return action
def set_sequence_to_default(self): """Set the new sequence to the default value defined in the config.""" sequence = CONF.get_default('shortcuts', "{}/{}".format(self.context, self.name)) self._qsequences = sequence.split(', ') self.update_warning()
def set_executable_config_helper(executable=None): if executable is None: CONF.set('main_interpreter', 'default', True) CONF.set('main_interpreter', 'custom', False) CONF.set('main_interpreter', 'custom_interpreter', sys.executable) CONF.set('main_interpreter', 'custom_interpreters_list', [sys.executable]) CONF.set('main_interpreter', 'executable', sys.executable) else: CONF.set('main_interpreter', 'default', False) CONF.set('main_interpreter', 'custom', True) CONF.set('main_interpreter', 'custom_interpreter', executable) CONF.set('main_interpreter', 'custom_interpreters_list', [executable]) CONF.set('main_interpreter', 'executable', executable)
def env(self): """Env vars for kernels""" default_interpreter = CONF.get('main_interpreter', 'default') env_vars = os.environ.copy() # Avoid IPython adding the virtualenv on which Spyder is running # to the kernel sys.path env_vars.pop('VIRTUAL_ENV', None) # Add spyder-kernels subrepo path to PYTHONPATH if DEV or running_under_pytest(): repo_path = osp.normpath(osp.join(HERE, '..', '..', '..', '..')) subrepo_path = osp.join(repo_path, 'external-deps', 'spyder-kernels') env_vars.update({'PYTHONPATH': subrepo_path}) # List of paths declared by the user, plus project's path, to # add to PYTHONPATH pathlist = CONF.get('main', 'spyder_pythonpath', default=[]) pypath = os.pathsep.join(pathlist) # List of modules to exclude from our UMR umr_namelist = CONF.get('main_interpreter', 'umr/namelist') # Environment variables that we need to pass to the kernel env_vars.update({ 'SPY_EXTERNAL_INTERPRETER': not default_interpreter, 'SPY_UMR_ENABLED': CONF.get('main_interpreter', 'umr/enabled'), 'SPY_UMR_VERBOSE': CONF.get('main_interpreter', 'umr/verbose'), 'SPY_UMR_NAMELIST': ','.join(umr_namelist), 'SPY_RUN_LINES_O': CONF.get('ipython_console', 'startup/run_lines'), 'SPY_PYLAB_O': CONF.get('ipython_console', 'pylab'), 'SPY_BACKEND_O': CONF.get('ipython_console', 'pylab/backend'), 'SPY_AUTOLOAD_PYLAB_O': CONF.get('ipython_console', 'pylab/autoload'), 'SPY_FORMAT_O': CONF.get('ipython_console', 'pylab/inline/figure_format'), 'SPY_BBOX_INCHES_O': CONF.get('ipython_console', 'pylab/inline/bbox_inches'), 'SPY_RESOLUTION_O': CONF.get('ipython_console', 'pylab/inline/resolution'), 'SPY_WIDTH_O': CONF.get('ipython_console', 'pylab/inline/width'), 'SPY_HEIGHT_O': CONF.get('ipython_console', 'pylab/inline/height'), 'SPY_USE_FILE_O': CONF.get('ipython_console', 'startup/use_run_file'), 'SPY_RUN_FILE_O': CONF.get('ipython_console', 'startup/run_file'), 'SPY_AUTOCALL_O': CONF.get('ipython_console', 'autocall'), 'SPY_GREEDY_O': CONF.get('ipython_console', 'greedy_completer'), 'SPY_JEDI_O': CONF.get('ipython_console', 'jedi_completer'), 'SPY_SYMPY_O': CONF.get('ipython_console', 'symbolic_math'), 'SPY_TESTING': running_under_pytest() or get_safe_mode(), 'SPY_HIDE_CMD': CONF.get('ipython_console', 'hide_cmd_windows'), 'SPY_PYTHONPATH': pypath }) if self.is_pylab is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = True env_vars['SPY_SYMPY_O'] = False env_vars['SPY_RUN_CYTHON'] = False if self.is_sympy is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = False env_vars['SPY_SYMPY_O'] = True env_vars['SPY_RUN_CYTHON'] = False if self.is_cython is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = False env_vars['SPY_SYMPY_O'] = False env_vars['SPY_RUN_CYTHON'] = True # macOS app considerations if (running_in_mac_app() or is_pynsist()) and not default_interpreter: env_vars.pop('PYTHONHOME', None) env_vars.pop('PYTHONPATH', None) # Making all env_vars strings clean_env_vars = clean_env(env_vars) return clean_env_vars
def test_kite_code_snippets(kite_codeeditor, qtbot): """ Test kite code snippets completions without initial placeholder. See spyder-ide/spyder#10971 """ assert rtree_available code_editor, kite = kite_codeeditor completion = code_editor.completion_widget snippets = code_editor.editor_extensions.get('SnippetsExtension') CONF.set('lsp-server', 'code_snippets', True) CONF.set('kite', 'enable', True) kite.update_configuration() code_editor.toggle_automatic_completions(False) code_editor.toggle_code_snippets(True) # Set cursor to start code_editor.go_to_line(1) text = """ import numpy as np """ text = textwrap.dedent(text) code_editor.insert_text(text) qtbot.keyClicks(code_editor, 'np.sin') with qtbot.waitSignal(completion.sig_show_completions, timeout=10000) as sig: qtbot.keyPress(code_editor, Qt.Key_Tab, delay=300) assert 'sin(' + u'\u2026' + ')' in {x['label'] for x in sig.args[0]} expected_insert = 'sin($1)$0' insert = sig.args[0][0] assert expected_insert == insert['insertText'] # Insert completion qtbot.keyPress(completion, Qt.Key_Tab) assert snippets.is_snippet_active # Get code selected text cursor = code_editor.textCursor() arg1 = cursor.selectedText() assert '' == arg1 assert snippets.active_snippet == 1 code_editor.set_cursor_position('eol') code_editor.move_cursor(-1) with qtbot.waitSignal(completion.sig_show_completions, timeout=10000) as sig2: qtbot.keyPress(code_editor, Qt.Key_Space, modifier=Qt.ControlModifier, delay=300) assert '<x>)' in {x['label'] for x in sig2.args[0]} expected_insert = '${1:[x]})$0' insert = sig2.args[0][0] assert expected_insert == insert['textEdit']['newText'] qtbot.keyPress(completion, Qt.Key_Tab) # Snippets are disabled when there are no more left code_editor.set_cursor_position('eol') qtbot.keyPress(code_editor, Qt.Key_Enter) assert not snippets.is_snippet_active cursor = code_editor.textCursor() cursor.movePosition(QTextCursor.PreviousBlock) cursor.movePosition(QTextCursor.StartOfBlock) cursor.movePosition(QTextCursor.EndOfBlock, mode=QTextCursor.KeepAnchor) text1 = cursor.selectedText() assert text1 == 'np.sin([x])' CONF.set('lsp-server', 'code_snippets', False) CONF.set('kite', 'enable', False) kite.update_configuration() code_editor.toggle_automatic_completions(True) code_editor.toggle_code_snippets(True)
def setup_workingdirectory(qtbot, request): """Setup working directory plugin.""" CONF.reset_to_defaults() use_startup_wdir = request.node.get_closest_marker('use_startup_wdir') if use_startup_wdir: new_wdir = osp.join(os.getcwd(), NEW_DIR) if not osp.exists(new_wdir): os.mkdir(new_wdir) CONF.set('workingdir', 'startup/use_fixed_directory', True) CONF.set('workingdir', 'startup/fixed_directory', new_wdir) else: CONF.set('workingdir', 'startup/use_fixed_directory', False) CONF.set('workingdir', 'console/use_fixed_directory', False) CONF.set('workingdir', 'startup/fixed_directory', get_home_dir()) workingdirectory = WorkingDirectory(None) qtbot.addWidget(workingdirectory) workingdirectory.show() return workingdirectory, qtbot
def teardown(): completions.shutdown() os.environ['SPY_TEST_USE_INTROSPECTION'] = 'False' CONF.set('lsp-server', 'pycodestyle', False) CONF.set('lsp-server', 'pydocstyle', False)
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 _set_run_configurations(configurations): history_count = CONF.get('run', 'history', 20) CONF.set('run', 'configurations', configurations[:history_count])
def _remove_option(self, option, section=None): """Remove option from spyder.ini.""" section = self.CONF_SECTION if section is None else section CONF.remove_option(section, option)