text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Called when sig_option_changed is received. <END_TASK> <USER_TASK:> Description: def received_sig_option_changed(self, option, value): """ Called when sig_option_changed is received. If option being changed is autosave_mapping, then synchronize new mapping with all editor stacks except the sender. """
if option == 'autosave_mapping': for editorstack in self.editorstacks: if editorstack != self.sender(): editorstack.autosave_mapping = value self.sig_option_changed.emit(option, value)
<SYSTEM_TASK:> Removing editorstack only if it's not the last remaining <END_TASK> <USER_TASK:> Description: def unregister_editorstack(self, editorstack): """Removing editorstack only if it's not the last remaining"""
self.remove_last_focus_editorstack(editorstack) if len(self.editorstacks) > 1: index = self.editorstacks.index(editorstack) self.editorstacks.pop(index) return True else: # editorstack was not removed! return False
<SYSTEM_TASK:> Enable 'Save All' if there are files to be saved <END_TASK> <USER_TASK:> Description: def refresh_save_all_action(self): """Enable 'Save All' if there are files to be saved"""
editorstack = self.get_current_editorstack() if editorstack: state = any(finfo.editor.document().isModified() or finfo.newly_created for finfo in editorstack.data) self.save_all_action.setEnabled(state)
<SYSTEM_TASK:> Synchronize todo results between editorstacks <END_TASK> <USER_TASK:> Description: def todo_results_changed(self): """ Synchronize todo results between editorstacks Refresh todo list navigation buttons """
editorstack = self.get_current_editorstack() results = editorstack.get_todo_results() index = editorstack.get_stack_index() if index != -1: filename = editorstack.data[index].filename for other_editorstack in self.editorstacks: if other_editorstack is not editorstack: other_editorstack.set_todo_results(filename, results) self.update_todo_actions()
<SYSTEM_TASK:> Receive bookmark changes and save them. <END_TASK> <USER_TASK:> Description: def save_bookmarks(self, filename, bookmarks): """Receive bookmark changes and save them."""
filename = to_text_string(filename) bookmarks = to_text_string(bookmarks) filename = osp.normpath(osp.abspath(filename)) bookmarks = eval(bookmarks) save_bookmarks(filename, bookmarks)
<SYSTEM_TASK:> Load temporary file from a text file in user home directory <END_TASK> <USER_TASK:> Description: def __load_temp_file(self): """Load temporary file from a text file in user home directory"""
if not osp.isfile(self.TEMPFILE_PATH): # Creating temporary file default = ['# -*- coding: utf-8 -*-', '"""', _("Spyder Editor"), '', _("This is a temporary script file."), '"""', '', ''] text = os.linesep.join([encoding.to_unicode(qstr) for qstr in default]) try: encoding.write(to_text_string(text), self.TEMPFILE_PATH, 'utf-8') except EnvironmentError: self.new() return self.load(self.TEMPFILE_PATH)
<SYSTEM_TASK:> Set current script directory as working directory <END_TASK> <USER_TASK:> Description: def __set_workdir(self): """Set current script directory as working directory"""
fname = self.get_current_filename() if fname is not None: directory = osp.dirname(osp.abspath(fname)) self.open_dir.emit(directory)
<SYSTEM_TASK:> Add to recent file list <END_TASK> <USER_TASK:> Description: def __add_recent_file(self, fname): """Add to recent file list"""
if fname is None: return if fname in self.recent_files: self.recent_files.remove(fname) self.recent_files.insert(0, fname) if len(self.recent_files) > self.get_option('max_recent_files'): self.recent_files.pop(-1)
<SYSTEM_TASK:> Reopens the last closed tab. <END_TASK> <USER_TASK:> Description: def open_last_closed(self): """ Reopens the last closed tab."""
editorstack = self.get_current_editorstack() last_closed_files = editorstack.get_last_closed_files() if (len(last_closed_files) > 0): file_to_open = last_closed_files[0] last_closed_files.remove(file_to_open) editorstack.set_last_closed_files(last_closed_files) self.load(file_to_open)
<SYSTEM_TASK:> Close file from its name <END_TASK> <USER_TASK:> Description: def close_file_from_name(self, filename): """Close file from its name"""
filename = osp.abspath(to_text_string(filename)) index = self.editorstacks[0].has_filename(filename) if index is not None: self.editorstacks[0].close_file(index)
<SYSTEM_TASK:> Directory was removed in project explorer widget <END_TASK> <USER_TASK:> Description: def removed_tree(self, dirname): """Directory was removed in project explorer widget"""
dirname = osp.abspath(to_text_string(dirname)) for fname in self.get_filenames(): if osp.abspath(fname).startswith(dirname): self.close_file_from_name(fname)
<SYSTEM_TASK:> File was renamed in file explorer widget or in project explorer <END_TASK> <USER_TASK:> Description: def renamed(self, source, dest): """File was renamed in file explorer widget or in project explorer"""
filename = osp.abspath(to_text_string(source)) index = self.editorstacks[0].has_filename(filename) if index is not None: for editorstack in self.editorstacks: editorstack.rename_in_data(filename, new_filename=to_text_string(dest))
<SYSTEM_TASK:> Directory was renamed in file explorer or in project explorer. <END_TASK> <USER_TASK:> Description: def renamed_tree(self, source, dest): """Directory was renamed in file explorer or in project explorer."""
dirname = osp.abspath(to_text_string(source)) tofile = to_text_string(dest) for fname in self.get_filenames(): if osp.abspath(fname).startswith(dirname): new_filename = fname.replace(dirname, tofile) self.renamed(source=fname, dest=new_filename)
<SYSTEM_TASK:> Clear breakpoints in all files <END_TASK> <USER_TASK:> Description: def clear_all_breakpoints(self): """Clear breakpoints in all files"""
self.switch_to_plugin() clear_all_breakpoints() self.breakpoints_saved.emit() editorstack = self.get_current_editorstack() if editorstack is not None: for data in editorstack.data: data.editor.debugger.clear_breakpoints() self.refresh_plugin()
<SYSTEM_TASK:> Remove a single breakpoint <END_TASK> <USER_TASK:> Description: def clear_breakpoint(self, filename, lineno): """Remove a single breakpoint"""
clear_breakpoint(filename, lineno) self.breakpoints_saved.emit() editorstack = self.get_current_editorstack() if editorstack is not None: index = self.is_file_opened(filename) if index is not None: editorstack.data[index].editor.debugger.toogle_breakpoint( lineno)
<SYSTEM_TASK:> Run script inside current interpreter or in a new one <END_TASK> <USER_TASK:> Description: def run_file(self, debug=False): """Run script inside current interpreter or in a new one"""
editorstack = self.get_current_editorstack() if editorstack.save(): editor = self.get_current_editor() fname = osp.abspath(self.get_current_filename()) # Get fname's dirname before we escape the single and double # quotes (Fixes Issue #6771) dirname = osp.dirname(fname) # Escape single and double quotes in fname and dirname # (Fixes Issue #2158) fname = fname.replace("'", r"\'").replace('"', r'\"') dirname = dirname.replace("'", r"\'").replace('"', r'\"') runconf = get_run_configuration(fname) if runconf is None: dialog = RunConfigOneDialog(self) dialog.size_change.connect(lambda s: self.set_dialog_size(s)) if self.dialog_size is not None: dialog.resize(self.dialog_size) dialog.setup(fname) if CONF.get('run', 'open_at_least_once', not running_under_pytest()): # Open Run Config dialog at least once: the first time # a script is ever run in Spyder, so that the user may # see it at least once and be conscious that it exists show_dlg = True CONF.set('run', 'open_at_least_once', False) else: # Open Run Config dialog only # if ALWAYS_OPEN_FIRST_RUN_OPTION option is enabled show_dlg = CONF.get('run', ALWAYS_OPEN_FIRST_RUN_OPTION) if show_dlg and not dialog.exec_(): return runconf = dialog.get_configuration() args = runconf.get_arguments() python_args = runconf.get_python_arguments() interact = runconf.interact post_mortem = runconf.post_mortem current = runconf.current systerm = runconf.systerm clear_namespace = runconf.clear_namespace if runconf.file_dir: wdir = dirname elif runconf.cw_dir: wdir = '' elif osp.isdir(runconf.dir): wdir = runconf.dir else: wdir = '' python = True # Note: in the future, it may be useful to run # something in a terminal instead of a Python interp. self.__last_ec_exec = (fname, wdir, args, interact, debug, python, python_args, current, systerm, post_mortem, clear_namespace) self.re_run_file() if not interact and not debug: # If external console dockwidget is hidden, it will be # raised in top-level and so focus will be given to the # current external shell automatically # (see SpyderPluginWidget.visibility_changed method) editor.setFocus()
<SYSTEM_TASK:> Save current line and position as bookmark. <END_TASK> <USER_TASK:> Description: def save_bookmark(self, slot_num): """Save current line and position as bookmark."""
bookmarks = CONF.get('editor', 'bookmarks') editorstack = self.get_current_editorstack() if slot_num in bookmarks: filename, line_num, column = bookmarks[slot_num] if osp.isfile(filename): index = editorstack.has_filename(filename) if index is not None: block = (editorstack.tabs.widget(index).document() .findBlockByNumber(line_num)) block.userData().bookmarks.remove((slot_num, column)) if editorstack is not None: self.switch_to_plugin() editorstack.set_bookmark(slot_num)
<SYSTEM_TASK:> Get the list of open files in the current stack <END_TASK> <USER_TASK:> Description: def get_open_filenames(self): """Get the list of open files in the current stack"""
editorstack = self.editorstacks[0] filenames = [] filenames += [finfo.filename for finfo in editorstack.data] return filenames
<SYSTEM_TASK:> Set the recent opened files on editor based on active project. <END_TASK> <USER_TASK:> Description: def set_open_filenames(self): """ Set the recent opened files on editor based on active project. If no project is active, then editor filenames are saved, otherwise the opened filenames are stored in the project config info. """
if self.projects is not None: if not self.projects.get_active_project(): filenames = self.get_open_filenames() self.set_option('filenames', filenames)
<SYSTEM_TASK:> Open the list of saved files per project. <END_TASK> <USER_TASK:> Description: def setup_open_files(self): """ Open the list of saved files per project. Also open any files that the user selected in the recovery dialog. """
self.set_create_new_file_if_empty(False) active_project_path = None if self.projects is not None: active_project_path = self.projects.get_active_project_path() if active_project_path: filenames = self.projects.get_project_filenames() else: filenames = self.get_option('filenames', default=[]) self.close_all_files() all_filenames = self.autosave.recover_files_to_open + filenames if all_filenames and any([osp.isfile(f) for f in all_filenames]): layout = self.get_option('layout_settings', None) # Check if no saved layout settings exist, e.g. clean prefs file # If not, load with default focus/layout, to fix issue #8458 . if layout: is_vertical, cfname, clines = layout.get('splitsettings')[0] if cfname in filenames: index = filenames.index(cfname) # First we load the last focused file. self.load(filenames[index], goto=clines[index], set_focus=True) # Then we load the files located to the left of the last # focused file in the tabbar, while keeping the focus on # the last focused file. if index > 0: self.load(filenames[index::-1], goto=clines[index::-1], set_focus=False, add_where='start') # Then we load the files located to the right of the last # focused file in the tabbar, while keeping the focus on # the last focused file. if index < (len(filenames) - 1): self.load(filenames[index+1:], goto=clines[index:], set_focus=False, add_where='end') # Finally we load any recovered files at the end of the tabbar, # while keeping focus on the last focused file. if self.autosave.recover_files_to_open: self.load(self.autosave.recover_files_to_open, set_focus=False, add_where='end') else: if filenames: self.load(filenames, goto=clines) if self.autosave.recover_files_to_open: self.load(self.autosave.recover_files_to_open) else: if filenames: self.load(filenames) if self.autosave.recover_files_to_open: self.load(self.autosave.recover_files_to_open) if self.__first_open_files_setup: self.__first_open_files_setup = False if layout is not None: self.editorsplitter.set_layout_settings( layout, dont_goto=filenames[0]) win_layout = self.get_option('windows_layout_settings', []) if win_layout: for layout_settings in win_layout: self.editorwindows_to_be_created.append( layout_settings) self.set_last_focus_editorstack(self, self.editorstacks[0]) else: self.__load_temp_file() self.set_create_new_file_if_empty(True)
<SYSTEM_TASK:> Initialize the logger for this thread. <END_TASK> <USER_TASK:> Description: def logger_init(level): """ Initialize the logger for this thread. Sets the log level to ERROR (0), WARNING (1), INFO (2), or DEBUG (3), depending on the argument `level`. """
levellist = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] handler = logging.StreamHandler() fmt = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' '-35s %(lineno) -5d: %(message)s') handler.setFormatter(logging.Formatter(fmt)) logger = logging.root logger.addHandler(handler) logger.setLevel(levellist[level])
<SYSTEM_TASK:> Restore signal handlers to their original settings. <END_TASK> <USER_TASK:> Description: def restore(self): """Restore signal handlers to their original settings."""
signal.signal(signal.SIGINT, self.original_sigint) signal.signal(signal.SIGTERM, self.original_sigterm) if os.name == 'nt': signal.signal(signal.SIGBREAK, self.original_sigbreak)
<SYSTEM_TASK:> Show warning using Tkinter if available <END_TASK> <USER_TASK:> Description: def show_warning(message): """Show warning using Tkinter if available"""
try: # If Tkinter is installed (highly probable), showing an error pop-up import Tkinter, tkMessageBox root = Tkinter.Tk() root.withdraw() tkMessageBox.showerror("Spyder", message) except ImportError: pass raise RuntimeError(message)
<SYSTEM_TASK:> Determine if the lock of the given name is held or not. <END_TASK> <USER_TASK:> Description: def isLocked(name): """Determine if the lock of the given name is held or not. @type name: C{str} @param name: The filesystem path to the lock to test @rtype: C{bool} @return: True if the lock is held, False otherwise. """
l = FilesystemLock(name) result = None try: result = l.lock() finally: if result: l.unlock() return not result
<SYSTEM_TASK:> Acquire this lock. <END_TASK> <USER_TASK:> Description: def lock(self): """ Acquire this lock. @rtype: C{bool} @return: True if the lock is acquired, false otherwise. @raise: Any exception os.symlink() may raise, other than EEXIST. """
clean = True while True: try: symlink(str(os.getpid()), self.name) except OSError as e: if _windows and e.errno in (errno.EACCES, errno.EIO): # The lock is in the middle of being deleted because we're # on Windows where lock removal isn't atomic. Give up, we # don't know how long this is going to take. return False if e.errno == errno.EEXIST: try: pid = readlink(self.name) except OSError as e: if e.errno == errno.ENOENT: # The lock has vanished, try to claim it in the # next iteration through the loop. continue raise except IOError as e: if _windows and e.errno == errno.EACCES: # The lock is in the middle of being # deleted because we're on Windows where # lock removal isn't atomic. Give up, we # don't know how long this is going to # take. return False raise try: if kill is not None: kill(int(pid), 0) # Verify that the running process corresponds to # a Spyder one p = psutil.Process(int(pid)) # Valid names for main script names = set(['spyder', 'spyder3', 'spyder.exe', 'spyder3.exe', 'bootstrap.py', 'spyder-script.py']) if running_under_pytest(): names.add('runtests.py') # Check the first three command line arguments arguments = set(os.path.basename(arg) for arg in p.cmdline()[:3]) conditions = [names & arguments] if not any(conditions): raise(OSError(errno.ESRCH, 'No such process')) except OSError as e: if e.errno == errno.ESRCH: # The owner has vanished, try to claim it in the # next iteration through the loop. try: rmlink(self.name) except OSError as e: if e.errno == errno.ENOENT: # Another process cleaned up the lock. # Race them to acquire it in the next # iteration through the loop. continue raise clean = False continue raise return False raise self.locked = True self.clean = clean return True
<SYSTEM_TASK:> Release this lock. <END_TASK> <USER_TASK:> Description: def unlock(self): """ Release this lock. This deletes the directory with the given name. @raise: Any exception os.readlink() may raise, or ValueError if the lock is not owned by this process. """
pid = readlink(self.name) if int(pid) != os.getpid(): raise ValueError("Lock %r not owned by this process" % (self.name,)) rmlink(self.name) self.locked = False
<SYSTEM_TASK:> Start thread to render a given documentation <END_TASK> <USER_TASK:> Description: def render(self, doc, context=None, math_option=False, img_path='', css_path=CSS_PATH): """Start thread to render a given documentation"""
# If the thread is already running wait for it to finish before # starting it again. if self.wait(): self.doc = doc self.context = context self.math_option = math_option self.img_path = img_path self.css_path = css_path # This causes run() to be executed in separate thread self.start()
<SYSTEM_TASK:> Adds an external path to the combobox if it exists on the file system. <END_TASK> <USER_TASK:> Description: def add_external_path(self, path): """ Adds an external path to the combobox if it exists on the file system. If the path is already listed in the combobox, it is removed from its current position and added back at the end. If the maximum number of paths is reached, the oldest external path is removed from the list. """
if not osp.exists(path): return self.removeItem(self.findText(path)) self.addItem(path) self.setItemData(self.count() - 1, path, Qt.ToolTipRole) while self.count() > MAX_PATH_HISTORY + EXTERNAL_PATHS: self.removeItem(EXTERNAL_PATHS)
<SYSTEM_TASK:> Returns a list of the external paths listed in the combobox. <END_TASK> <USER_TASK:> Description: def get_external_paths(self): """Returns a list of the external paths listed in the combobox."""
return [to_text_string(self.itemText(i)) for i in range(EXTERNAL_PATHS, self.count())]
<SYSTEM_TASK:> Returns the path corresponding to the currently selected item <END_TASK> <USER_TASK:> Description: def get_current_searchpath(self): """ Returns the path corresponding to the currently selected item in the combobox. """
idx = self.currentIndex() if idx == CWD: return self.path elif idx == PROJECT: return self.project_path elif idx == FILE_PATH: return self.file_path else: return self.external_path
<SYSTEM_TASK:> Handles when the current index of the combobox changes. <END_TASK> <USER_TASK:> Description: def path_selection_changed(self): """Handles when the current index of the combobox changes."""
idx = self.currentIndex() if idx == SELECT_OTHER: external_path = self.select_directory() if len(external_path) > 0: self.add_external_path(external_path) self.setCurrentIndex(self.count() - 1) else: self.setCurrentIndex(CWD) elif idx == CLEAR_LIST: reply = QMessageBox.question( self, _("Clear other directories"), _("Do you want to clear the list of other directories?"), QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: self.clear_external_paths() self.setCurrentIndex(CWD) elif idx >= EXTERNAL_PATHS: self.external_path = to_text_string(self.itemText(idx))
<SYSTEM_TASK:> Sets the project path and disables the project search in the combobox <END_TASK> <USER_TASK:> Description: def set_project_path(self, path): """ Sets the project path and disables the project search in the combobox if the value of path is None. """
if path is None: self.project_path = None self.model().item(PROJECT, 0).setEnabled(False) if self.currentIndex() == PROJECT: self.setCurrentIndex(CWD) else: path = osp.abspath(path) self.project_path = path self.model().item(PROJECT, 0).setEnabled(True)
<SYSTEM_TASK:> Used to handle key events on the QListView of the combobox. <END_TASK> <USER_TASK:> Description: def eventFilter(self, widget, event): """Used to handle key events on the QListView of the combobox."""
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Delete: index = self.view().currentIndex().row() if index >= EXTERNAL_PATHS: # Remove item and update the view. self.removeItem(index) self.showPopup() # Set the view selection so that it doesn't bounce around. new_index = min(self.count() - 1, index) new_index = 0 if new_index < EXTERNAL_PATHS else new_index self.view().setCurrentIndex(self.model().index(new_index, 0)) self.setCurrentIndex(new_index) return True return QComboBox.eventFilter(self, widget, event)
<SYSTEM_TASK:> Searches through the parent tree to see if it is possible to emit the <END_TASK> <USER_TASK:> Description: def __redirect_stdio_emit(self, value): """ Searches through the parent tree to see if it is possible to emit the redirect_stdio signal. This logic allows to test the SearchInComboBox select_directory method outside of the FindInFiles plugin. """
parent = self.parent() while parent is not None: try: parent.redirect_stdio.emit(value) except AttributeError: parent = parent.parent() else: break
<SYSTEM_TASK:> Reimplemented to handle key events <END_TASK> <USER_TASK:> Description: def keyPressEvent(self, event): """Reimplemented to handle key events"""
ctrl = event.modifiers() & Qt.ControlModifier shift = event.modifiers() & Qt.ShiftModifier if event.key() in (Qt.Key_Enter, Qt.Key_Return): self.find.emit() elif event.key() == Qt.Key_F and ctrl and shift: # Toggle find widgets self.parent().toggle_visibility.emit(not self.isVisible()) else: QWidget.keyPressEvent(self, event)
<SYSTEM_TASK:> Enable result sorting after search is complete. <END_TASK> <USER_TASK:> Description: def set_sorting(self, flag): """Enable result sorting after search is complete."""
self.sorting['status'] = flag self.header().setSectionsClickable(flag == ON)
<SYSTEM_TASK:> Override show event to start waiting spinner. <END_TASK> <USER_TASK:> Description: def showEvent(self, event): """Override show event to start waiting spinner."""
QWidget.showEvent(self, event) self.spinner.start()
<SYSTEM_TASK:> Override hide event to stop waiting spinner. <END_TASK> <USER_TASK:> Description: def hideEvent(self, event): """Override hide event to stop waiting spinner."""
QWidget.hideEvent(self, event) self.spinner.stop()
<SYSTEM_TASK:> Stop current search thread and clean-up <END_TASK> <USER_TASK:> Description: def stop_and_reset_thread(self, ignore_results=False): """Stop current search thread and clean-up"""
if self.search_thread is not None: if self.search_thread.isRunning(): if ignore_results: self.search_thread.sig_finished.disconnect( self.search_complete) self.search_thread.stop() self.search_thread.wait() self.search_thread.setParent(None) self.search_thread = None
<SYSTEM_TASK:> Current search thread has finished <END_TASK> <USER_TASK:> Description: def search_complete(self, completed): """Current search thread has finished"""
self.result_browser.set_sorting(ON) self.find_options.ok_button.setEnabled(True) self.find_options.stop_button.setEnabled(False) self.status_bar.hide() self.result_browser.expandAll() if self.search_thread is None: return self.sig_finished.emit() found = self.search_thread.get_results() self.stop_and_reset_thread() if found is not None: results, pathlist, nb, error_flag = found self.result_browser.show()
<SYSTEM_TASK:> Get the stored credentials if any. <END_TASK> <USER_TASK:> Description: def _get_credentials_from_settings(self): """Get the stored credentials if any."""
remember_me = CONF.get('main', 'report_error/remember_me') remember_token = CONF.get('main', 'report_error/remember_token') username = CONF.get('main', 'report_error/username', '') if not remember_me: username = '' return username, remember_me, remember_token
<SYSTEM_TASK:> Store credentials for future use. <END_TASK> <USER_TASK:> Description: def _store_credentials(self, username, password, remember=False): """Store credentials for future use."""
if username and password and remember: CONF.set('main', 'report_error/username', username) try: keyring.set_password('github', username, password) except Exception: if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to store password'), _('It was not possible to securely ' 'save your password. You will be ' 'prompted for your Github ' 'credentials next time you want ' 'to report an issue.')) remember = False CONF.set('main', 'report_error/remember_me', remember)
<SYSTEM_TASK:> Get user credentials with the login dialog. <END_TASK> <USER_TASK:> Description: def get_user_credentials(self): """Get user credentials with the login dialog."""
password = None token = None (username, remember_me, remember_token) = self._get_credentials_from_settings() valid_py_os = not (PY2 and sys.platform.startswith('linux')) if username and remember_me and valid_py_os: # Get password from keyring try: password = keyring.get_password('github', username) except Exception: # No safe keyring backend if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to retrieve password'), _('It was not possible to retrieve ' 'your password. Please introduce ' 'it again.')) if remember_token and valid_py_os: # Get token from keyring try: token = keyring.get_password('github', 'token') except Exception: # No safe keyring backend if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to retrieve token'), _('It was not possible to retrieve ' 'your token. Please introduce it ' 'again.')) if not running_under_pytest(): credentials = DlgGitHubLogin.login(self.parent_widget, username, password, token, remember_me, remember_token) if (credentials['username'] and credentials['password'] and valid_py_os): self._store_credentials(credentials['username'], credentials['password'], credentials['remember']) CONF.set('main', 'report_error/remember_me', credentials['remember']) if credentials['token'] and valid_py_os: self._store_token(credentials['token'], credentials['remember_token']) CONF.set('main', 'report_error/remember_token', credentials['remember_token']) else: return dict(username=username, password=password, token='', remember=remember_me, remember_token=remember_token) return credentials
<SYSTEM_TASK:> Override Qt method to hide the tooltip on leave. <END_TASK> <USER_TASK:> Description: def leaveEvent(self, event): """Override Qt method to hide the tooltip on leave."""
super(ToolTipWidget, self).leaveEvent(event) self.hide()
<SYSTEM_TASK:> Reimplemented to hide on certain key presses and on text edit focus <END_TASK> <USER_TASK:> Description: def eventFilter(self, obj, event): """ Reimplemented to hide on certain key presses and on text edit focus changes. """
if obj == self._text_edit: etype = event.type() if etype == QEvent.KeyPress: key = event.key() cursor = self._text_edit.textCursor() prev_char = self._text_edit.get_character(cursor.position(), offset=-1) if key in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Down, Qt.Key_Up): self.hide() elif key == Qt.Key_Escape: self.hide() return True elif prev_char == ')': self.hide() elif etype == QEvent.FocusOut: self.hide() elif etype == QEvent.Enter: if (self._hide_timer.isActive() and self.app.topLevelAt(QCursor.pos()) == self): self._hide_timer.stop() elif etype == QEvent.Leave: self._leave_event_hide() return super(CallTipWidget, self).eventFilter(obj, event)
<SYSTEM_TASK:> Reimplemented to hide the widget when the hide timer fires. <END_TASK> <USER_TASK:> Description: def timerEvent(self, event): """ Reimplemented to hide the widget when the hide timer fires. """
if event.timerId() == self._hide_timer.timerId(): self._hide_timer.stop() self.hide()
<SYSTEM_TASK:> Reimplemented to cancel the hide timer. <END_TASK> <USER_TASK:> Description: def enterEvent(self, event): """ Reimplemented to cancel the hide timer. """
super(CallTipWidget, self).enterEvent(event) if self.as_tooltip: self.hide() if (self._hide_timer.isActive() and self.app.topLevelAt(QCursor.pos()) == self): self._hide_timer.stop()
<SYSTEM_TASK:> Reimplemented to disconnect signal handlers and event filter. <END_TASK> <USER_TASK:> Description: def hideEvent(self, event): """ Reimplemented to disconnect signal handlers and event filter. """
super(CallTipWidget, self).hideEvent(event) self._text_edit.cursorPositionChanged.disconnect( self._cursor_position_changed) self._text_edit.removeEventFilter(self)
<SYSTEM_TASK:> Reimplemented to start the hide timer. <END_TASK> <USER_TASK:> Description: def leaveEvent(self, event): """ Reimplemented to start the hide timer. """
super(CallTipWidget, self).leaveEvent(event) self._leave_event_hide()
<SYSTEM_TASK:> Reimplemented to connect signal handlers and event filter. <END_TASK> <USER_TASK:> Description: def showEvent(self, event): """ Reimplemented to connect signal handlers and event filter. """
super(CallTipWidget, self).showEvent(event) self._text_edit.cursorPositionChanged.connect( self._cursor_position_changed) self._text_edit.installEventFilter(self)
<SYSTEM_TASK:> Updates the tip based on user cursor movement. <END_TASK> <USER_TASK:> Description: def _cursor_position_changed(self): """ Updates the tip based on user cursor movement. """
cursor = self._text_edit.textCursor() position = cursor.position() document = self._text_edit.document() char = to_text_string(document.characterAt(position - 1)) if position <= self._start_position: self.hide() elif char == ')': pos, _ = self._find_parenthesis(position - 1, forward=False) if pos == -1: self.hide()
<SYSTEM_TASK:> Detect if text has mixed EOL characters <END_TASK> <USER_TASK:> Description: def has_mixed_eol_chars(text): """Detect if text has mixed EOL characters"""
eol_chars = get_eol_chars(text) if eol_chars is None: return False correct_text = eol_chars.join((text+eol_chars).splitlines()) return repr(correct_text) != repr(text)
<SYSTEM_TASK:> Test if passed string is the name of a Python builtin object <END_TASK> <USER_TASK:> Description: def is_builtin(text): """Test if passed string is the name of a Python builtin object"""
from spyder.py3compat import builtins return text in [str(name) for name in dir(builtins) if not name.startswith('_')]
<SYSTEM_TASK:> Get tab title without ambiguation. <END_TASK> <USER_TASK:> Description: def disambiguate_fname(files_path_list, filename): """Get tab title without ambiguation."""
fname = os.path.basename(filename) same_name_files = get_same_name_files(files_path_list, fname) if len(same_name_files) > 1: compare_path = shortest_path(same_name_files) if compare_path == filename: same_name_files.remove(path_components(filename)) compare_path = shortest_path(same_name_files) diff_path = differentiate_prefix(path_components(filename), path_components(compare_path)) diff_path_length = len(diff_path) path_component = path_components(diff_path) if (diff_path_length > 20 and len(path_component) > 2): if path_component[0] != '/' and path_component[0] != '': path_component = [path_component[0], '...', path_component[-1]] else: path_component = [path_component[2], '...', path_component[-1]] diff_path = os.path.join(*path_component) fname = fname + " - " + diff_path return fname
<SYSTEM_TASK:> Get a list of the path components of the files with the same name. <END_TASK> <USER_TASK:> Description: def get_same_name_files(files_path_list, filename): """Get a list of the path components of the files with the same name."""
same_name_files = [] for fname in files_path_list: if filename == os.path.basename(fname): same_name_files.append(path_components(fname)) return same_name_files
<SYSTEM_TASK:> Add text decorations on a CodeEditor instance. <END_TASK> <USER_TASK:> Description: def add(self, decorations): """ Add text decorations on a CodeEditor instance. Don't add duplicated decorations, and order decorations according draw_order and the size of the selection. Args: decorations (sourcecode.api.TextDecoration) (could be a list) Returns: int: Amount of decorations added. """
added = 0 if isinstance(decorations, list): not_repeated = set(decorations) - set(self._decorations) self._decorations.extend(list(not_repeated)) added = len(not_repeated) elif decorations not in self._decorations: self._decorations.append(decorations) added = 1 if added > 0: self._order_decorations() self.update() return added
<SYSTEM_TASK:> Update editor extra selections with added decorations. <END_TASK> <USER_TASK:> Description: def update(self): """Update editor extra selections with added decorations. NOTE: Update TextDecorations to use editor font, using a different font family and point size could cause unwanted behaviors. """
font = self.editor.font() for decoration in self._decorations: try: decoration.format.setFont( font, QTextCharFormat.FontPropertiesSpecifiedOnly) except (TypeError, AttributeError): # Qt < 5.3 decoration.format.setFontFamily(font.family()) decoration.format.setFontPointSize(font.pointSize()) self.editor.setExtraSelections(self._decorations)
<SYSTEM_TASK:> Order decorations according draw_order and size of selection. <END_TASK> <USER_TASK:> Description: def _order_decorations(self): """Order decorations according draw_order and size of selection. Highest draw_order will appear on top of the lowest values. If draw_order is equal,smaller selections are draw in top of bigger selections. """
def order_function(sel): end = sel.cursor.selectionEnd() start = sel.cursor.selectionStart() return sel.draw_order, -(end - start) self._decorations = sorted(self._decorations, key=order_function)
<SYSTEM_TASK:> Get signature from inspect reply content <END_TASK> <USER_TASK:> Description: def get_signature(self, content): """Get signature from inspect reply content"""
data = content.get('data', {}) text = data.get('text/plain', '') if text: text = ANSI_OR_SPECIAL_PATTERN.sub('', text) self._control.current_prompt_pos = self._prompt_pos line = self._control.get_current_line_to_cursor() name = line[:-1].split('(')[-1] # Take last token after a ( name = name.split('.')[-1] # Then take last token after a . # Clean name from invalid chars try: name = self.clean_invalid_var_chars(name).split('_')[-1] except: pass argspec = getargspecfromtext(text) if argspec: # This covers cases like np.abs, whose docstring is # the same as np.absolute and because of that a proper # signature can't be obtained correctly signature = name + argspec else: signature = getsignaturefromtext(text, name) # Remove docstring for uniformity with editor signature = signature.split('Docstring:')[0] return signature else: return ''
<SYSTEM_TASK:> Reimplement call tips to only show signatures, using the same <END_TASK> <USER_TASK:> Description: def _handle_inspect_reply(self, rep): """ Reimplement call tips to only show signatures, using the same style from our Editor and External Console too """
cursor = self._get_cursor() info = self._request_info.get('call_tip') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): content = rep['content'] if content.get('status') == 'ok' and content.get('found', False): signature = self.get_signature(content) if signature: # TODO: Pass the language from the Console to the calltip self._control.show_calltip(signature, color='#999999', is_python=True)
<SYSTEM_TASK:> Call function req and then send its results via ZMQ. <END_TASK> <USER_TASK:> Description: def send_request(req=None, method=None, requires_response=True): """Call function req and then send its results via ZMQ."""
if req is None: return functools.partial(send_request, method=method, requires_response=requires_response) @functools.wraps(req) def wrapper(self, *args, **kwargs): params = req(self, *args, **kwargs) _id = self.send(method, params, requires_response) return _id wrapper._sends = method return wrapper
<SYSTEM_TASK:> Decide if showing a warning when the user is trying to view <END_TASK> <USER_TASK:> Description: def show_warning(self, index): """ Decide if showing a warning when the user is trying to view a big variable associated to a Tablemodel index This avoids getting the variables' value to know its size and type, using instead those already computed by the TableModel. The problem is when a variable is too big, it can take a lot of time just to get its value """
try: val_size = index.model().sizes[index.row()] val_type = index.model().types[index.row()] except: return False if val_type in ['list', 'set', 'tuple', 'dict'] and \ int(val_size) > 1e5: return True else: return False
<SYSTEM_TASK:> Allow user to drop supported files <END_TASK> <USER_TASK:> Description: def dropEvent(self, event): """Allow user to drop supported files"""
urls = mimedata2url(event.mimeData()) if urls: event.setDropAction(Qt.CopyAction) event.accept() self.sig_files_dropped.emit(urls) else: event.ignore()
<SYSTEM_TASK:> Return True if variable is a list or a tuple <END_TASK> <USER_TASK:> Description: def is_list(self, key): """Return True if variable is a list or a tuple"""
data = self.model.get_data() return isinstance(data[key], (tuple, list))
<SYSTEM_TASK:> Return True if variable is a set <END_TASK> <USER_TASK:> Description: def is_set(self, key): """Return True if variable is a set"""
data = self.model.get_data() return isinstance(data[key], set)
<SYSTEM_TASK:> Return True if variable is a numpy array <END_TASK> <USER_TASK:> Description: def is_array(self, key): """Return True if variable is a numpy array"""
data = self.model.get_data() return isinstance(data[key], (ndarray, MaskedArray))
<SYSTEM_TASK:> Return True if variable is a dictionary <END_TASK> <USER_TASK:> Description: def is_dict(self, key): """Return True if variable is a dictionary"""
data = self.model.get_data() return isinstance(data[key], dict)
<SYSTEM_TASK:> Setup editor. <END_TASK> <USER_TASK:> Description: def setup(self, data, title='', readonly=False, width=650, remote=False, icon=None, parent=None): """Setup editor."""
if isinstance(data, (dict, set)): # dictionnary, set self.data_copy = data.copy() datalen = len(data) elif isinstance(data, (tuple, list)): # list, tuple self.data_copy = data[:] datalen = len(data) else: # unknown object import copy try: self.data_copy = copy.deepcopy(data) except NotImplementedError: self.data_copy = copy.copy(data) except (TypeError, AttributeError): readonly = True self.data_copy = data datalen = len(get_object_attrs(data)) # If the copy has a different type, then do not allow editing, because # this would change the type after saving; cf. issue #6936 if type(self.data_copy) != type(data): readonly = True self.widget = CollectionsEditorWidget(self, self.data_copy, title=title, readonly=readonly, remote=remote) self.widget.editor.model.sig_setting_data.connect( self.save_and_close_enable) layout = QVBoxLayout() layout.addWidget(self.widget) self.setLayout(layout) # Buttons configuration btn_layout = QHBoxLayout() btn_layout.addStretch() if not readonly: self.btn_save_and_close = QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) layout.addLayout(btn_layout) constant = 121 row_height = 30 error_margin = 10 height = constant + row_height * min([10, datalen]) + error_margin self.resize(width, height) self.setWindowTitle(self.widget.get_title()) if icon is None: self.setWindowIcon(ima.icon('dictedit')) if sys.platform == 'darwin': # See: https://github.com/spyder-ide/spyder/issues/9051 self.setWindowFlags(Qt.Tool) else: # Make the dialog act as a window self.setWindowFlags(Qt.Window)
<SYSTEM_TASK:> Remove stderr_file associated with the client. <END_TASK> <USER_TASK:> Description: def remove_stderr_file(self): """Remove stderr_file associated with the client."""
try: # Defer closing the stderr_handle until the client # is closed because jupyter_client needs it open # while it tries to restart the kernel self.stderr_handle.close() os.remove(self.stderr_file) except Exception: pass
<SYSTEM_TASK:> Configure shellwidget after kernel is started <END_TASK> <USER_TASK:> Description: def configure_shellwidget(self, give_focus=True): """Configure shellwidget after kernel is started"""
if give_focus: self.get_control().setFocus() # Set exit callback self.shellwidget.set_exit_callback() # To save history self.shellwidget.executing.connect(self.add_to_history) # For Mayavi to run correctly self.shellwidget.executing.connect( self.shellwidget.set_backend_for_mayavi) # To update history after execution self.shellwidget.executed.connect(self.update_history) # To update the Variable Explorer after execution self.shellwidget.executed.connect( self.shellwidget.refresh_namespacebrowser) # To enable the stop button when executing a process self.shellwidget.executing.connect(self.enable_stop_button) # To disable the stop button after execution stopped self.shellwidget.executed.connect(self.disable_stop_button) # To show kernel restarted/died messages self.shellwidget.sig_kernel_restarted.connect( self.kernel_restarted_message) # To correctly change Matplotlib backend interactively self.shellwidget.executing.connect( self.shellwidget.change_mpl_backend) # To show env and sys.path contents self.shellwidget.sig_show_syspath.connect(self.show_syspath) self.shellwidget.sig_show_env.connect(self.show_env) # To sync with working directory toolbar self.shellwidget.executed.connect(self.shellwidget.get_cwd) # To apply style self.set_color_scheme(self.shellwidget.syntax_style, reset=False) # To hide the loading page self.shellwidget.sig_prompt_ready.connect(self._hide_loading_page) # Show possible errors when setting Matplotlib backend self.shellwidget.sig_prompt_ready.connect( self._show_mpl_backend_errors)
<SYSTEM_TASK:> Method to handle what to do when the stop button is pressed <END_TASK> <USER_TASK:> Description: def stop_button_click_handler(self): """Method to handle what to do when the stop button is pressed"""
self.stop_button.setDisabled(True) # Interrupt computations or stop debugging if not self.shellwidget._reading: self.interrupt_kernel() else: self.shellwidget.write_to_stdin('exit')
<SYSTEM_TASK:> Add actions to IPython widget context menu <END_TASK> <USER_TASK:> Description: def add_actions_to_context_menu(self, menu): """Add actions to IPython widget context menu"""
inspect_action = create_action(self, _("Inspect current object"), QKeySequence(get_shortcut('console', 'inspect current object')), icon=ima.icon('MessageBoxInformation'), triggered=self.inspect_object) clear_line_action = create_action(self, _("Clear line or block"), QKeySequence(get_shortcut( 'console', 'clear line')), triggered=self.clear_line) reset_namespace_action = create_action(self, _("Remove all variables"), QKeySequence(get_shortcut( 'ipython_console', 'reset namespace')), icon=ima.icon('editdelete'), triggered=self.reset_namespace) clear_console_action = create_action(self, _("Clear console"), QKeySequence(get_shortcut('console', 'clear shell')), triggered=self.clear_console) quit_action = create_action(self, _("&Quit"), icon=ima.icon('exit'), triggered=self.exit_callback) add_actions(menu, (None, inspect_action, clear_line_action, clear_console_action, reset_namespace_action, None, quit_action)) return menu
<SYSTEM_TASK:> Restart the associated kernel. <END_TASK> <USER_TASK:> Description: def restart_kernel(self): """ Restart the associated kernel. Took this code from the qtconsole project Licensed under the BSD license """
sw = self.shellwidget if not running_under_pytest() and self.ask_before_restart: message = _('Are you sure you want to restart the kernel?') buttons = QMessageBox.Yes | QMessageBox.No result = QMessageBox.question(self, _('Restart kernel?'), message, buttons) else: result = None if (result == QMessageBox.Yes or running_under_pytest() or not self.ask_before_restart): if sw.kernel_manager: if self.infowidget.isVisible(): self.infowidget.hide() sw.show() try: sw.kernel_manager.restart_kernel( stderr=self.stderr_handle) except RuntimeError as e: sw._append_plain_text( _('Error restarting kernel: %s\n') % e, before_prompt=True ) else: # For issue 6235. IPython was changing the setting of # %colors on windows by assuming it was using a dark # background. This corrects it based on the scheme. self.set_color_scheme(sw.syntax_style) sw._append_html(_("<br>Restarting kernel...\n<hr><br>"), before_prompt=False) else: sw._append_plain_text( _('Cannot restart a kernel not started by Spyder\n'), before_prompt=True )
<SYSTEM_TASK:> Resets the namespace by removing all names defined by the user <END_TASK> <USER_TASK:> Description: def reset_namespace(self): """Resets the namespace by removing all names defined by the user"""
self.shellwidget.reset_namespace(warning=self.reset_warning, message=True)
<SYSTEM_TASK:> Show environment variables. <END_TASK> <USER_TASK:> Description: def show_env(self, env): """Show environment variables."""
self.dialog_manager.show(RemoteEnvDialog(env, parent=self))
<SYSTEM_TASK:> Show animation while the kernel is loading. <END_TASK> <USER_TASK:> Description: def _show_loading_page(self): """Show animation while the kernel is loading."""
self.shellwidget.hide() self.infowidget.show() self.info_page = self.loading_page self.set_info_page()
<SYSTEM_TASK:> Hide animation shown while the kernel is loading. <END_TASK> <USER_TASK:> Description: def _hide_loading_page(self): """Hide animation shown while the kernel is loading."""
self.infowidget.hide() self.shellwidget.show() self.info_page = self.blank_page self.set_info_page() self.shellwidget.sig_prompt_ready.disconnect(self._hide_loading_page)
<SYSTEM_TASK:> Show possible errors when setting the selected Matplotlib backend. <END_TASK> <USER_TASK:> Description: def _show_mpl_backend_errors(self): """ Show possible errors when setting the selected Matplotlib backend. """
if not self.external_kernel: self.shellwidget.silent_execute( "get_ipython().kernel._show_mpl_backend_errors()") self.shellwidget.sig_prompt_ready.disconnect( self._show_mpl_backend_errors)
<SYSTEM_TASK:> Create HTML template for signature. <END_TASK> <USER_TASK:> Description: def _format_signature(self, signature, doc='', parameter='', parameter_doc='', color=_DEFAULT_TITLE_COLOR, is_python=False): """ Create HTML template for signature. This template will include indent after the method name, a highlight color for the active parameter and highlights for special chars. """
active_parameter_template = ( '<span style=\'font-family:"{font_family}";' 'font-size:{font_size}pt;' 'color:{color}\'>' '<b>{parameter}</b>' '</span>' ) chars_template = ( '<span style="color:{0};'.format(self._CHAR_HIGHLIGHT_COLOR) + 'font-weight:bold">{char}' '</span>' ) def handle_sub(matchobj): """ Handle substitution of active parameter template. This ensures the correct highlight of the active parameter. """ match = matchobj.group(0) new = match.replace(parameter, active_parameter_template) return new # Remove duplicate spaces signature = ' '.join(signature.split()) # Replace ay initial spaces signature = signature.replace('( ', '(') # Process signature template pattern = r'[\*|(|\s](' + parameter + r')[,|)|\s|=]' formatted_lines = [] name = signature.split('(')[0] indent = ' ' * (len(name) + 1) rows = textwrap.wrap(signature, width=60, subsequent_indent=indent) for row in rows: # Add template to highlight the active parameter row = re.sub(pattern, handle_sub, row) row = row.replace(' ', '&nbsp;') row = row.replace('span&nbsp;', 'span ') if is_python: for char in ['(', ')', ',', '*', '**']: new_char = chars_template.format(char=char) row = row.replace(char, new_char) formatted_lines.append(row) title_template = '<br>'.join(formatted_lines) # Get current font properties font = self.font() font_size = font.pointSize() font_family = font.family() # Format title to display active parameter title = title_template.format( font_size=font_size, font_family=font_family, color=self._PARAMETER_HIGHLIGHT_COLOR, parameter=parameter, ) # Process documentation # TODO: To be included in a separate PR # active = active_parameter_template.format( # font_size=font_size, # font_family=font_family, # color=self._PARAMETER_HIGHLIGHT_COLOR, # parameter=parameter, # ) # if doc is not None and len(doc) > 0: # text_doc = doc.split('\n')[0] # else: # text_doc = '' # if parameter_doc is not None and len(parameter_doc) > 0: # text_prefix = text_doc + '<br><hr><br>param: ' + active # text = parameter_doc # else: # text_prefix = '' # text = '' # formatted_lines = [] # rows = textwrap.wrap(text, width=60) # for row in rows: # row = row.replace(' ', '&nbsp;') # if text_prefix: # text = text_prefix + '<br><br>' + '<br>'.join(rows) # else: # text = '<br>'.join(rows) # text += '<br>' # Format text tiptext = self._format_text(title, '', color) return tiptext, rows
<SYSTEM_TASK:> Show calltip. <END_TASK> <USER_TASK:> Description: def show_calltip(self, signature, doc='', parameter='', parameter_doc='', color=_DEFAULT_TITLE_COLOR, is_python=False): """ Show calltip. Calltips look like tooltips but will not disappear if mouse hovers them. They are useful for displaying signature information on methods and functions. """
# Find position of calltip point = self._calculate_position() # Format text tiptext, wrapped_lines = self._format_signature( signature, doc, parameter, parameter_doc, color, is_python, ) self._update_stylesheet(self.calltip_widget) # Show calltip self.calltip_widget.show_tip(point, tiptext, wrapped_lines)
<SYSTEM_TASK:> Show tooltip. <END_TASK> <USER_TASK:> Description: def show_tooltip(self, title, text, color=_DEFAULT_TITLE_COLOR, at_line=None, at_position=None, at_point=None): """ Show tooltip. Tooltips will disappear if mouse hovers them. They are meant for quick inspections. """
if text is not None and len(text) != 0: # Find position of calltip point = self._calculate_position( at_line=at_line, at_position=at_position, at_point=at_point, ) # Format text tiptext = self._format_text(title, text, color, ellide=True) self._update_stylesheet(self.tooltip_widget) # Display tooltip self.tooltip_widget.show_tip(point, tiptext) self.tooltip_widget.show()
<SYSTEM_TASK:> Get offset in character for the given subject from the start of <END_TASK> <USER_TASK:> Description: def get_position(self, subject): """Get offset in character for the given subject from the start of text edit area"""
cursor = self.textCursor() if subject == 'cursor': pass elif subject == 'sol': cursor.movePosition(QTextCursor.StartOfBlock) elif subject == 'eol': cursor.movePosition(QTextCursor.EndOfBlock) elif subject == 'eof': cursor.movePosition(QTextCursor.End) elif subject == 'sof': cursor.movePosition(QTextCursor.Start) else: # Assuming that input argument was already a position return subject return cursor.position()
<SYSTEM_TASK:> Return True if cursor is on the first line <END_TASK> <USER_TASK:> Description: def is_cursor_on_first_line(self): """Return True if cursor is on the first line"""
cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) return cursor.atStart()
<SYSTEM_TASK:> Return True if cursor is on the last line <END_TASK> <USER_TASK:> Description: def is_cursor_on_last_line(self): """Return True if cursor is on the last line"""
cursor = self.textCursor() cursor.movePosition(QTextCursor.EndOfBlock) return cursor.atEnd()
<SYSTEM_TASK:> Return current word, i.e. word at cursor position, <END_TASK> <USER_TASK:> Description: def get_current_word_and_position(self, completion=False): """Return current word, i.e. word at cursor position, and the start position"""
cursor = self.textCursor() if cursor.hasSelection(): # Removes the selection and moves the cursor to the left side # of the selection: this is required to be able to properly # select the whole word under cursor (otherwise, the same word is # not selected when the cursor is at the right side of it): cursor.setPosition(min([cursor.selectionStart(), cursor.selectionEnd()])) else: # Checks if the first character to the right is a white space # and if not, moves the cursor one word to the left (otherwise, # if the character to the left do not match the "word regexp" # (see below), the word to the left of the cursor won't be # selected), but only if the first character to the left is not a # white space too. def is_space(move): curs = self.textCursor() curs.movePosition(move, QTextCursor.KeepAnchor) return not to_text_string(curs.selectedText()).strip() if not completion: if is_space(QTextCursor.NextCharacter): if is_space(QTextCursor.PreviousCharacter): return cursor.movePosition(QTextCursor.WordLeft) else: def is_special_character(move): curs = self.textCursor() curs.movePosition(move, QTextCursor.KeepAnchor) text_cursor = to_text_string(curs.selectedText()).strip() return len(re.findall(r'([^\d\W]\w*)', text_cursor, re.UNICODE)) == 0 if is_space(QTextCursor.PreviousCharacter): return if (is_special_character(QTextCursor.NextCharacter)): cursor.movePosition(QTextCursor.WordLeft) cursor.select(QTextCursor.WordUnderCursor) text = to_text_string(cursor.selectedText()) # find a valid python variable name match = re.findall(r'([^\d\W]\w*)', text, re.UNICODE) if match: return match[0], cursor.selectionStart()
<SYSTEM_TASK:> Return current word, i.e. word at cursor position <END_TASK> <USER_TASK:> Description: def get_current_word(self, completion=False): """Return current word, i.e. word at cursor position"""
ret = self.get_current_word_and_position(completion) if ret is not None: return ret[0]
<SYSTEM_TASK:> Return text selected by current text cursor, converted in unicode <END_TASK> <USER_TASK:> Description: def get_selected_text(self): """ Return text selected by current text cursor, converted in unicode Replace the unicode line separator character \u2029 by the line separator characters returned by get_line_separator """
return to_text_string(self.textCursor().selectedText()).replace(u"\u2029", self.get_line_separator())
<SYSTEM_TASK:> Get the number of matches for the searched text. <END_TASK> <USER_TASK:> Description: def get_number_matches(self, pattern, source_text='', case=False, regexp=False): """Get the number of matches for the searched text."""
pattern = to_text_string(pattern) if not pattern: return 0 if not regexp: pattern = re.escape(pattern) if not source_text: source_text = to_text_string(self.toPlainText()) try: if case: regobj = re.compile(pattern) else: regobj = re.compile(pattern, re.IGNORECASE) except sre_constants.error: return None number_matches = 0 for match in regobj.finditer(source_text): number_matches += 1 return number_matches
<SYSTEM_TASK:> Get number of the match for the searched text. <END_TASK> <USER_TASK:> Description: def get_match_number(self, pattern, case=False, regexp=False): """Get number of the match for the searched text."""
position = self.textCursor().position() source_text = self.get_text(position_from='sof', position_to=position) match_number = self.get_number_matches(pattern, source_text=source_text, case=case, regexp=regexp) return match_number
<SYSTEM_TASK:> Show Pointing Hand Cursor on error messages <END_TASK> <USER_TASK:> Description: def mouseMoveEvent(self, event): """Show Pointing Hand Cursor on error messages"""
text = self.get_line_at(event.pos()) if get_error_match(text): if not self.__cursor_changed: QApplication.setOverrideCursor(QCursor(Qt.PointingHandCursor)) self.__cursor_changed = True event.accept() return if self.__cursor_changed: QApplication.restoreOverrideCursor() self.__cursor_changed = False self.QT_CLASS.mouseMoveEvent(self, event)
<SYSTEM_TASK:> If cursor has not been restored yet, do it now <END_TASK> <USER_TASK:> Description: def leaveEvent(self, event): """If cursor has not been restored yet, do it now"""
if self.__cursor_changed: QApplication.restoreOverrideCursor() self.__cursor_changed = False self.QT_CLASS.leaveEvent(self, event)
<SYSTEM_TASK:> Return a QKeySequence representation of the provided QKeyEvent. <END_TASK> <USER_TASK:> Description: def keyevent_to_keyseq(self, event): """Return a QKeySequence representation of the provided QKeyEvent."""
self.keyPressEvent(event) event.accept() return self.keySequence()
<SYSTEM_TASK:> Check if the first sub-sequence of the new key sequence is valid. <END_TASK> <USER_TASK:> Description: def check_singlekey(self): """Check if the first sub-sequence of the new key sequence is valid."""
if len(self._qsequences) == 0: return True else: keystr = self._qsequences[0] valid_single_keys = (EDITOR_SINGLE_KEYS if self.context == 'editor' else SINGLE_KEYS) if any((m in keystr for m in ('Ctrl', 'Alt', 'Shift', 'Meta'))): return True else: # This means that the the first subsequence is composed of # a single key with no modifier. valid_single_keys = (EDITOR_SINGLE_KEYS if self.context == 'editor' else SINGLE_KEYS) if any((k == keystr for k in valid_single_keys)): return True else: return False
<SYSTEM_TASK:> Update the warning label, buttons state and sequence text. <END_TASK> <USER_TASK:> Description: def update_warning(self): """Update the warning label, buttons state and sequence text."""
new_qsequence = self.new_qsequence new_sequence = self.new_sequence self.text_new_sequence.setText( new_qsequence.toString(QKeySequence.NativeText)) conflicts = self.check_conflicts() if len(self._qsequences) == 0: warning = SEQUENCE_EMPTY tip = '' icon = QIcon() elif conflicts: warning = SEQUENCE_CONFLICT template = '<i>{0}<b>{1}</b>{2}</i>' tip_title = _('The new shortcut conflicts with:') + '<br>' tip_body = '' for s in conflicts: tip_body += ' - {0}: {1}<br>'.format(s.context, s.name) tip_body = tip_body[:-4] # Removing last <br> tip_override = '<br>Press <b>OK</b> to unbind ' tip_override += 'it' if len(conflicts) == 1 else 'them' tip_override += ' and assign it to <b>{}</b>'.format(self.name) tip = template.format(tip_title, tip_body, tip_override) icon = get_std_icon('MessageBoxWarning') elif new_sequence in BLACKLIST: warning = IN_BLACKLIST template = '<i>{0}<b>{1}</b></i>' tip_title = _('Forbidden key sequence!') + '<br>' tip_body = '' use = BLACKLIST[new_sequence] if use is not None: tip_body = use tip = template.format(tip_title, tip_body) icon = get_std_icon('MessageBoxWarning') elif self.check_singlekey() is False or self.check_ascii() is False: warning = INVALID_KEY template = '<i>{0}</i>' tip = _('Invalid key sequence entered') + '<br>' icon = get_std_icon('MessageBoxWarning') else: warning = NO_WARNING tip = 'This shortcut is valid.' icon = get_std_icon('DialogApplyButton') self.warning = warning self.conflicts = conflicts self.helper_button.setIcon(icon) self.button_ok.setEnabled( self.warning in [NO_WARNING, SEQUENCE_CONFLICT]) self.label_warning.setText(tip) # Everytime after update warning message, update the label height new_height = self.label_warning.sizeHint().height() self.label_warning.setMaximumHeight(new_height)
<SYSTEM_TASK:> This is a convenience method to set the new QKeySequence of the <END_TASK> <USER_TASK:> Description: def set_sequence_from_str(self, sequence): """ This is a convenience method to set the new QKeySequence of the shortcut editor from a string. """
self._qsequences = [QKeySequence(s) for s in sequence.split(', ')] self.update_warning()
<SYSTEM_TASK:> Set the new sequence to the default value defined in the config. <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Unbind all conflicted shortcuts, and accept the new one <END_TASK> <USER_TASK:> Description: def accept_override(self): """Unbind all conflicted shortcuts, and accept the new one"""
conflicts = self.check_conflicts() if conflicts: for shortcut in conflicts: shortcut.key = '' self.accept()
<SYSTEM_TASK:> Get the currently selected index in the parent table view. <END_TASK> <USER_TASK:> Description: def current_index(self): """Get the currently selected index in the parent table view."""
i = self._parent.proxy_model.mapToSource(self._parent.currentIndex()) return i
<SYSTEM_TASK:> Update search letters with text input in search box. <END_TASK> <USER_TASK:> Description: def update_search_letters(self, text): """Update search letters with text input in search box."""
self.letters = text names = [shortcut.name for shortcut in self.shortcuts] results = get_search_scores(text, names, template='<b>{0}</b>') self.normal_text, self.rich_text, self.scores = zip(*results) self.reset()
<SYSTEM_TASK:> Set regular expression for filter. <END_TASK> <USER_TASK:> Description: def set_filter(self, text): """Set regular expression for filter."""
self.pattern = get_search_regex(text) if self.pattern: self._parent.setSortingEnabled(False) else: self._parent.setSortingEnabled(True) self.invalidateFilter()