INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Highlight the scope of the current caret position.
def _highlight_caret_scope(self): """ Highlight the scope of the current caret position. This get called only if :attr:` spyder.widgets.panels.FoldingPanel.highlight_care_scope` is True. """ cursor = self.editor.textCursor() block_nbr = cursor.blockNumber() ...
Add options to corner menu.
def set_menu_actions(self, menu_actions): """Add options to corner menu.""" if self.menu_actions is not None: add_actions(self.menu, self.menu_actions)
Refresh tabwidget.
def refresh(self): """Refresh tabwidget.""" if self.tabwidget.count(): editor = self.tabwidget.currentWidget() else: editor = None self.find_widget.set_editor(editor)
Move tab.
def move_tab(self, index_from, index_to): """ Move tab. (tabs themselves have already been moved by the history.tabwidget) """ filename = self.filenames.pop(index_from) editor = self.editors.pop(index_from) self.filenames.insert(index_to, filename) self....
Add new history tab.
def add_history(self, filename, color_scheme, font, wrap): """ Add new history tab. Args: filename (str): file to be loaded in a new tab. """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = c...
Append an entry to history filename.
def append_to_history(self, filename, command, go_to_eof): """ Append an entry to history filename. Args: filename (str): file to be updated in a new tab. command (str): line to be added. go_to_eof (bool): scroll to the end of file. """ if not...
Call function req and then emit its results to the LSP server.
def request(req=None, method=None, requires_response=True): """Call function req and then emit its results to the LSP server.""" if req is None: return functools.partial(request, method=method, requires_response=requires_response) @functools.wraps(req) def wrapp...
Class decorator that allows to map LSP method names to class methods.
def class_register(cls): """Class decorator that allows to map LSP method names to class methods.""" cls.handler_registry = {} for method_name in dir(cls): method = getattr(cls, method_name) if hasattr(method, '_handle'): cls.handler_registry.update({method._handle: method_name})...
Update font from Preferences
def update_font(self): """Update font from Preferences""" font = self.get_plugin_font() for client in self.clients: client.set_font(font)
Apply configuration file s plugin settings
def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" font_n = 'plugin_font' font_o = self.get_plugin_font() help_n = 'connect_to_oi' help_o = CONF.get('help', 'connect/ipython_console') color_scheme_n = 'color_scheme_name' ...
Toggle view
def toggle_view(self, checked): """Toggle view""" if checked: self.dockwidget.show() self.dockwidget.raise_() # Start a client in case there are none shown if not self.clients: if self.main.is_setting_up: self.cr...
Perform actions before parent main window is closed
def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" self.mainwindow_close = True for client in self.clients: client.shutdown() client.remove_stderr_file() client.dialog_manager.close_all() cl...
Refresh tabwidget
def refresh_plugin(self): """Refresh tabwidget""" client = None if self.tabwidget.count(): client = self.tabwidget.currentWidget() # Decide what to show for each client if client.info_page != client.blank_page: # Show info_page if it h...
Return a list of actions related to plugin.
def get_plugin_actions(self): """Return a list of actions related to plugin.""" create_client_action = create_action( self, _("New console (default settings)"), icon=ima.icon('ipython_console'),...
Register plugin in Spyder s main window
def register_plugin(self): """Register plugin in Spyder's main window""" self.main.add_dockwidget(self) self.focus_changed.connect(self.main.plugin_focus_changed) self.edit_goto.connect(self.main.editor.load) self.edit_goto[str, int, str, bool].connect( ...
Return current client with focus if any
def get_focus_client(self): """Return current client with focus, if any""" widget = QApplication.focusWidget() for client in self.get_clients(): if widget is client or widget is client.get_control(): return client
Run script in current or dedicated client
def run_script(self, filename, wdir, args, debug, post_mortem, current_client, clear_variables): """Run script in current or dedicated client""" norm = lambda text: remove_backslashes(to_text_string(text)) # Run Cython files in a dedicated console is_cython = os...
Run cell in current or dedicated client.
def run_cell(self, code, cell_name, filename, run_cell_copy): """Run cell in current or dedicated client.""" def norm(text): return remove_backslashes(to_text_string(text)) self.run_cell_filename = filename # Select client to execute code on it client = se...
Set current client working directory.
def set_current_client_working_directory(self, directory): """Set current client working directory.""" shellwidget = self.get_current_shellwidget() if shellwidget is not None: shellwidget.set_cwd(directory)
Set current working directory. In the workingdirectory and explorer plugins.
def set_working_directory(self, dirname): """Set current working directory. In the workingdirectory and explorer plugins. """ if dirname: self.main.workingdirectory.chdir(dirname, refresh_explorer=True, refresh_console=False)
Execute code instructions.
def execute_code(self, lines, current_client=True, clear_variables=False): """Execute code instructions.""" sw = self.get_current_shellwidget() if sw is not None: if sw._reading: pass else: if not current_client: ...
Create a new client
def create_new_client(self, give_focus=True, filename='', is_cython=False, is_pylab=False, is_sympy=False, given_name=None): """Create a new client""" self.master_clients += 1 client_id = dict(int_id=to_text_string(self.master_clients), str...
Create a client connected to an existing kernel
def create_client_for_kernel(self): """Create a client connected to an existing kernel""" connect_output = KernelConnectionDialog.get_connection_parameters(self) (connection_file, hostname, sshkey, password, ok) = connect_output if not ok: return else: ...
Connect a client to its kernel
def connect_client_to_kernel(self, client, is_cython=False, is_pylab=False, is_sympy=False): """Connect a client to its kernel""" connection_file = client.connection_file stderr_handle = None if self.test_no_stderr else client.stderr_handle km, kc = ...
Handle %edit magic petitions.
def edit_file(self, filename, line): """Handle %edit magic petitions.""" if encoding.is_text_file(filename): # The default line number sent by ipykernel is always the last # one, but we prefer to use the first. self.edit_goto.emit(filename, 1, '')
Generate a Trailets Config instance for shell widgets using our config system This lets us create each widget with its own config
def config_options(self): """ Generate a Trailets Config instance for shell widgets using our config system This lets us create each widget with its own config """ # ---- Jupyter config ---- try: full_cfg = load_pyconfig_files(['jupyter_qtcon...
Python and IPython versions used by clients
def interpreter_versions(self): """Python and IPython versions used by clients""" if CONF.get('main_interpreter', 'default'): from IPython.core import release versions = dict( python_version = sys.version.split("\n")[0].strip(), ipython_versi...
Additional options for shell widgets that are not defined in JupyterWidget config options
def additional_options(self, is_pylab=False, is_sympy=False): """ Additional options for shell widgets that are not defined in JupyterWidget config options """ options = dict( pylab=self.get_option('pylab'), autoload_pylab=self.get_option('pylab/aut...
Register new client
def register_client(self, client, give_focus=True): """Register new client""" client.configure_shellwidget(give_focus=give_focus) # Local vars shellwidget = client.shellwidget control = shellwidget._control page_control = shellwidget._page_control # Cre...
Close client tab from index or widget ( or close current tab )
def close_client(self, index=None, client=None, force=False): """Close client tab from index or widget (or close current tab)""" if not self.tabwidget.count(): return if client is not None: index = self.tabwidget.indexOf(client) # if index is not found i...
Return client index from id
def get_client_index_from_id(self, client_id): """Return client index from id""" for index, client in enumerate(self.clients): if id(client) == client_id: return index
Get all other clients that are connected to the same kernel as client
def get_related_clients(self, client): """ Get all other clients that are connected to the same kernel as `client` """ related_clients = [] for cl in self.get_clients(): if cl.connection_file == client.connection_file and \ cl is not client: ...
Close all clients related to * client * except itself
def close_related_clients(self, client): """Close all clients related to *client*, except itself""" related_clients = self.get_related_clients(client) for cl in related_clients: self.close_client(client=cl, force=True)
Restart the console This is needed when we switch projects to update PYTHONPATH and the selected interpreter
def restart(self): """ Restart the console This is needed when we switch projects to update PYTHONPATH and the selected interpreter """ self.master_clients = 0 self.create_new_client_if_empty = False for i in range(len(self.clients)): ...
Python debugger has just stopped at frame ( fname lineno )
def pdb_has_stopped(self, fname, lineno, shellwidget): """Python debugger has just stopped at frame (fname, lineno)""" # This is a unique form of the edit_goto signal that is intended to # prevent keyboard input from accidentally entering the editor # during repeated, rapid entry of ...
Create a client with its cwd pointing to path.
def create_client_from_path(self, path): """Create a client with its cwd pointing to path.""" self.create_new_client() sw = self.get_current_shellwidget() sw.set_cwd(path)
Create a client to execute code related to a file.
def create_client_for_file(self, filename, is_cython=False): """Create a client to execute code related to a file.""" # Create client self.create_new_client(filename=filename, is_cython=is_cython) # Don't increase the count of master clients self.master_clients -= 1 ...
Get client associated with a given file.
def get_client_for_file(self, filename): """Get client associated with a given file.""" client = None for idx, cl in enumerate(self.get_clients()): if self.filenames[idx] == filename: self.tabwidget.setCurrentIndex(idx) client = cl ...
Set elapsed time for slave clients.
def set_elapsed_time(self, client): """Set elapsed time for slave clients.""" related_clients = self.get_related_clients(client) for cl in related_clients: if cl.timer is not None: client.create_time_label() client.t0 = cl.t0 cli...
Tunnel connections to a kernel via ssh. Remote ports are specified in the connection info ci.
def tunnel_to_kernel(self, connection_info, hostname, sshkey=None, password=None, timeout=10): """ Tunnel connections to a kernel via ssh. Remote ports are specified in the connection info ci. """ lports = zmqtunnel.select_random_ports(4) ...
Create a kernel spec for our own kernels
def create_kernel_spec(self, is_cython=False, is_pylab=False, is_sympy=False): """Create a kernel spec for our own kernels""" # Before creating our kernel spec, we always need to # set this value in spyder.ini CONF.set('main', 'spyder_pythonpath', ...
Create kernel manager and client.
def create_kernel_manager_and_kernel_client(self, connection_file, stderr_handle, is_cython=False, is_pylab=False, is_sympy=...
Restart kernel of current client.
def restart_kernel(self): """Restart kernel of current client.""" client = self.get_current_client() if client is not None: self.switch_to_plugin() client.restart_kernel()
Reset kernel of current client.
def reset_kernel(self): """Reset kernel of current client.""" client = self.get_current_client() if client is not None: self.switch_to_plugin() client.reset_namespace()
Interrupt kernel of current client.
def interrupt_kernel(self): """Interrupt kernel of current client.""" client = self.get_current_client() if client is not None: self.switch_to_plugin() client.stop_button_click_handler()
Update actions following the execution state of the kernel.
def update_execution_state_kernel(self): """Update actions following the execution state of the kernel.""" client = self.get_current_client() if client is not None: executing = client.stop_button.isEnabled() self.interrupt_action.setEnabled(executing)
Connect an external kernel to the Variable Explorer and Help if it is a Spyder kernel.
def connect_external_kernel(self, shellwidget): """ Connect an external kernel to the Variable Explorer and Help, if it is a Spyder kernel. """ sw = shellwidget kc = shellwidget.kernel_client if self.main.help is not None: self.main.help.set_sh...
Add tab
def add_tab(self, widget, name, filename=''): """Add tab""" self.clients.append(widget) index = self.tabwidget.addTab(widget, name) self.filenames.insert(index, filename) self.tabwidget.setCurrentIndex(index) if self.dockwidget and not self.main.is_setting_up: ...
Move tab ( tabs themselves have already been moved by the tabwidget )
def move_tab(self, index_from, index_to): """ Move tab (tabs themselves have already been moved by the tabwidget) """ filename = self.filenames.pop(index_from) client = self.clients.pop(index_from) self.filenames.insert(index_to, filename) self.clients.inse...
Generate a file name without ambiguation.
def disambiguate_fname(self, fname): """Generate a file name without ambiguation.""" files_path_list = [filename for filename in self.filenames if filename] return sourcecode.disambiguate_fname(files_path_list, fname)
Update the text from the tabs.
def update_tabs_text(self): """Update the text from the tabs.""" # This is needed to prevent that hanged consoles make reference # to an index that doesn't exist. See issue 4881 try: for index, fname in enumerate(self.filenames): client = self.clients[in...
Rename client s tab
def rename_client_tab(self, client, given_name): """Rename client's tab""" index = self.get_client_index_from_id(id(client)) if given_name is not None: client.given_name = given_name self.tabwidget.setTabText(index, client.get_name())
Rename tabs after a change in name.
def rename_tabs_after_change(self, given_name): """Rename tabs after a change in name.""" client = self.get_current_client() # Prevent renames that want to assign the same name of # a previous tab repeated = False for cl in self.get_clients(): if id(c...
Trigger the tab name editor.
def tab_name_editor(self): """Trigger the tab name editor.""" index = self.tabwidget.currentIndex() self.tabwidget.tabBar().tab_name_editor.edit_tab(index)
Go to error if relevant
def go_to_error(self, text): """Go to error if relevant""" match = get_error_match(to_text_string(text)) if match: fname, lnb = match.groups() if ("<ipython-input-" in fname and self.run_cell_filename is not None): fname = self.r...
Show intro to IPython help
def show_intro(self): """Show intro to IPython help""" from IPython.core.usage import interactive_usage self.main.help.show_rich_text(interactive_usage)
Show qtconsole help
def show_guiref(self): """Show qtconsole help""" from qtconsole.usage import gui_reference self.main.help.show_rich_text(gui_reference, collapse=True)
Show IPython Cheat Sheet
def show_quickref(self): """Show IPython Cheat Sheet""" from IPython.core.usage import quick_reference self.main.help.show_plain_text(quick_reference)
Generate a new connection file Taken from jupyter_client/ console_app. py Licensed under the BSD license
def _new_connection_file(self): """ Generate a new connection file Taken from jupyter_client/console_app.py Licensed under the BSD license """ # Check if jupyter_runtime_dir exists (Spyder addition) if not osp.isdir(jupyter_runtime_dir()): tr...
Remove stderr files left by previous Spyder instances. This is only required on Windows because we can t clean up stderr files while Spyder is running on it.
def _remove_old_stderr_files(self): """ Remove stderr files left by previous Spyder instances. This is only required on Windows because we can't clean up stderr files while Spyder is running on it. """ if os.name == 'nt': tmpdir = get_temp_dir() ...
Rotate the kill ring then yank back the new top.
def rotate(self): """ Rotate the kill ring, then yank back the new top. Returns ------- A text string or None. """ self._index -= 1 if self._index >= 0: return self._ring[self._index] return None
Kills the text selected by the give cursor.
def kill_cursor(self, cursor): """ Kills the text selected by the give cursor. """ text = cursor.selectedText() if text: cursor.removeSelectedText() self.kill(text)
Yank back the most recently killed text.
def yank(self): """ Yank back the most recently killed text. """ text = self._ring.yank() if text: self._skip_cursor = True cursor = self._text_edit.textCursor() cursor.insertText(text) self._prev_yank = text
Show files in external file explorer Args: fnames ( list ): Names of files to show.
def show_in_external_file_explorer(fnames=None): """Show files in external file explorer Args: fnames (list): Names of files to show. """ if not isinstance(fnames, (tuple, list)): fnames = [fnames] for fname in fnames: open_file_in_external_explorer(fname)
Normalize path fixing case making absolute and removing symlinks
def fixpath(path): """Normalize path fixing case, making absolute and removing symlinks""" norm = osp.normcase if os.name == 'nt' else osp.normpath return norm(osp.abspath(osp.realpath(path)))
Create a new Python script
def create_script(fname): """Create a new Python script""" text = os.linesep.join(["# -*- coding: utf-8 -*-", "", ""]) try: encoding.write(to_text_string(text), fname, 'utf-8') except EnvironmentError as error: QMessageBox.critical(_("Save Error"), _("...
List files and directories
def listdir(path, include=r'.', exclude=r'\.pyc$|^\.', show_all=False, folders_only=False): """List files and directories""" namelist = [] dirlist = [to_text_string(osp.pardir)] for item in os.listdir(to_text_string(path)): if re.search(exclude, item) and not show_all: ...
Return True if path has subdirectories
def has_subdirectories(path, include, exclude, show_all): """Return True if path has subdirectories""" try: # > 1 because of '..' return len( listdir(path, include, exclude, show_all, folders_only=True) ) > 1 except (IOError, OSError): return False
Reimplement Qt method
def icon(self, icontype_or_qfileinfo): """Reimplement Qt method""" if isinstance(icontype_or_qfileinfo, QFileIconProvider.IconType): return super(IconProvider, self).icon(icontype_or_qfileinfo) else: qfileinfo = icontype_or_qfileinfo fname = osp.normpath...
Setup filesystem model
def setup_fs_model(self): """Setup filesystem model""" filters = QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot self.fsmodel = QFileSystemModel(self) self.fsmodel.setFilter(filters) self.fsmodel.setNameFilterDisables(False)
Setup view
def setup_view(self): """Setup view""" self.install_model() self.fsmodel.directoryLoaded.connect( lambda: self.resizeColumnToContents(0)) self.setAnimated(False) self.setSortingEnabled(True) self.sortByColumn(0, Qt.AscendingOrder) self.fsmodel....
Set single click to open items.
def set_single_click_to_open(self, value): """Set single click to open items.""" self.single_click_to_open = value self.parent_widget.sig_option_changed.emit('single_click_to_open', value)
Set name filters
def set_name_filters(self, name_filters): """Set name filters""" self.name_filters = name_filters self.fsmodel.setNameFilters(name_filters)
Toggle show all files state
def set_show_all(self, state): """Toggle 'show all files' state""" if state: self.fsmodel.setNameFilters([]) else: self.fsmodel.setNameFilters(self.name_filters)
Return filename associated with * index *
def get_filename(self, index): """Return filename associated with *index*""" if index: return osp.normpath(to_text_string(self.fsmodel.filePath(index)))
Return selected filenames
def get_selected_filenames(self): """Return selected filenames""" if self.selectionMode() == self.ExtendedSelection: if self.selectionModel() is None: return [] return [self.get_filename(idx) for idx in self.selectionModel().selectedRows...
Return dirname associated with * index *
def get_dirname(self, index): """Return dirname associated with *index*""" fname = self.get_filename(index) if fname: if osp.isdir(fname): return fname else: return osp.dirname(fname)
Setup tree widget
def setup(self, name_filters=['*.py', '*.pyw'], show_all=False, single_click_to_open=False): """Setup tree widget""" self.setup_view() self.set_name_filters(name_filters) self.show_all = show_all self.single_click_to_open = single_click_to_open ...
Setup context menu common actions
def setup_common_actions(self): """Setup context menu common actions""" # Filters filters_action = create_action(self, _("Edit filename filters..."), None, ima.icon('filter'), triggered=self.edit_filter) ...
Edit name filters
def edit_filter(self): """Edit name filters""" filters, valid = QInputDialog.getText(self, _('Edit filename filters'), _('Name filters:'), QLineEdit.Normal, ", "...
Toggle all files mode
def toggle_all(self, checked): """Toggle all files mode""" self.parent_widget.sig_option_changed.emit('show_all', checked) self.show_all = checked self.set_show_all(checked)
Return actions for submenu New...
def create_file_new_actions(self, fnames): """Return actions for submenu 'New...'""" if not fnames: return [] new_file_act = create_action(self, _("File..."), icon=ima.icon('filenew'), triggered=lambda: ...
Return file management actions
def create_file_manage_actions(self, fnames): """Return file management actions""" only_files = all([osp.isfile(_fn) for _fn in fnames]) only_modules = all([osp.splitext(_fn)[1] in ('.py', '.pyw', '.ipy') for _fn in fnames]) only_notebooks = all([osp.spli...
Return folder management actions
def create_folder_manage_actions(self, fnames): """Return folder management actions""" actions = [] if os.name == 'nt': _title = _("Open command prompt here") else: _title = _("Open terminal here") _title = _("Open IPython console here") ac...
Create context menu actions
def create_context_menu_actions(self): """Create context menu actions""" actions = [] fnames = self.get_selected_filenames() new_actions = self.create_file_new_actions(fnames) if len(new_actions) > 1: # Creating a submenu only if there is more than one entry ...
Update context menu
def update_menu(self): """Update context menu""" self.menu.clear() add_actions(self.menu, self.create_context_menu_actions())
Reimplement Qt method
def keyPressEvent(self, event): """Reimplement Qt method""" if event.key() in (Qt.Key_Enter, Qt.Key_Return): self.clicked() elif event.key() == Qt.Key_F2: self.rename() elif event.key() == Qt.Key_Delete: self.delete() elif event.key() =...
Reimplement Qt method.
def mouseReleaseEvent(self, event): """Reimplement Qt method.""" QTreeView.mouseReleaseEvent(self, event) if self.single_click_to_open: self.clicked()
Selected item was double - clicked or enter/ return was pressed
def clicked(self): """Selected item was double-clicked or enter/return was pressed""" fnames = self.get_selected_filenames() for fname in fnames: if osp.isdir(fname): self.directory_clicked(fname) else: self.open([fname])
Drag and Drop - Move event
def dragMoveEvent(self, event): """Drag and Drop - Move event""" if (event.mimeData().hasFormat("text/plain")): event.setDropAction(Qt.MoveAction) event.accept() else: event.ignore()
Reimplement Qt Method - handle drag event
def startDrag(self, dropActions): """Reimplement Qt Method - handle drag event""" data = QMimeData() data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()]) drag = QDrag(self) drag.setMimeData(data) drag.exec_()
Open files with the appropriate application
def open(self, fnames=None): """Open files with the appropriate application""" if fnames is None: fnames = self.get_selected_filenames() for fname in fnames: if osp.isfile(fname) and encoding.is_text_file(fname): self.parent_widget.sig_open_file.emit...
Open files with default application
def open_external(self, fnames=None): """Open files with default application""" if fnames is None: fnames = self.get_selected_filenames() for fname in fnames: self.open_outside_spyder([fname])
Open file outside Spyder with the appropriate application If this does not work opening unknown file in Spyder as text file
def open_outside_spyder(self, fnames): """Open file outside Spyder with the appropriate application If this does not work, opening unknown file in Spyder, as text file""" for path in sorted(fnames): path = file_uri(path) ok = programs.start_file(path) if...
Open interpreter
def open_interpreter(self, fnames): """Open interpreter""" for path in sorted(fnames): self.sig_open_interpreter.emit(path)
Run Python scripts
def run(self, fnames=None): """Run Python scripts""" if fnames is None: fnames = self.get_selected_filenames() for fname in fnames: self.sig_run.emit(fname)
Remove whole directory tree Reimplemented in project explorer widget
def remove_tree(self, dirname): """Remove whole directory tree Reimplemented in project explorer widget""" while osp.exists(dirname): try: shutil.rmtree(dirname, onerror=misc.onerror) except Exception as e: # This handles a Windows p...
Delete file
def delete_file(self, fname, multiple, yes_to_all): """Delete file""" if multiple: buttons = QMessageBox.Yes|QMessageBox.YesToAll| \ QMessageBox.No|QMessageBox.Cancel else: buttons = QMessageBox.Yes|QMessageBox.No if yes_to_all is None...
Delete files
def delete(self, fnames=None): """Delete files""" if fnames is None: fnames = self.get_selected_filenames() multiple = len(fnames) > 1 yes_to_all = None for fname in fnames: spyproject_path = osp.join(fname,'.spyproject') if osp.isdir(f...
Convert an IPython notebook to a Python script in editor
def convert_notebook(self, fname): """Convert an IPython notebook to a Python script in editor""" try: script = nbexporter().from_filename(fname)[0] except Exception as e: QMessageBox.critical(self, _('Conversion error'), _("It was...