sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def delete(self): """ Deletes the selected items. """ urls = self.selected_urls() rep = QtWidgets.QMessageBox.question( self.tree_view, _('Confirm delete'), _('Are you sure about deleting the selected files/directories?'), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes) if rep == QtWidgets.QMessageBox.Yes: deleted_files = [] for fn in urls: try: if os.path.isfile(fn): os.remove(fn) deleted_files.append(fn) else: files = self._get_files(fn) shutil.rmtree(fn) deleted_files += files except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Delete failed'), _('Failed to remove "%s".\n\n%s') % (fn, str(e))) _logger().exception('failed to remove %s', fn) self.tree_view.files_deleted.emit(deleted_files) for d in deleted_files: debug('%s removed', d) self.tree_view.file_deleted.emit(os.path.normpath(d))
Deletes the selected items.
entailment
def get_current_path(self): """ Gets the path of the currently selected item. """ path = self.tree_view.fileInfo( self.tree_view.currentIndex()).filePath() # https://github.com/pyQode/pyQode/issues/6 if not path: path = self.tree_view.root_path return path
Gets the path of the currently selected item.
entailment
def copy_path_to_clipboard(self): """ Copies the file path to the clipboard """ path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug('path copied: %s' % path)
Copies the file path to the clipboard
entailment
def rename(self): """ Renames the selected item in the tree view """ src = self.get_current_path() pardir, name = os.path.split(src) new_name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Rename '), _('New name:'), QtWidgets.QLineEdit.Normal, name) if status: dest = os.path.join(pardir, new_name) old_files = [] if os.path.isdir(src): old_files = self._get_files(src) else: old_files = [src] try: os.rename(src, dest) except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Rename failed'), _('Failed to rename "%s" into "%s".\n\n%s') % (src, dest, str(e))) else: if os.path.isdir(dest): new_files = self._get_files(dest) else: new_files = [dest] self.tree_view.file_renamed.emit(os.path.normpath(src), os.path.normpath(dest)) renamed_files = [] for old_f, new_f in zip(old_files, new_files): self.tree_view.file_renamed.emit(old_f, new_f) renamed_files.append((old_f, new_f)) # emit all changes in one go self.tree_view.files_renamed.emit(renamed_files)
Renames the selected item in the tree view
entailment
def create_directory(self): """ Creates a directory under the selected directory (if the selected item is a file, the parent directory is used). """ src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create directory'), _('Name:'), QtWidgets.QLineEdit.Normal, '') if status: fatal_names = ['.', '..'] for i in fatal_names: if i == name: QtWidgets.QMessageBox.critical( self.tree_view, _("Error"), _("Wrong directory name")) return if os.path.isfile(src): src = os.path.dirname(src) dir_name = os.path.join(src, name) try: os.makedirs(dir_name, exist_ok=True) except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Failed to create directory'), _('Failed to create directory: "%s".\n\n%s') % (dir_name, str(e)))
Creates a directory under the selected directory (if the selected item is a file, the parent directory is used).
entailment
def create_file(self): """ Creates a file under the current directory. """ src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create new file'), _('File name:'), QtWidgets.QLineEdit.Normal, '') if status: fatal_names = ['.', '..', os.sep] for i in fatal_names: if i == name: QtWidgets.QMessageBox.critical( self.tree_view, _("Error"), _("Wrong directory name")) return if os.path.isfile(src): src = os.path.dirname(src) path = os.path.join(src, name) try: with open(path, 'w'): pass except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Failed to create new file'), _('Failed to create file: "%s".\n\n%s') % (path, str(e))) else: self.tree_view.file_created.emit(os.path.normpath(path))
Creates a file under the current directory.
entailment
def get_mimetype(path): """ Guesses the mime type of a file. If mime type cannot be detected, plain text is assumed. :param path: path of the file :return: the corresponding mime type. """ filename = os.path.split(path)[1] mimetype = mimetypes.guess_type(filename)[0] if mimetype is None: mimetype = 'text/x-plain' _logger().debug('mimetype detected: %s', mimetype) return mimetype
Guesses the mime type of a file. If mime type cannot be detected, plain text is assumed. :param path: path of the file :return: the corresponding mime type.
entailment
def open(self, path, encoding=None, use_cached_encoding=True): """ Open a file and set its content on the editor widget. pyqode does not try to guess encoding. It's up to the client code to handle encodings. You can either use a charset detector to detect encoding or rely on a settings in your application. It is also up to you to handle UnicodeDecodeError, unless you've added class:`pyqode.core.panels.EncodingPanel` on the editor. pyqode automatically caches file encoding that you can later reuse it automatically. :param path: Path of the file to open. :param encoding: Default file encoding. Default is to use the locale encoding. :param use_cached_encoding: True to use the cached encoding instead of ``encoding``. Set it to True if you want to force reload with a new encoding. :raises: UnicodeDecodeError in case of error if no EncodingPanel were set on the editor. """ ret_val = False if encoding is None: encoding = locale.getpreferredencoding() self.opening = True settings = Cache() self._path = path # get encoding from cache if use_cached_encoding: try: cached_encoding = settings.get_file_encoding( path, preferred_encoding=encoding) except KeyError: pass else: encoding = cached_encoding enable_modes = os.path.getsize(path) < self._limit for m in self.editor.modes: if m.enabled: m.enabled = enable_modes # open file and get its content try: with open(path, 'Ur', encoding=encoding) as file: content = file.read() if self.autodetect_eol: self._eol = file.newlines if isinstance(self._eol, tuple): self._eol = self._eol[0] if self._eol is None: # empty file has no newlines self._eol = self.EOL.string(self.preferred_eol) else: self._eol = self.EOL.string(self.preferred_eol) except (UnicodeDecodeError, UnicodeError) as e: try: from pyqode.core.panels import EncodingPanel panel = self.editor.panels.get(EncodingPanel) except KeyError: raise e # panel not found, not automatic error management else: panel.on_open_failed(path, encoding) else: # success! Cache the encoding settings.set_file_encoding(path, encoding) self._encoding = encoding # replace tabs by spaces if self.replace_tabs_by_spaces: content = content.replace("\t", " " * self.editor.tab_length) # set plain text self.editor.setPlainText( content, self.get_mimetype(path), self.encoding) self.editor.setDocumentTitle(self.editor.file.name) ret_val = True _logger().debug('file open: %s', path) self.opening = False if self.restore_cursor: self._restore_cached_pos() self._check_for_readonly() return ret_val
Open a file and set its content on the editor widget. pyqode does not try to guess encoding. It's up to the client code to handle encodings. You can either use a charset detector to detect encoding or rely on a settings in your application. It is also up to you to handle UnicodeDecodeError, unless you've added class:`pyqode.core.panels.EncodingPanel` on the editor. pyqode automatically caches file encoding that you can later reuse it automatically. :param path: Path of the file to open. :param encoding: Default file encoding. Default is to use the locale encoding. :param use_cached_encoding: True to use the cached encoding instead of ``encoding``. Set it to True if you want to force reload with a new encoding. :raises: UnicodeDecodeError in case of error if no EncodingPanel were set on the editor.
entailment
def reload(self, encoding): """ Reload the file with another encoding. :param encoding: the new encoding to use to reload the file. """ assert os.path.exists(self.path) self.open(self.path, encoding=encoding, use_cached_encoding=False)
Reload the file with another encoding. :param encoding: the new encoding to use to reload the file.
entailment
def save(self, path=None, encoding=None, fallback_encoding=None): """ Save the editor content to a file. :param path: optional file path. Set it to None to save using the current path (save), set a new path to save as. :param encoding: optional encoding, will use the current file encoding if None. :param fallback_encoding: Fallback encoding to use in case of encoding error. None to use the locale preferred encoding """ if not self.editor.dirty and \ (encoding is None and encoding == self.encoding) and \ (path is None and path == self.path): # avoid saving if editor not dirty or if encoding or path did not # change return if fallback_encoding is None: fallback_encoding = locale.getpreferredencoding() _logger().log( 5, "saving %r with %r encoding", path, encoding) if path is None: if self.path: path = self.path else: _logger().debug( 'failed to save file, path argument cannot be None if ' 'FileManager.path is also None') return False # use cached encoding if None were specified if encoding is None: encoding = self._encoding self.saving = True self.editor.text_saving.emit(str(path)) # get file persmission on linux try: st_mode = os.stat(path).st_mode except (ImportError, TypeError, AttributeError, OSError): st_mode = None # perform a safe save: we first save to a temporary file, if the save # succeeded we just rename the temporary file to the final file name # and remove it. if self.safe_save: tmp_path = path + '~' else: tmp_path = path try: with open(tmp_path, 'wb') as file: file.write(self._get_text(encoding)) except UnicodeEncodeError: # fallback to utf-8 in case of error. with open(tmp_path, 'wb') as file: file.write(self._get_text(fallback_encoding)) except (IOError, OSError) as e: self._rm(tmp_path) self.saving = False self.editor.text_saved.emit(str(path)) raise e # cache update encoding Cache().set_file_encoding(path, encoding) self._encoding = encoding # remove path and rename temp file, if safe save is on if self.safe_save: self._rm(path) os.rename(tmp_path, path) self._rm(tmp_path) # reset dirty flags self.editor.document().setModified(False) # remember path for next save self._path = os.path.normpath(path) self.editor.text_saved.emit(str(path)) self.saving = False _logger().debug('file saved: %s', path) self._check_for_readonly() # restore file permission if st_mode: try: os.chmod(path, st_mode) except (ImportError, TypeError, AttributeError): pass
Save the editor content to a file. :param path: optional file path. Set it to None to save using the current path (save), set a new path to save as. :param encoding: optional encoding, will use the current file encoding if None. :param fallback_encoding: Fallback encoding to use in case of encoding error. None to use the locale preferred encoding
entailment
def close(self, clear=True): """ Close the file open in the editor: - clear editor content - reset file attributes to their default values :param clear: True to clear the editor content. Default is True. """ Cache().set_cursor_position( self.path, self.editor.textCursor().position()) self.editor._original_text = '' if clear: self.editor.clear() self._path = '' self.mimetype = '' self._encoding = locale.getpreferredencoding()
Close the file open in the editor: - clear editor content - reset file attributes to their default values :param clear: True to clear the editor content. Default is True.
entailment
def on_state_changed(self, state): """ Connects/Disconnects to the painted event of the editor :param state: Enable state """ if state: self.editor.painted.connect(self._paint_margin) self.editor.repaint() else: self.editor.painted.disconnect(self._paint_margin) self.editor.repaint()
Connects/Disconnects to the painted event of the editor :param state: Enable state
entailment
def _paint_margin(self, event): """ Paints the right margin after editor paint event. """ font = QtGui.QFont(self.editor.font_name, self.editor.font_size + self.editor.zoom_level) metrics = QtGui.QFontMetricsF(font) pos = self._margin_pos offset = self.editor.contentOffset().x() + \ self.editor.document().documentMargin() x80 = round(metrics.width(' ') * pos) + offset painter = QtGui.QPainter(self.editor.viewport()) painter.setPen(self._pen) painter.drawLine(x80, 0, x80, 2 ** 16)
Paints the right margin after editor paint event.
entailment
def _update_mtime(self): """ Updates modif time """ try: self._mtime = os.path.getmtime(self.editor.file.path) except OSError: # file_path does not exists. self._mtime = 0 self._timer.stop() except (TypeError, AttributeError): # file path is none, this happen if you use setPlainText instead of # openFile. This is perfectly fine, we just do not have anything to # watch try: self._timer.stop() except AttributeError: pass
Updates modif time
entailment
def _check_file(self): """ Checks watched file moficiation time and permission changes. """ try: self.editor.toPlainText() except RuntimeError: self._timer.stop() return if self.editor and self.editor.file.path: if not os.path.exists(self.editor.file.path) and self._mtime: self._notify_deleted_file() else: mtime = os.path.getmtime(self.editor.file.path) if mtime > self._mtime: self._mtime = mtime self._notify_change() # check for permission change writeable = os.access(self.editor.file.path, os.W_OK) self.editor.setReadOnly(not writeable)
Checks watched file moficiation time and permission changes.
entailment
def _notify(self, title, message, expected_action=None): """ Notify user from external event """ if self.editor is None: return inital_value = self.editor.save_on_focus_out self.editor.save_on_focus_out = False self._flg_notify = True dlg_type = (QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) expected_action = ( lambda *x: None) if not expected_action else expected_action if (self._auto_reload or QtWidgets.QMessageBox.question( self.editor, title, message, dlg_type, QtWidgets.QMessageBox.Yes) == QtWidgets.QMessageBox.Yes): expected_action(self.editor.file.path) self._update_mtime() self.editor.save_on_focus_out = inital_value
Notify user from external event
entailment
def _notify_change(self): """ Notify user from external change if autoReloadChangedFiles is False then reload the changed file in the editor """ def inner_action(*args): """ Inner action: open file """ # cache cursor position before reloading so that the cursor # position is restored automatically after reload has finished. # See OpenCobolIDE/OpenCobolIDE#97 Cache().set_cursor_position( self.editor.file.path, self.editor.textCursor().position()) if os.path.exists(self.editor.file.path): self.editor.file.open(self.editor.file.path) self.file_reloaded.emit() else: # file moved just after a change, see OpenCobolIDE/OpenCobolIDE#337 self._notify_deleted_file() args = (_("File changed"), _("The file <i>%s</i> has changed externally.\nDo you want to " "reload it?") % os.path.basename(self.editor.file.path)) kwargs = {"expected_action": inner_action} if self.editor.hasFocus() or self.auto_reload: self._notify(*args, **kwargs) else: # show the reload prompt as soon as the editor has focus self._notification_pending = True self._data = (args, kwargs)
Notify user from external change if autoReloadChangedFiles is False then reload the changed file in the editor
entailment
def _check_for_pending(self, *args, **kwargs): """ Checks if a notification is pending. """ if self._notification_pending and not self._processing: self._processing = True args, kwargs = self._data self._notify(*args, **kwargs) self._notification_pending = False self._processing = False
Checks if a notification is pending.
entailment
def _notify_deleted_file(self): """ Notify user from external file deletion. """ self.file_deleted.emit(self.editor) # file deleted, disable file watcher self.enabled = False
Notify user from external file deletion.
entailment
def get_gae_versions(): """Gets a list of all of the available Python SDK versions, sorted with the newest last.""" r = requests.get(SDK_RELEASES_URL) r.raise_for_status() releases = r.json().get('items', {}) # We only care about the Python releases, which all are in the format # "featured/google_appengine_{version}.zip". We'll extract the version # number so we can sort the list by version, and finally get the download # URL. versions_and_urls = [] for release in releases: match = PYTHON_RELEASE_RE.match(release['name']) if not match: continue versions_and_urls.append( ([int(x) for x in match.groups()], release['mediaLink'])) return sorted(versions_and_urls, key=lambda x: x[0])
Gets a list of all of the available Python SDK versions, sorted with the newest last.
entailment
def is_existing_up_to_date(destination, latest_version): """Returns False if there is no existing install or if the existing install is out of date. Otherwise, returns True.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') if not os.path.exists(version_path): return False with open(version_path, 'r') as f: version_line = f.readline() match = SDK_RELEASE_RE.match(version_line) if not match: print('Unable to parse version from:', version_line) return False version = [int(x) for x in match.groups()] return version >= latest_version
Returns False if there is no existing install or if the existing install is out of date. Otherwise, returns True.
entailment
def download_sdk(url): """Downloads the SDK and returns a file-like object for the zip content.""" r = requests.get(url) r.raise_for_status() return StringIO(r.content)
Downloads the SDK and returns a file-like object for the zip content.
entailment
def fixup_version(destination, version): """Newer releases of the SDK do not have the version number set correctly in the VERSION file. Fix it up.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') with open(version_path, 'r') as f: version_data = f.read() version_data = version_data.replace( 'release: "0.0.0"', 'release: "{}"'.format('.'.join(str(x) for x in version))) with open(version_path, 'w') as f: f.write(version_data)
Newer releases of the SDK do not have the version number set correctly in the VERSION file. Fix it up.
entailment
def download_command(args): """Downloads and extracts the latest App Engine SDK to the given destination.""" latest_two_versions = list(reversed(get_gae_versions()))[:2] zip = None version_number = None for version in latest_two_versions: if is_existing_up_to_date(args.destination, version[0]): print( 'App Engine SDK already exists and is up to date ' 'at {}.'.format(args.destination)) return try: print('Downloading App Engine SDK {}'.format( '.'.join([str(x) for x in version[0]]))) zip = download_sdk(version[1]) version_number = version[0] break except Exception as e: print('Failed to download: {}'.format(e)) continue if not zip: return print('Extracting SDK to {}'.format(args.destination)) extract_zip(zip, args.destination) fixup_version(args.destination, version_number) print('App Engine SDK installed.')
Downloads and extracts the latest App Engine SDK to the given destination.
entailment
def preferred_encodings(self): """ The list of user defined encodings, for display in the encodings menu/combobox. """ default_encodings = [ locale.getpreferredencoding().lower().replace('-', '_')] if 'utf_8' not in default_encodings: default_encodings.append('utf_8') default_encodings = list(set(default_encodings)) return json.loads(self._settings.value( 'userDefinedEncodings', json.dumps(default_encodings)))
The list of user defined encodings, for display in the encodings menu/combobox.
entailment
def get_file_encoding(self, file_path, preferred_encoding=None): """ Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding. """ _logger().debug('getting encoding for %s', file_path) try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} try: return map[file_path] except KeyError: encodings = self.preferred_encodings if preferred_encoding: encodings.insert(0, preferred_encoding) for encoding in encodings: _logger().debug('trying encoding: %s', encoding) try: with open(file_path, encoding=encoding) as f: f.read() except (UnicodeDecodeError, IOError, OSError): pass else: return encoding raise KeyError(file_path)
Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding.
entailment
def set_file_encoding(self, path, encoding): """ Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache """ try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} map[path] = encoding self._settings.setValue('cachedFileEncodings', json.dumps(map))
Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache
entailment
def get_cursor_position(self, file_path): """ Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0) """ try: map = json.loads(self._settings.value('cachedCursorPosition')) except TypeError: map = {} try: pos = map[file_path] except KeyError: pos = 0 if isinstance(pos, list): # changed in pyqode 2.6.3, now we store the cursor position # instead of the line and column (faster) pos = 0 return pos
Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0)
entailment
def set_cursor_position(self, path, position): """ Cache encoding for the specified file path. :param path: path of the file to cache :param position: cursor position to cache """ try: map = json.loads(self._settings.value('cachedCursorPosition')) except TypeError: map = {} map[path] = position self._settings.setValue('cachedCursorPosition', json.dumps(map))
Cache encoding for the specified file path. :param path: path of the file to cache :param position: cursor position to cache
entailment
def _mid(string, start, end=None): """ Returns a substring delimited by start and end position. """ if end is None: end = len(string) return string[start:start + end]
Returns a substring delimited by start and end position.
entailment
def _ansi_color(code, theme): """ Converts an ansi code to a QColor, taking the color scheme (theme) into account. """ red = 170 if code & 1 else 0 green = 170 if code & 2 else 0 blue = 170 if code & 4 else 0 color = QtGui.QColor(red, green, blue) if theme is not None: mappings = { '#aa0000': theme.red, '#00aa00': theme.green, '#aaaa00': theme.yellow, '#0000aa': theme.blue, '#aa00aa': theme.magenta, '#00aaaa': theme.cyan, '#000000': theme.background, "#ffffff": theme.foreground } try: return mappings[color.name()] except KeyError: pass return color
Converts an ansi code to a QColor, taking the color scheme (theme) into account.
entailment
def _qkey_to_ascii(event): """ (Try to) convert the Qt key event to the corresponding ASCII sequence for the terminal. This works fine for standard alphanumerical characters, but most other characters require terminal specific control_modifier sequences. The conversion below works for TERM="linux' terminals. """ if sys.platform == 'darwin': control_modifier = QtCore.Qt.MetaModifier else: control_modifier = QtCore.Qt.ControlModifier ctrl = int(event.modifiers() & control_modifier) != 0 if ctrl: if event.key() == QtCore.Qt.Key_P: return b'\x10' elif event.key() == QtCore.Qt.Key_N: return b'\x0E' elif event.key() == QtCore.Qt.Key_C: return b'\x03' elif event.key() == QtCore.Qt.Key_L: return b'\x0C' elif event.key() == QtCore.Qt.Key_B: return b'\x02' elif event.key() == QtCore.Qt.Key_F: return b'\x06' elif event.key() == QtCore.Qt.Key_D: return b'\x04' elif event.key() == QtCore.Qt.Key_O: return b'\x0F' elif event.key() == QtCore.Qt.Key_V: return QtWidgets.qApp.clipboard().text().encode('utf-8') else: return None else: if event.key() == QtCore.Qt.Key_Return: return '\n'.encode('utf-8') elif event.key() == QtCore.Qt.Key_Enter: return '\n'.encode('utf-8') elif event.key() == QtCore.Qt.Key_Tab: return '\t'.encode('utf-8') elif event.key() == QtCore.Qt.Key_Backspace: return b'\x08' elif event.key() == QtCore.Qt.Key_Delete: return b'\x06\x08' elif event.key() == QtCore.Qt.Key_Enter: return '\n'.encode('utf-8') elif event.key() == QtCore.Qt.Key_Home: return b'\x1b[H' elif event.key() == QtCore.Qt.Key_End: return b'\x1b[F' elif event.key() == QtCore.Qt.Key_Left: return b'\x02' elif event.key() == QtCore.Qt.Key_Up: return b'\x10' elif event.key() == QtCore.Qt.Key_Right: return b'\x06' elif event.key() == QtCore.Qt.Key_Down: return b'\x0E' elif event.key() == QtCore.Qt.Key_PageUp: return b'\x49' elif event.key() == QtCore.Qt.Key_PageDown: return b'\x51' elif event.key() == QtCore.Qt.Key_F1: return b'\x1b\x31' elif event.key() == QtCore.Qt.Key_F2: return b'\x1b\x32' elif event.key() == QtCore.Qt.Key_F3: return b'\x00\x3b' elif event.key() == QtCore.Qt.Key_F4: return b'\x1b\x34' elif event.key() == QtCore.Qt.Key_F5: return b'\x1b\x35' elif event.key() == QtCore.Qt.Key_F6: return b'\x1b\x36' elif event.key() == QtCore.Qt.Key_F7: return b'\x1b\x37' elif event.key() == QtCore.Qt.Key_F8: return b'\x1b\x38' elif event.key() == QtCore.Qt.Key_F9: return b'\x1b\x39' elif event.key() == QtCore.Qt.Key_F10: return b'\x1b\x30' elif event.key() == QtCore.Qt.Key_F11: return b'\x45' elif event.key() == QtCore.Qt.Key_F12: return b'\x46' elif event.text() in ('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' '[],=-.;/`&^~*@|#(){}$><%+?"_!' "'\\ :"): return event.text().encode('utf8') else: return None
(Try to) convert the Qt key event to the corresponding ASCII sequence for the terminal. This works fine for standard alphanumerical characters, but most other characters require terminal specific control_modifier sequences. The conversion below works for TERM="linux' terminals.
entailment
def is_running(self): """ Checks if the child process is running (or is starting). """ return self._process.state() in [self._process.Running, self._process.Starting]
Checks if the child process is running (or is starting).
entailment
def start_process(self, program, arguments=None, working_dir=None, print_command=True, use_pseudo_terminal=True, env=None): """ Starts the child process. :param program: program to start :param arguments: list of program arguments :param working_dir: working directory of the child process :param print_command: True to print the full command (pgm + arguments) as the first line of the output window :param use_pseudo_terminal: True to use a pseudo terminal on Unix (pty), False to avoid using a pty wrapper. When using a pty wrapper, both stdout and stderr are merged together. :param environ: environment variables to set on the child process. If None, os.environ will be used. """ # clear previous output self.clear() self.setReadOnly(False) if arguments is None: arguments = [] if sys.platform != 'win32' and use_pseudo_terminal: pgm = sys.executable args = [pty_wrapper.__file__, program] + arguments self.flg_use_pty = use_pseudo_terminal else: pgm = program args = arguments self.flg_use_pty = False # pty not available on windows self._process.setProcessEnvironment(self._setup_process_environment(env)) if working_dir: self._process.setWorkingDirectory(working_dir) if print_command: self._formatter.append_message('\x1b[0m%s %s\n' % (program, ' '.join(arguments)), output_format=OutputFormat.CustomFormat) self._process.start(pgm, args)
Starts the child process. :param program: program to start :param arguments: list of program arguments :param working_dir: working directory of the child process :param print_command: True to print the full command (pgm + arguments) as the first line of the output window :param use_pseudo_terminal: True to use a pseudo terminal on Unix (pty), False to avoid using a pty wrapper. When using a pty wrapper, both stdout and stderr are merged together. :param environ: environment variables to set on the child process. If None, os.environ will be used.
entailment
def stop_process(self): """ Stops the child process. """ self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
Stops the child process.
entailment
def create_color_scheme(background=None, foreground=None, error=None, custom=None, red=None, green=None, yellow=None, blue=None, magenta=None, cyan=None): """ Utility function that creates a color scheme instance, with default values. The default colors are chosen based on the current palette. :param background: background color :param foreground: foreground color :param error: color of error messages (stderr) :param custom: color of custom messages (e.g. to print the full command or the process exit code) :param red: value of the red ANSI color :param green: value of the green ANSI color :param yellow: value of the yellow ANSI color :param blue: value of the blue ANSI color :param magenta: value of the magenta ANSI color :param cyan: value of the cyan ANSI color :return: A ColorScheme instance. """ if background is None: background = qApp.palette().base().color() if foreground is None: foreground = qApp.palette().text().color() is_light = background.lightness() >= 128 if error is None: if is_light: error = QColor('dark red') else: error = QColor('#FF5555') if red is None: red = QColor(error) if green is None: if is_light: green = QColor('dark green') else: green = QColor('#55FF55') if yellow is None: if is_light: yellow = QColor('#aaaa00') else: yellow = QColor('#FFFF55') if blue is None: if is_light: blue = QColor('dark blue') else: blue = QColor('#5555FF') if magenta is None: if is_light: magenta = QColor('dark magenta') else: magenta = QColor('#FF55FF') if cyan is None: if is_light: cyan = QColor('dark cyan') else: cyan = QColor('#55FFFF') if custom is None: custom = QColor('orange') return OutputWindow.ColorScheme(background, foreground, error, custom, red, green, yellow, blue, magenta, cyan)
Utility function that creates a color scheme instance, with default values. The default colors are chosen based on the current palette. :param background: background color :param foreground: foreground color :param error: color of error messages (stderr) :param custom: color of custom messages (e.g. to print the full command or the process exit code) :param red: value of the red ANSI color :param green: value of the green ANSI color :param yellow: value of the yellow ANSI color :param blue: value of the blue ANSI color :param magenta: value of the magenta ANSI color :param cyan: value of the cyan ANSI color :return: A ColorScheme instance.
entailment
def closeEvent(self, event): """ Terminates the child process on close. """ self.stop_process() self.backend.stop() try: self.modes.remove('_LinkHighlighter') except KeyError: pass # already removed super(OutputWindow, self).closeEvent(event)
Terminates the child process on close.
entailment
def keyPressEvent(self, event): """ Handle key press event using the defined input handler. """ if self._process.state() != self._process.Running: return tc = self.textCursor() sel_start = tc.selectionStart() sel_end = tc.selectionEnd() tc.setPosition(self._formatter._last_cursor_pos) self.setTextCursor(tc) if self.input_handler.key_press_event(event): tc.setPosition(sel_start) tc.setPosition(sel_end, tc.KeepAnchor) self.setTextCursor(tc) super(OutputWindow, self).keyPressEvent(event) self._formatter._last_cursor_pos = self.textCursor().position()
Handle key press event using the defined input handler.
entailment
def mouseMoveEvent(self, event): """ Handle mouse over file link. """ c = self.cursorForPosition(event.pos()) block = c.block() self._link_match = None self.viewport().setCursor(QtCore.Qt.IBeamCursor) for match in self.link_regex.finditer(block.text()): if not match: continue start, end = match.span() if start <= c.positionInBlock() <= end: self._link_match = match self.viewport().setCursor(QtCore.Qt.PointingHandCursor) break self._last_hovered_block = block super(OutputWindow, self).mouseMoveEvent(event)
Handle mouse over file link.
entailment
def mousePressEvent(self, event): """ Handle file link clicks. """ super(OutputWindow, self).mousePressEvent(event) if self._link_match: path = self._link_match.group('url') line = self._link_match.group('line') if line is not None: line = int(line) - 1 else: line = 0 self.open_file_requested.emit(path, line)
Handle file link clicks.
entailment
def _init_code_edit(self, backend): """ Initializes the code editor (setup modes, panels and colors). """ from pyqode.core import panels, modes self.modes.append(_LinkHighlighter(self.document())) self.background = self._formatter.color_scheme.background self.foreground = self._formatter.color_scheme.foreground self._reset_stylesheet() self.setCenterOnScroll(False) self.setMouseTracking(True) self.setUndoRedoEnabled(False) search_panel = panels.SearchAndReplacePanel() self.panels.append(search_panel, search_panel.Position.TOP) self.action_copy.setShortcut('Ctrl+Shift+C') self.action_paste.setShortcut('Ctrl+Shift+V') self.remove_action(self.action_undo, sub_menu=None) self.remove_action(self.action_redo, sub_menu=None) self.remove_action(self.action_cut, sub_menu=None) self.remove_action(self.action_duplicate_line, sub_menu=None) self.remove_action(self.action_indent) self.remove_action(self.action_un_indent) self.remove_action(self.action_goto_line) self.remove_action(search_panel.menu.menuAction()) self.remove_menu(self._sub_menus['Advanced']) self.add_action(search_panel.actionSearch, sub_menu=None) self.modes.append(modes.ZoomMode()) self.backend.start(backend)
Initializes the code editor (setup modes, panels and colors).
entailment
def _setup_process_environment(self, env): """ Sets up the process environment. """ environ = self._process.processEnvironment() if env is None: env = {} for k, v in os.environ.items(): environ.insert(k, v) for k, v in env.items(): environ.insert(k, v) if sys.platform != 'win32': environ.insert('TERM', 'xterm') environ.insert('LINES', '24') environ.insert('COLUMNS', '450') environ.insert('PYTHONUNBUFFERED', '1') environ.insert('QT_LOGGING_TO_CONSOLE', '1') return environ
Sets up the process environment.
entailment
def _on_process_error(self, error): """ Display child process error in the text edit. """ if self is None: return err = PROCESS_ERROR_STRING[error] self._formatter.append_message(err + '\r\n', output_format=OutputFormat.ErrorMessageFormat)
Display child process error in the text edit.
entailment
def _on_process_finished(self): """ Write the process finished message and emit the `finished` signal. """ exit_code = self._process.exitCode() if self._process.exitStatus() != self._process.NormalExit: exit_code = 139 self._formatter.append_message('\x1b[0m\nProcess finished with exit code %d' % exit_code, output_format=OutputFormat.CustomFormat) self.setReadOnly(True) self.process_finished.emit()
Write the process finished message and emit the `finished` signal.
entailment
def _read_stdout(self): """ Reads the child process' stdout and process it. """ output = self._decode(self._process.readAllStandardOutput().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.NormalMessageFormat) else: self.insertPlainText(output)
Reads the child process' stdout and process it.
entailment
def _read_stderr(self): """ Reads the child process' stderr and process it. """ output = self._decode(self._process.readAllStandardError().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.ErrorMessageFormat) else: self.insertPlainText(output)
Reads the child process' stderr and process it.
entailment
def parse_text(self, formatted_text): """ Retursn a list of operations (draw, cup, ed,...). Each operation consist of a command and its associated data. :param formatted_text: text to parse with the default char format to apply. :return: list of Operation """ assert isinstance(formatted_text, FormattedText) ret_val = [] fmt = formatted_text.fmt if self._prev_fmt_closed else self._prev_fmt fmt = QtGui.QTextCharFormat(fmt) if not self._pending_text: stripped_text = formatted_text.txt else: stripped_text = self._pending_text + formatted_text.txt self._pending_text = '' while stripped_text: try: escape_pos = stripped_text.index(self._escape[0]) except ValueError: ret_val.append(Operation('draw', FormattedText(stripped_text, fmt))) break else: if escape_pos != 0: ret_val.append(Operation('draw', FormattedText(stripped_text[:escape_pos], fmt))) stripped_text = stripped_text[escape_pos:] fmt = QtGui.QTextCharFormat(fmt) assert stripped_text[0] == self._escape[0] while stripped_text and stripped_text[0] == self._escape[0]: if self._escape.startswith(stripped_text): # control sequence not complete self._pending_text += stripped_text stripped_text = '' break if not stripped_text.startswith(self._escape): # check vt100 escape sequences ctrl_seq = False for alt_seq in self._escape_alts: if stripped_text.startswith(alt_seq): ctrl_seq = True break if not ctrl_seq: # not a control sequence self._pending_text = '' ret_val.append(Operation('draw', FormattedText(stripped_text[:1], fmt))) fmt = QtGui.QTextCharFormat(fmt) stripped_text = stripped_text[1:] continue self._pending_text += _mid(stripped_text, 0, self._escape_len) stripped_text = stripped_text[self._escape_len:] # Non draw related command (cursor/erase) if self._pending_text in [self._escape] + self._escape_alts: m = self._supported_commands.match(stripped_text) if m and self._pending_text == self._escape: _, e = m.span() n = m.group('n') cmd = m.group('cmd') if not n: n = 0 ret_val.append(Operation(self._commands[cmd], n)) self._pending_text = '' stripped_text = stripped_text[e:] continue else: m = self._unsupported_command.match(stripped_text) if m: self._pending_text = '' stripped_text = stripped_text[m.span()[1]:] continue elif self._pending_text in ['\x1b=', '\x1b>']: self._pending_text = '' continue # Handle Select Graphic Rendition commands # get the number str_nbr = '' numbers = [] while stripped_text: if stripped_text[0].isdigit(): str_nbr += stripped_text[0] else: if str_nbr: numbers.append(str_nbr) if not str_nbr or stripped_text[0] != self._semicolon: break str_nbr = '' self._pending_text += _mid(stripped_text, 0, 1) stripped_text = stripped_text[1:] if not stripped_text: break # remove terminating char if not stripped_text.startswith(self._color_terminator): # _logger().warn('removing %s', repr(self._pending_text + stripped_text[0])) self._pending_text = '' stripped_text = stripped_text[1:] break # got consistent control sequence, ok to clear pending text self._pending_text = '' stripped_text = stripped_text[1:] if not numbers: fmt = QtGui.QTextCharFormat(formatted_text.fmt) self.end_format_scope() i_offset = 0 n = len(numbers) for i in range(n): i += i_offset code = int(numbers[i]) if self._TextColorStart <= code <= self._TextColorEnd: fmt.setForeground(_ansi_color(code - self._TextColorStart, self.color_scheme)) self._set_format_scope(fmt) elif self._BackgroundColorStart <= code <= self._BackgroundColorEnd: fmt.setBackground(_ansi_color(code - self._BackgroundColorStart, self.color_scheme)) self._set_format_scope(fmt) else: if code == self._ResetFormat: fmt = QtGui.QTextCharFormat(formatted_text.fmt) self.end_format_scope() elif code == self._BoldText: fmt.setFontWeight(QtGui.QFont.Bold) self._set_format_scope(fmt) elif code == self._NotBold: fmt.setFontWeight(QtGui.QFont.Normal) self._set_format_scope(fmt) elif code == self._ItalicText: fmt.setFontItalic(True) self._set_format_scope(fmt) elif code == self._NotItalicNotFraktur: fmt.setFontItalic(False) self._set_format_scope(fmt) elif code == self._UnderlinedText: fmt.setUnderlineStyle(fmt.SingleUnderline) fmt.setUnderlineColor(fmt.foreground().color()) self._set_format_scope(fmt) elif code == self._NotUnderlined: fmt.setUnderlineStyle(fmt.NoUnderline) self._set_format_scope(fmt) elif code == self._DefaultTextColor: fmt.setForeground(formatted_text.fmt.foreground()) self._set_format_scope(fmt) elif code == self._DefaultBackgroundColor: fmt.setBackground(formatted_text.fmt.background()) self._set_format_scope(fmt) elif code == self._Dim: fmt = QtGui.QTextCharFormat(fmt) fmt.setForeground(fmt.foreground().color().darker(self.DIM_FACTOR)) elif code == self._Negative: normal_fmt = fmt fmt = QtGui.QTextCharFormat(fmt) fmt.setForeground(normal_fmt.background()) fmt.setBackground(normal_fmt.foreground()) elif code == self._Positive: fmt = QtGui.QTextCharFormat(formatted_text.fmt) elif code in [self._RgbBackgroundColor, self._RgbTextColor]: # See http://en.wikipedia.org/wiki/ANSI_escape_code#Colors i += 1 if i == n: break next_code = int(numbers[i]) if next_code == 2: # RGB set with format: 38;2;<r>;<g>;<b> if i + 3 < n: method = fmt.setForeground if code == self._RgbTextColor else fmt.setBackground method(QtGui.QColor(int(numbers[i + 1]), int(numbers[i + 2]), int(numbers[i + 3]))) self._set_format_scope(fmt) i_offset = 3 elif next_code == 5: # 256 color mode with format: 38;5;<i> index = int(numbers[i + 1]) if index < 8: # The first 8 colors are standard low-intensity ANSI colors. color = _ansi_color(index, self.color_scheme) elif index < 16: # The next 8 colors are standard high-intensity ANSI colors. color = _ansi_color(index - 8, self.color_scheme).lighter(150) elif index < 232: # The next 216 colors are a 6x6x6 RGB cube. o = index - 16 color = QtGui.QColor((o / 36) * 51, ((o / 6) % 6) * 51, (o % 6) * 51) else: # The last 24 colors are a greyscale gradient. grey = (index - 232) * 11 color = QtGui.QColor(grey, grey, grey) if code == self._RgbTextColor: fmt.setForeground(color) else: fmt.setBackground(color) self._set_format_scope(fmt) else: _logger().warn('unsupported SGR code: %r', code) return ret_val
Retursn a list of operations (draw, cup, ed,...). Each operation consist of a command and its associated data. :param formatted_text: text to parse with the default char format to apply. :return: list of Operation
entailment
def _set_format_scope(self, fmt): """ Opens the format scope. """ self._prev_fmt = QtGui.QTextCharFormat(fmt) self._prev_fmt_closed = False
Opens the format scope.
entailment
def key_press_event(self, event): """ Directly writes the ascii code of the key to the process' stdin. :retuns: False to prevent the event from being propagated to the parent widget. """ if event.key() == QtCore.Qt.Key_Return: cursor = self.edit.textCursor() cursor.movePosition(cursor.EndOfBlock) self.edit.setTextCursor(cursor) code = _qkey_to_ascii(event) if code: self.process.writeData(code) return False return True
Directly writes the ascii code of the key to the process' stdin. :retuns: False to prevent the event from being propagated to the parent widget.
entailment
def add_command(self, command): """ Adds a command to the history and reset history index. """ try: self._history.remove(command) except ValueError: pass self._history.insert(0, command) self._index = -1
Adds a command to the history and reset history index.
entailment
def scroll_up(self): """ Returns the previous command, if any. """ self._index += 1 nb_commands = len(self._history) if self._index >= nb_commands: self._index = nb_commands - 1 try: return self._history[self._index] except IndexError: return ''
Returns the previous command, if any.
entailment
def scroll_down(self): """ Returns the next command if any. """ self._index -= 1 if self._index < 0: self._index = -1 return '' try: return self._history[self._index] except IndexError: return ''
Returns the next command if any.
entailment
def _insert_command(self, command): """ Insert command by replacing the current input buffer and display it on the text edit. """ self._clear_user_buffer() tc = self.edit.textCursor() tc.insertText(command) self.edit.setTextCursor(tc)
Insert command by replacing the current input buffer and display it on the text edit.
entailment
def key_press_event(self, event): """ Manages our own buffer and send it to the subprocess when user pressed RETURN. """ input_buffer = self._get_input_buffer() ctrl = int(event.modifiers() & QtCore.Qt.ControlModifier) != 0 shift = int(event.modifiers() & QtCore.Qt.ShiftModifier) != 0 delete = event.key() in [QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete] ignore = False if delete and not input_buffer and not shift: return False if ctrl: if shift and event.key() == QtCore.Qt.Key_V: self.edit.insertPlainText(QtWidgets.qApp.clipboard().text()) return False elif event.key() == QtCore.Qt.Key_L: self.edit.clear() if sys.platform == 'win32': self.process.write(b'\r') self.process.write(b'\n') return False if (shift or ctrl) and event.key() == QtCore.Qt.Key_Backspace: if input_buffer.strip() != '': return True self._clear_user_buffer() return False if event.key() == QtCore.Qt.Key_Up: if self.is_code_completion_popup_visible(): return True self._insert_command(self._history.scroll_up()) return False if event.key() == QtCore.Qt.Key_Left: return bool(input_buffer) if event.key() == QtCore.Qt.Key_Down: if self.is_code_completion_popup_visible(): return True self._insert_command(self._history.scroll_down()) return False if event.key() == QtCore.Qt.Key_Home: tc = self.edit.textCursor() tc.movePosition(tc.StartOfBlock) tc.movePosition(tc.Right, tc.MoveAnchor, self.edit._formatter._prefix_len) self.edit.setTextCursor(tc) return False if event.key() == QtCore.Qt.Key_End: tc = self.edit.textCursor() tc.movePosition(tc.EndOfBlock) self.edit.setTextCursor(tc) self._cursor_pos = len(self._get_input_buffer()) return False if event.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter]: if self.is_code_completion_popup_visible(): return True tc = self.edit.textCursor() tc.movePosition(tc.EndOfBlock) self.edit.setTextCursor(tc) # send the user input to the child process if self.edit.flg_use_pty or 'cmd.exe' in self.process.program(): # remove user buffer from text edit, the content of the buffer will be # drawn as soon as we write it to the process stdin tc = self.edit.textCursor() for _ in input_buffer: tc.deletePreviousChar() self.edit.setTextCursor(tc) self._history.add_command(input_buffer) if sys.platform == 'win32': input_buffer += "\r" input_buffer += "\n" self.process.write(input_buffer.encode()) if self.edit.flg_use_pty or 'cmd.exe' in self.process.program(): ignore = True return not ignore
Manages our own buffer and send it to the subprocess when user pressed RETURN.
entailment
def append_message(self, text, output_format=OutputFormat.NormalMessageFormat): """ Parses and append message to the text edit. """ self._append_message(text, self._formats[output_format])
Parses and append message to the text edit.
entailment
def _append_message(self, text, char_format): """ Parses text and executes parsed operations. """ self._cursor = self._text_edit.textCursor() operations = self._parser.parse_text(FormattedText(text, char_format)) for i, operation in enumerate(operations): try: func = getattr(self, '_%s' % operation.command) except AttributeError: print('command not implemented: %r - %r' % ( operation.command, operation.data)) else: try: func(operation.data) except Exception: _logger().exception('exception while running %r', operation) # uncomment next line for debugging commands self._text_edit.repaint()
Parses text and executes parsed operations.
entailment
def _init_formats(self): """ Initialise default formats. """ theme = self._color_scheme # normal message format fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.foreground) fmt.setBackground(theme.background) self._formats[OutputFormat.NormalMessageFormat] = fmt # error message fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.error) fmt.setBackground(theme.background) self._formats[OutputFormat.ErrorMessageFormat] = fmt # debug message fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.custom) fmt.setBackground(theme.background) self._formats[OutputFormat.CustomFormat] = fmt
Initialise default formats.
entailment
def _draw(self, data): """ Draw text """ self._cursor.clearSelection() self._cursor.setPosition(self._last_cursor_pos) if '\x07' in data.txt: print('\a') txt = data.txt.replace('\x07', '') if '\x08' in txt: parts = txt.split('\x08') else: parts = [txt] for i, part in enumerate(parts): if part: part = part.replace('\r\r', '\r') if len(part) >= 80 * 24 * 8: # big output, process it in one step (\r and \n will not be handled) self._draw_chars(data, part) continue to_draw = '' for n, char in enumerate(part): if char == '\n': self._draw_chars(data, to_draw) to_draw = '' self._linefeed() elif char == '\r': self._draw_chars(data, to_draw) to_draw = '' self._erase_in_line(0) try: nchar = part[n + 1] except IndexError: nchar = None if self._cursor.positionInBlock() > 80 and self.flg_bash and nchar != '\n': self._linefeed() self._cursor.movePosition(self._cursor.StartOfBlock) self._text_edit.setTextCursor(self._cursor) else: to_draw += char if to_draw: self._draw_chars(data, to_draw) if i != len(parts) - 1: self._cursor_back(1) self._last_cursor_pos = self._cursor.position() self._prefix_len = self._cursor.positionInBlock() self._text_edit.setTextCursor(self._cursor)
Draw text
entailment
def _draw_chars(self, data, to_draw): """ Draw the specified charachters using the specified format. """ i = 0 while not self._cursor.atBlockEnd() and i < len(to_draw) and len(to_draw) > 1: self._cursor.deleteChar() i += 1 self._cursor.insertText(to_draw, data.fmt)
Draw the specified charachters using the specified format.
entailment
def _linefeed(self): """ Performs a line feed. """ last_line = self._cursor.blockNumber() == self._text_edit.blockCount() - 1 if self._cursor.atEnd() or last_line: if last_line: self._cursor.movePosition(self._cursor.EndOfBlock) self._cursor.insertText('\n') else: self._cursor.movePosition(self._cursor.Down) self._cursor.movePosition(self._cursor.StartOfBlock) self._text_edit.setTextCursor(self._cursor)
Performs a line feed.
entailment
def _cursor_down(self, value): """ Moves the cursor down by ``value``. """ self._cursor.clearSelection() if self._cursor.atEnd(): self._cursor.insertText('\n') else: self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, value) self._last_cursor_pos = self._cursor.position()
Moves the cursor down by ``value``.
entailment
def _cursor_up(self, value): """ Moves the cursor up by ``value``. """ value = int(value) if value == 0: value = 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.Up, self._cursor.MoveAnchor, value) self._last_cursor_pos = self._cursor.position()
Moves the cursor up by ``value``.
entailment
def _cursor_position(self, data): """ Moves the cursor position. """ column, line = self._get_line_and_col(data) self._move_cursor_to_line(line) self._move_cursor_to_column(column) self._last_cursor_pos = self._cursor.position()
Moves the cursor position.
entailment
def _move_cursor_to_column(self, column): """ Moves the cursor to the specified column, if possible. """ last_col = len(self._cursor.block().text()) self._cursor.movePosition(self._cursor.EndOfBlock) to_insert = '' for i in range(column - last_col): to_insert += ' ' if to_insert: self._cursor.insertText(to_insert) self._cursor.movePosition(self._cursor.StartOfBlock) self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, column) self._last_cursor_pos = self._cursor.position()
Moves the cursor to the specified column, if possible.
entailment
def _move_cursor_to_line(self, line): """ Moves the cursor to the specified line, if possible. """ last_line = self._text_edit.document().blockCount() - 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.End) to_insert = '' for i in range(line - last_line): to_insert += '\n' if to_insert: self._cursor.insertText(to_insert) self._cursor.movePosition(self._cursor.Start) self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, line) self._last_cursor_pos = self._cursor.position()
Moves the cursor to the specified line, if possible.
entailment
def _get_line_and_col(data): """ Gets line and column from a string like the following: "1;5" or "1;" or ";5" and convers the column/line numbers to 0 base. """ try: line, column = data.split(';') except AttributeError: line = int(data) column = 1 # handle empty values and convert them to 0 based indices if not line: line = 0 else: line = int(line) - 1 if line < 0: line = 0 if not column: column = 0 else: column = int(column) - 1 if column < 0: column = 0 return column, line
Gets line and column from a string like the following: "1;5" or "1;" or ";5" and convers the column/line numbers to 0 base.
entailment
def _erase_in_line(self, value): """ Erases charachters in line. """ initial_pos = self._cursor.position() if value == 0: # delete end of line self._cursor.movePosition(self._cursor.EndOfBlock, self._cursor.KeepAnchor) elif value == 1: # delete start of line self._cursor.movePosition(self._cursor.StartOfBlock, self._cursor.KeepAnchor) else: # delete whole line self._cursor.movePosition(self._cursor.StartOfBlock) self._cursor.movePosition(self._cursor.EndOfBlock, self._cursor.KeepAnchor) self._cursor.insertText(' ' * len(self._cursor.selectedText())) self._cursor.setPosition(initial_pos) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
Erases charachters in line.
entailment
def _erase_display(self, value): """ Erases display. """ if value == 0: # delete end of line self._cursor.movePosition(self._cursor.End, self._cursor.KeepAnchor) elif value == 1: # delete start of line self._cursor.movePosition(self._cursor.Start, self._cursor.KeepAnchor) else: # delete whole line self._cursor.movePosition(self._cursor.Start) self._cursor.movePosition(self._cursor.End, self._cursor.KeepAnchor) self._cursor.removeSelectedText() self._last_cursor_pos = self._cursor.position()
Erases display.
entailment
def _cursor_back(self, value): """ Moves the cursor back. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Left, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
Moves the cursor back.
entailment
def _cursor_forward(self, value): """ Moves the cursor forward. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
Moves the cursor forward.
entailment
def _delete_chars(self, value): """ Deletes the specified number of charachters. """ value = int(value) if value <= 0: value = 1 for i in range(value): self._cursor.deleteChar() self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
Deletes the specified number of charachters.
entailment
def get_package_info(package): """Gets the PyPI information for a given package.""" url = 'https://pypi.python.org/pypi/{}/json'.format(package) r = requests.get(url) r.raise_for_status() return r.json()
Gets the PyPI information for a given package.
entailment
def read_requirements(req_file): """Reads a requirements file. Args: req_file (str): Filename of requirements file """ items = list(parse_requirements(req_file, session={})) result = [] for item in items: # Get line number from item line_number = item.comes_from.split(req_file + ' (line ')[1][:-1] if item.req: item.req.marker = item.markers result.append((item.req, line_number)) else: result.append((item, line_number)) return result
Reads a requirements file. Args: req_file (str): Filename of requirements file
entailment
def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' else: # "foo > 2.0, < 3.0" return True
Returns true if requirements specify a version range.
entailment
def update_req(req): """Updates a given req object with the latest version.""" if not req.name: return req, None info = get_package_info(req.name) if info['info'].get('_pypi_hidden'): print('{} is hidden on PyPI and will not be updated.'.format(req)) return req, None if _is_pinned(req) and _is_version_range(req): print('{} is pinned to a range and will not be updated.'.format(req)) return req, None newest_version = _get_newest_version(info) current_spec = next(iter(req.specifier)) if req.specifier else None current_version = current_spec.version if current_spec else None new_spec = Specifier(u'=={}'.format(newest_version)) if not current_spec or current_spec._spec != new_spec._spec: req.specifier = new_spec update_info = ( req.name, current_version, newest_version) return req, update_info return req, None
Updates a given req object with the latest version.
entailment
def write_requirements(reqs_linenum, req_file): """Writes a list of req objects out to a given file.""" with open(req_file, 'r') as input: lines = input.readlines() for req in reqs_linenum: line_num = int(req[1]) if hasattr(req[0], 'link'): lines[line_num - 1] = '{}\n'.format(req[0].link) else: lines[line_num - 1] = '{}\n'.format(req[0]) with open(req_file, 'w') as output: output.writelines(lines)
Writes a list of req objects out to a given file.
entailment
def check_req(req): """Checks if a given req is the latest version available.""" if not isinstance(req, Requirement): return None info = get_package_info(req.name) newest_version = _get_newest_version(info) if _is_pinned(req) and _is_version_range(req): return None current_spec = next(iter(req.specifier)) if req.specifier else None current_version = current_spec.version if current_spec else None if current_version != newest_version: return req.name, current_version, newest_version
Checks if a given req is the latest version available.
entailment
def check_requirements_file(req_file, skip_packages): """Return list of outdated requirements. Args: req_file (str): Filename of requirements file skip_packages (list): List of package names to ignore. """ reqs = read_requirements(req_file) if skip_packages is not None: reqs = [req for req in reqs if req.name not in skip_packages] outdated_reqs = filter(None, [check_req(req) for req in reqs]) return outdated_reqs
Return list of outdated requirements. Args: req_file (str): Filename of requirements file skip_packages (list): List of package names to ignore.
entailment
def update_command(args): """Updates all dependencies the specified requirements file.""" updated = update_requirements_file( args.requirements_file, args.skip_packages) if updated: print('Updated requirements in {}:'.format(args.requirements_file)) for item in updated: print(' * {} from {} to {}.'.format(*item)) else: print('All dependencies in {} are up-to-date.'.format( args.requirements_file))
Updates all dependencies the specified requirements file.
entailment
def check_command(args): """Checks that all dependencies in the specified requirements file are up to date.""" outdated = check_requirements_file(args.requirements_file, args.skip_packages) if outdated: print('Requirements in {} are out of date:'.format( args.requirements_file)) for item in outdated: print(' * {} is {} latest is {}.'.format(*item)) sys.exit(1) else: print('Requirements in {} are up to date.'.format( args.requirements_file))
Checks that all dependencies in the specified requirements file are up to date.
entailment
def paintEvent(self, event): """ Fills the panel background. """ super(EncodingPanel, self).paintEvent(event) if self.isVisible(): # fill background painter = QtGui.QPainter(self) self._background_brush = QtGui.QBrush(self._color) painter.fillRect(event.rect(), self._background_brush)
Fills the panel background.
entailment
def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() items = list(style.style_for_token(token).items()) for key, value in items: if value is None and key == 'color': # make sure to use a default visible color for the foreground # brush value = drift_color(self.background, 1000).name() if value: if key == 'color': result.setForeground(self._get_brush(value)) elif key == 'bgcolor': result.setBackground(self._get_brush(value)) elif key == 'bold': result.setFontWeight(QtGui.QFont.Bold) elif key == 'italic': result.setFontItalic(value) elif key == 'underline': result.setUnderlineStyle( QtGui.QTextCharFormat.SingleUnderline) elif key == 'sans': result.setFontStyleHint(QtGui.QFont.SansSerif) elif key == 'roman': result.setFontStyleHint(QtGui.QFont.Times) elif key == 'mono': result.setFontStyleHint(QtGui.QFont.TypeWriter) if token in [Token.Literal.String, Token.Literal.String.Doc, Token.Comment]: # mark strings, comments and docstrings regions for further queries result.setObjectType(result.UserObject) return result
Returns a QTextCharFormat for token by reading a Pygments style.
entailment
def _get_color(color): """ Returns a QColor built from a Pygments color string. """ color = str(color).replace("#", "") qcolor = QtGui.QColor() qcolor.setRgb(int(color[:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16)) return qcolor
Returns a QColor built from a Pygments color string.
entailment
def refresh_editor(self, color_scheme): """ Refresh editor settings (background and highlight colors) when color scheme changed. :param color_scheme: new color scheme. """ self.editor.background = color_scheme.background self.editor.foreground = color_scheme.formats[ 'normal'].foreground().color() self.editor.whitespaces_foreground = color_scheme.formats[ 'whitespace'].foreground().color() try: mode = self.editor.modes.get('CaretLineHighlighterMode') except KeyError: pass else: mode.background = color_scheme.highlight mode.refresh() try: mode = self.editor.panels.get('FoldingPanel') except KeyError: pass else: mode.refresh_decorations(force=True) self.editor._reset_stylesheet()
Refresh editor settings (background and highlight colors) when color scheme changed. :param color_scheme: new color scheme.
entailment
def rehighlight(self): """ Rehighlight the entire document, may be slow. """ start = time.time() QtWidgets.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) try: super(SyntaxHighlighter, self).rehighlight() except RuntimeError: # cloned widget, no need to rehighlight the same document twice ;) pass QtWidgets.QApplication.restoreOverrideCursor() end = time.time() _logger().debug('rehighlight duration: %fs' % (end - start))
Rehighlight the entire document, may be slow.
entailment
def line_number_area_width(self): """ Computes the lineNumber area width depending on the number of lines in the document :return: Widtg """ digits = 1 count = max(1, self.editor.blockCount()) while count >= 10: count /= 10 digits += 1 space = 5 + self.editor.fontMetrics().width("9") * digits return space
Computes the lineNumber area width depending on the number of lines in the document :return: Widtg
entailment
def mousePressEvent(self, e): """ Starts selecting """ self._selecting = True self._sel_start = e.pos().y() start = end = TextHelper(self.editor).line_nbr_from_position( self._sel_start) self._start_line = start TextHelper(self.editor).select_lines(start, end)
Starts selecting
entailment
def set_editor(self, editor): """ Sets the current editor. The widget display the structure of that editor. :param editor: CodeEdit """ try: self._editor.cursorPositionChanged.disconnect(self.sync) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass try: self._outline_mode.document_changed.disconnect( self._on_changed) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass try: self._folding_panel.trigger_state_changed.disconnect( self._on_block_state_changed) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass if editor: self._editor = weakref.proxy(editor) else: self._editor = None if editor is not None: editor.cursorPositionChanged.connect(self.sync) try: self._folding_panel = weakref.proxy( editor.panels.get(FoldingPanel)) except KeyError: pass else: self._folding_panel.trigger_state_changed.connect( self._on_block_state_changed) try: analyser = editor.modes.get(OutlineMode) except KeyError: self._outline_mode = None else: self._outline_mode = weakref.proxy(analyser) analyser.document_changed.connect(self._on_changed) self._on_changed()
Sets the current editor. The widget display the structure of that editor. :param editor: CodeEdit
entailment
def _on_changed(self): """ Update the tree items """ self._updating = True to_collapse = [] self.clear() if self._editor and self._outline_mode and self._folding_panel: items, to_collapse = self.to_tree_widget_items( self._outline_mode.definitions, to_collapse=to_collapse) if len(items): self.addTopLevelItems(items) self.expandAll() for item in reversed(to_collapse): self.collapseItem(item) self._updating = False return # no data root = QtWidgets.QTreeWidgetItem() root.setText(0, _('No data')) root.setIcon(0, icons.icon( 'dialog-information', ':/pyqode-icons/rc/dialog-info.png', 'fa.info-circle')) self.addTopLevelItem(root) self._updating = False self.sync()
Update the tree items
entailment
def _on_item_clicked(self, item): """ Go to the item position in the editor. """ if item: name = item.data(0, QtCore.Qt.UserRole) if name: go = name.block.blockNumber() helper = TextHelper(self._editor) if helper.current_line_nbr() != go: helper.goto_line(go, column=name.column) self._editor.setFocus()
Go to the item position in the editor.
entailment
def to_tree_widget_items(self, definitions, to_collapse=None): """ Converts the list of top level definitions to a list of top level tree items. """ def flatten(definitions): """ Flattens the document structure tree as a simple sequential list. """ ret_val = [] for de in definitions: ret_val.append(de) for sub_d in de.children: ret_val.append(sub_d) ret_val += flatten(sub_d.children) return ret_val def convert(name, editor, to_collapse): ti = QtWidgets.QTreeWidgetItem() ti.setText(0, name.name) if isinstance(name.icon, list): icon = QtGui.QIcon.fromTheme( name.icon[0], QtGui.QIcon(name.icon[1])) else: icon = QtGui.QIcon(name.icon) ti.setIcon(0, icon) name.block = editor.document().findBlockByNumber(name.line) ti.setData(0, QtCore.Qt.UserRole, name) ti.setToolTip(0, name.description) name.tree_item = ti block_data = name.block.userData() if block_data is None: block_data = TextBlockUserData() name.block.setUserData(block_data) block_data.tree_item = ti if to_collapse is not None and \ TextBlockHelper.is_collapsed(name.block): to_collapse.append(ti) for ch in name.children: ti_ch, to_collapse = convert(ch, editor, to_collapse) if ti_ch: ti.addChild(ti_ch) return ti, to_collapse self._definitions = definitions self._flattened_defs = flatten(self._definitions) items = [] for d in definitions: value, to_collapse = convert(d, self._editor, to_collapse) items.append(value) if to_collapse is not None: return items, to_collapse return items
Converts the list of top level definitions to a list of top level tree items.
entailment
def symbol_pos(self, cursor, character_type=OPEN, symbol_type=PAREN): """ Find the corresponding symbol position (line, column) of the specified symbol. If symbol type is PAREN and character_type is OPEN, the function will look for '('. :param cursor: QTextCursor :param character_type: character type to look for (open or close char) :param symbol_type: symbol type (index in the SYMBOLS map). """ retval = None, None original_cursor = self.editor.textCursor() self.editor.setTextCursor(cursor) block = cursor.block() data = get_block_symbol_data(self.editor, block) self._match(symbol_type, data, block.position()) for deco in self._decorations: if deco.character == self.SYMBOLS[symbol_type][character_type]: retval = deco.line, deco.column break self.editor.setTextCursor(original_cursor) self._clear_decorations() return retval
Find the corresponding symbol position (line, column) of the specified symbol. If symbol type is PAREN and character_type is OPEN, the function will look for '('. :param cursor: QTextCursor :param character_type: character type to look for (open or close char) :param symbol_type: symbol type (index in the SYMBOLS map).
entailment
def do_symbols_matching(self): """ Performs symbols matching. """ self._clear_decorations() current_block = self.editor.textCursor().block() data = get_block_symbol_data(self.editor, current_block) pos = self.editor.textCursor().block().position() for symbol in [PAREN, SQUARE, BRACE]: self._match(symbol, data, pos)
Performs symbols matching.
entailment
def set_button_visible(self, visible): """ Sets the clear button as ``visible`` :param visible: Visible state (True = visible, False = hidden). """ self.button.setVisible(visible) left, top, right, bottom = self.getTextMargins() if visible: right = self._margin + self._spacing else: right = 0 self.setTextMargins(left, top, right, bottom)
Sets the clear button as ``visible`` :param visible: Visible state (True = visible, False = hidden).
entailment
def import_class(klass): """ Imports a class from a fully qualified name string. :param klass: class string, e.g. "pyqode.core.backend.workers.CodeCompletionWorker" :return: The corresponding class """ path = klass.rfind(".") class_name = klass[path + 1: len(klass)] try: module = __import__(klass[0:path], globals(), locals(), [class_name]) klass = getattr(module, class_name) except ImportError as e: raise ImportError('%s: %s' % (klass, str(e))) except AttributeError: raise ImportError(klass) else: return klass
Imports a class from a fully qualified name string. :param klass: class string, e.g. "pyqode.core.backend.workers.CodeCompletionWorker" :return: The corresponding class
entailment
def serve_forever(args=None): """ Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments. """ class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) sys.stdout = Unbuffered(sys.stdout) sys.stderr = Unbuffered(sys.stderr) server = JsonServer(args=args) server.serve_forever()
Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments.
entailment
def _create_actions(self): """ Create associated actions """ self.action_to_lower = QtWidgets.QAction(self.editor) self.action_to_lower.triggered.connect(self.to_lower) self.action_to_upper = QtWidgets.QAction(self.editor) self.action_to_upper.triggered.connect(self.to_upper) self.action_to_lower.setText(_('Convert to lower case')) self.action_to_lower.setShortcut('Ctrl+U') self.action_to_upper.setText(_('Convert to UPPER CASE')) self.action_to_upper.setShortcut('Ctrl+Shift+U') self.menu = QtWidgets.QMenu(_('Case'), self.editor) self.menu.addAction(self.action_to_lower) self.menu.addAction(self.action_to_upper) self._actions_created = True
Create associated actions
entailment
def _select_word_cursor(self): """ Selects the word under the mouse cursor. """ cursor = TextHelper(self.editor).word_under_mouse_cursor() if (self._previous_cursor_start != cursor.selectionStart() and self._previous_cursor_end != cursor.selectionEnd()): self._remove_decoration() self._add_decoration(cursor) self._previous_cursor_start = cursor.selectionStart() self._previous_cursor_end = cursor.selectionEnd()
Selects the word under the mouse cursor.
entailment
def _on_mouse_moved(self, event): """ mouse moved callback """ if event.modifiers() & QtCore.Qt.ControlModifier: cursor = TextHelper(self.editor).word_under_mouse_cursor() if (not self._cursor or cursor.position() != self._cursor.position()): self._check_word_cursor(cursor) self._cursor = cursor else: self._cursor = None self._clear_selection()
mouse moved callback
entailment
def _on_mouse_released(self, event): """ mouse pressed callback """ if event.button() == 1 and self._deco: cursor = TextHelper(self.editor).word_under_mouse_cursor() if cursor and cursor.selectedText(): self._timer.request_job( self.word_clicked.emit, cursor)
mouse pressed callback
entailment