sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _get_installation_key( self, project, user_id=None, install_id=None, reprime=False ): """Get the auth token for a project or installation id.""" installation_id = install_id if project is not None: installation_id = self.installation_map.get(project, {}).get( "installation_id" ) if not installation_id: if reprime: # prime installation map and try again without refreshing self._prime_install_map() return self._get_installation_key( project, user_id=user_id, install_id=install_id, reprime=False ) LOGGER.debug("No installation ID available for project %s", project) return "" # Look up the token from cache now = datetime.now(timezone.utc) token, expiry = self.installation_token_cache.get(installation_id, (None, None)) # Request new token if the available one is expired or could not be found if (not expiry) or (not token) or (now >= expiry): LOGGER.debug("Requesting new token for installation %s", installation_id) headers = self._get_app_auth_headers() url = "{}/installations/{}/access_tokens".format( self.api_url, installation_id ) json_data = {"user_id": user_id} if user_id else None response = requests.post(url, headers=headers, json=json_data) response.raise_for_status() data = response.json() token = data["token"] expiry = datetime.strptime(data["expires_at"], "%Y-%m-%dT%H:%M:%SZ") # Update time zone of expiration date to make it comparable with now() expiry = expiry.replace(tzinfo=timezone.utc) # Assume, that the token expires two minutes earlier, to not # get lost during the checkout/scraping? expiry -= timedelta(minutes=2) self.installation_token_cache[installation_id] = (token, expiry) return token
Get the auth token for a project or installation id.
entailment
def _prime_install_map(self): """Fetch all installations and look up the ID for each.""" url = "{}/app/installations".format(self.api_url) headers = self._get_app_auth_headers() LOGGER.debug("Fetching installations for GitHub app") response = requests.get(url, headers=headers) response.raise_for_status() data = response.json() for install in data: install_id = install.get("id") token = self._get_installation_key(project=None, install_id=install_id) headers = { "Accept": PREVIEW_JSON_ACCEPT, "Authorization": "token {}".format(token), } url = "{}/installation/repositories?per_page=100".format(self.api_url) while url: LOGGER.debug("Fetching repos for installation %s", install_id) response = requests.get(url, headers=headers) response.raise_for_status() repos = response.json() # Store all projects in the installation map for repo in repos.get("repositories", []): # TODO (fschmidt): Store the installation's # permissions (could come in handy for later features) project_name = repo["full_name"] self.installation_map[project_name] = { "installation_id": install_id, "default_branch": repo["default_branch"], } # Check if we need to do further page calls url = response.links.get("next", {}).get("url")
Fetch all installations and look up the ID for each.
entailment
def create_github_client(self, project): """Create a github3 client per repo/installation.""" token = self._get_installation_key(project=project) if not token: LOGGER.warning( "Could not find an authentication token for '%s'. Do you " "have access to this repository?", project, ) return gh = github3.GitHubEnterprise(self.base_url) gh.login(token=token) return gh
Create a github3 client per repo/installation.
entailment
def _clear_deco(self): """ Clear line decoration """ if self._decoration: self.editor.decorations.remove(self._decoration) self._decoration = None
Clear line decoration
entailment
def refresh(self): """ Updates the current line decoration """ if self.enabled and self.line: self._clear_deco() brush = QtGui.QBrush(self._color) self._decoration = TextDecoration( self.editor.textCursor(), start_line=self.line) self._decoration.set_background(brush) self._decoration.set_full_width() self._decoration.draw_order = 255 self.editor.decorations.append(self._decoration)
Updates the current line decoration
entailment
def close_others(self): """ Closes every editors tabs except the current one. """ current_widget = self.currentWidget() self._try_close_dirty_tabs(exept=current_widget) i = 0 while self.count() > 1: widget = self.widget(i) if widget != current_widget: self.removeTab(i) else: i = 1
Closes every editors tabs except the current one.
entailment
def save_current(self, path=None): """ Save current editor content. Leave file to None to erase the previous file content. If the current editor's file_path is None and path is None, the function will call ``QtWidgets.QFileDialog.getSaveFileName`` to get a valid save filename. :param path: path of the file to save, leave it None to overwrite existing file. """ try: if not path and not self._current.file.path: path, filter = QtWidgets.QFileDialog.getSaveFileName( self, _('Choose destination path')) if not path: return False old_path = self._current.file.path code_edit = self._current self._save_editor(code_edit, path) path = code_edit.file.path # path (and icon) may have changed if path and old_path != path: self._ensure_unique_name(code_edit, code_edit.file.name) self.setTabText(self.currentIndex(), code_edit._tab_name) ext = os.path.splitext(path)[1] old_ext = os.path.splitext(old_path)[1] if ext != old_ext or not old_path: icon = QtWidgets.QFileIconProvider().icon( QtCore.QFileInfo(code_edit.file.path)) self.setTabIcon(self.currentIndex(), icon) return True except AttributeError: # not an editor widget pass return False
Save current editor content. Leave file to None to erase the previous file content. If the current editor's file_path is None and path is None, the function will call ``QtWidgets.QFileDialog.getSaveFileName`` to get a valid save filename. :param path: path of the file to save, leave it None to overwrite existing file.
entailment
def save_all(self): """ Save all editors. """ initial_index = self.currentIndex() for i in range(self.count()): try: self.setCurrentIndex(i) self.save_current() except AttributeError: pass self.setCurrentIndex(initial_index)
Save all editors.
entailment
def index_from_filename(self, path): """ Checks if the path is already open in an editor tab. :param path: path to check :returns: The tab index if found or -1 """ if path: for i in range(self.count()): widget = self.widget(i) try: if widget.file.path == path: return i except AttributeError: pass # not an editor widget return -1
Checks if the path is already open in an editor tab. :param path: path to check :returns: The tab index if found or -1
entailment
def add_code_edit(self, code_edit, name=None): """ Adds a code edit tab, sets its text as the editor.file.name and sets it as the active tab. The widget is only added if there is no other editor tab open with the same filename, else the already open tab is set as current. If the widget file path is empty, i.e. this is a new document that has not been saved to disk, you may provided a formatted string such as 'New document %d.txt' for the document name. The int format will be automatically replaced by the number of new documents (e.g. 'New document 1.txt' then 'New document 2.txt' and so on). If you prefer to use your own code to manage the file names, just ensure that the names are unique. :param code_edit: The code editor widget tab to append :type code_edit: pyqode.core.api.CodeEdit :param name: Name of the tab. Will use code_edit.file.name if None is supplied. Default is None. If this is a new document, you should either pass a unique name or a formatted string (with a '%d' format) :return: Tab index """ # new empty editor widget (no path set) if code_edit.file.path == '': cnt = 0 for i in range(self.count()): tab = self.widget(i) if tab.file.path.startswith(name[:name.find('%')]): cnt += 1 name %= (cnt + 1) code_edit.file._path = name index = self.index_from_filename(code_edit.file.path) if index != -1: # already open, just show it self.setCurrentIndex(index) # no need to keep this instance self._del_code_edit(code_edit) return -1 self._ensure_unique_name(code_edit, name) index = self.addTab(code_edit, code_edit.file.icon, code_edit._tab_name) self.setCurrentIndex(index) self.setTabText(index, code_edit._tab_name) try: code_edit.setFocus() except TypeError: # PySide code_edit.setFocus() try: file_watcher = code_edit.modes.get(FileWatcherMode) except (KeyError, AttributeError): # not installed pass else: file_watcher.file_deleted.connect(self._on_file_deleted) return index
Adds a code edit tab, sets its text as the editor.file.name and sets it as the active tab. The widget is only added if there is no other editor tab open with the same filename, else the already open tab is set as current. If the widget file path is empty, i.e. this is a new document that has not been saved to disk, you may provided a formatted string such as 'New document %d.txt' for the document name. The int format will be automatically replaced by the number of new documents (e.g. 'New document 1.txt' then 'New document 2.txt' and so on). If you prefer to use your own code to manage the file names, just ensure that the names are unique. :param code_edit: The code editor widget tab to append :type code_edit: pyqode.core.api.CodeEdit :param name: Name of the tab. Will use code_edit.file.name if None is supplied. Default is None. If this is a new document, you should either pass a unique name or a formatted string (with a '%d' format) :return: Tab index
entailment
def addTab(self, elem, icon, name): """ Extends QTabWidget.addTab to keep an internal list of added tabs. :param elem: tab widget :param icon: tab icon :param name: tab name """ self._widgets.append(elem) return super(TabWidget, self).addTab(elem, icon, name)
Extends QTabWidget.addTab to keep an internal list of added tabs. :param elem: tab widget :param icon: tab icon :param name: tab name
entailment
def _name_exists(self, name): """ Checks if we already have an opened tab with the same name. """ for i in range(self.count()): if self.tabText(i) == name: return True return False
Checks if we already have an opened tab with the same name.
entailment
def _rename_duplicate_tabs(self, current, name, path): """ Rename tabs whose title is the same as the name """ for i in range(self.count()): if self.widget(i)._tab_name == name and self.widget(i) != current: file_path = self.widget(i).file.path if file_path: parent_dir = os.path.split(os.path.abspath( os.path.join(file_path, os.pardir)))[1] new_name = os.path.join(parent_dir, name) self.setTabText(i, new_name) self.widget(i)._tab_name = new_name break if path: parent_dir = os.path.split(os.path.abspath( os.path.join(path, os.pardir)))[1] return os.path.join(parent_dir, name) else: return name
Rename tabs whose title is the same as the name
entailment
def removeTab(self, index): """ Removes tab at index ``index``. This method will emits tab_closed for the removed tab. :param index: index of the tab to remove. """ widget = self.widget(index) try: self._widgets.remove(widget) except ValueError: pass self.tab_closed.emit(widget) self._del_code_edit(widget) QTabWidget.removeTab(self, index) if widget == self._current: self._current = None
Removes tab at index ``index``. This method will emits tab_closed for the removed tab. :param index: index of the tab to remove.
entailment
def _try_close_dirty_tabs(self, exept=None): """ Tries to close dirty tabs. Uses DlgUnsavedFiles to ask the user what he wants to do. """ widgets, filenames = self._collect_dirty_tabs(exept=exept) if not len(filenames): return True dlg = DlgUnsavedFiles(self, files=filenames) if dlg.exec_() == dlg.Accepted: if not dlg.discarded: for item in dlg.listWidget.selectedItems(): filename = item.text() widget = None for widget in widgets: if widget.file.path == filename: break if widget != exept: self._save_editor(widget) self.removeTab(self.indexOf(widget)) return True return False
Tries to close dirty tabs. Uses DlgUnsavedFiles to ask the user what he wants to do.
entailment
def _collect_dirty_tabs(self, exept=None): """ Collects the list of dirty tabs """ widgets = [] filenames = [] for i in range(self.count()): widget = self.widget(i) try: if widget.dirty and widget != exept: widgets.append(widget) filenames.append(widget.file.path) except AttributeError: pass return widgets, filenames
Collects the list of dirty tabs
entailment
def _on_dirty_changed(self, dirty): """ Adds a star in front of a dirtt tab and emits dirty_changed. """ try: title = self._current._tab_name index = self.indexOf(self._current) if dirty: self.setTabText(index, "* " + title) else: self.setTabText(index, title) except AttributeError: pass self.dirty_changed.emit(dirty)
Adds a star in front of a dirtt tab and emits dirty_changed.
entailment
def get_preferred_encodings(self): """ Gets the list of preferred encodings. :return: list """ encodings = [] for row in range(self.ui.tableWidgetPreferred.rowCount()): item = self.ui.tableWidgetPreferred.item(row, 0) encodings.append(item.data(QtCore.Qt.UserRole)) return encodings
Gets the list of preferred encodings. :return: list
entailment
def edit_encoding(cls, parent): """ Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings. :param parent: parent widget :return: True in case of succes, False otherwise """ dlg = cls(parent) if dlg.exec_() == dlg.Accepted: settings = Cache() settings.preferred_encodings = dlg.get_preferred_encodings() return True return False
Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings. :param parent: parent widget :return: True in case of succes, False otherwise
entailment
def choose_encoding(cls, parent, path, encoding): """ Show the encodings dialog and returns the user choice. :param parent: parent widget. :param path: file path :param encoding: current file encoding :return: selected encoding """ dlg = cls(parent, path, encoding) dlg.exec_() return dlg.ui.comboBoxEncodings.current_encoding
Show the encodings dialog and returns the user choice. :param parent: parent widget. :param path: file path :param encoding: current file encoding :return: selected encoding
entailment
def pty_wrapper_main(): """ Main function of the pty wrapper script """ # make sure we can import _pty even if pyqode is not installed (this is the case in HackEdit where pyqode has # been vendored). sys.path.insert(0, os.path.dirname(__file__)) import _pty # fixme: find a way to use a pty and keep stdout and stderr as separate channels _pty.spawn(sys.argv[1:])
Main function of the pty wrapper script
entailment
def background(self): """ Background color of the caret line. Default is to use a color slightly darker/lighter than the background color. You can override the automatic color by setting up this property """ if self._color or not self.editor: return self._color else: return drift_color(self.editor.background, 110)
Background color of the caret line. Default is to use a color slightly darker/lighter than the background color. You can override the automatic color by setting up this property
entailment
def refresh(self): """ Updates the current line decoration """ if self.enabled: self._clear_deco() if self._color: color = self._color else: color = drift_color(self.editor.background, 110) brush = QtGui.QBrush(color) self._decoration = TextDecoration(self.editor.textCursor()) self._decoration.set_background(brush) self._decoration.set_full_width() self.editor.decorations.append(self._decoration)
Updates the current line decoration
entailment
def create_menu(self): """ Creates the extended selection menu. """ # setup menu menu = QtWidgets.QMenu(self.editor) menu.setTitle(_('Select')) menu.menuAction().setIcon(QtGui.QIcon.fromTheme('edit-select')) # setup actions menu.addAction(self.action_select_word) menu.addAction(self.action_select_extended_word) menu.addAction(self.action_select_matched) menu.addAction(self.action_select_line) menu.addSeparator() menu.addAction(self.editor.action_select_all) icon = QtGui.QIcon.fromTheme( 'edit-select-all', QtGui.QIcon( ':/pyqode-icons/rc/edit-select-all.png')) self.editor.action_select_all.setIcon(icon) return menu
Creates the extended selection menu.
entailment
def perform_word_selection(self, event=None): """ Performs word selection :param event: QMouseEvent """ self.editor.setTextCursor( TextHelper(self.editor).word_under_cursor(True)) if event: event.accept()
Performs word selection :param event: QMouseEvent
entailment
def perform_extended_selection(self, event=None): """ Performs extended word selection. :param event: QMouseEvent """ TextHelper(self.editor).select_extended_word( continuation_chars=self.continuation_characters) if event: event.accept()
Performs extended word selection. :param event: QMouseEvent
entailment
def perform_matched_selection(self, event): """ Performs matched selection. :param event: QMouseEvent """ selected = TextHelper(self.editor).match_select() if selected and event: event.accept()
Performs matched selection. :param event: QMouseEvent
entailment
def to_dict(self): """ Serializes a definition to a dictionary, ready for json. Children are serialised recursively. """ ddict = {'name': self.name, 'icon': self.icon, 'line': self.line, 'column': self.column, 'children': [], 'description': self.description, 'user_data': self.user_data, 'path': self.file_path} for child in self.children: ddict['children'].append(child.to_dict()) return ddict
Serializes a definition to a dictionary, ready for json. Children are serialised recursively.
entailment
def from_dict(ddict): """ Deserializes a definition from a simple dict. """ d = Definition(ddict['name'], ddict['line'], ddict['column'], ddict['icon'], ddict['description'], ddict['user_data'], ddict['path']) for child_dict in ddict['children']: d.children.append(Definition.from_dict(child_dict)) return d
Deserializes a definition from a simple dict.
entailment
def indent_selection(self, cursor): """ Indent selected text :param cursor: QTextCursor """ doc = self.editor.document() tab_len = self.editor.tab_length cursor.beginEditBlock() nb_lines = len(cursor.selection().toPlainText().splitlines()) c = self.editor.textCursor() if c.atBlockStart() and c.position() == c.selectionEnd(): nb_lines += 1 block = doc.findBlock(cursor.selectionStart()) i = 0 # indent every lines while i < nb_lines: nb_space_to_add = tab_len cursor = QtGui.QTextCursor(block) cursor.movePosition(cursor.StartOfLine, cursor.MoveAnchor) if self.editor.use_spaces_instead_of_tabs: for _ in range(nb_space_to_add): cursor.insertText(" ") else: cursor.insertText('\t') block = block.next() i += 1 cursor.endEditBlock()
Indent selected text :param cursor: QTextCursor
entailment
def unindent_selection(self, cursor): """ Un-indents selected text :param cursor: QTextCursor """ doc = self.editor.document() tab_len = self.editor.tab_length nb_lines = len(cursor.selection().toPlainText().splitlines()) if nb_lines == 0: nb_lines = 1 block = doc.findBlock(cursor.selectionStart()) assert isinstance(block, QtGui.QTextBlock) i = 0 debug('unindent selection: %d lines', nb_lines) while i < nb_lines: txt = block.text() debug('line to unindent: %s', txt) debug('self.editor.use_spaces_instead_of_tabs: %r', self.editor.use_spaces_instead_of_tabs) if self.editor.use_spaces_instead_of_tabs: indentation = (len(txt) - len(txt.lstrip())) else: indentation = len(txt) - len(txt.replace('\t', '')) debug('unindent line %d: %d spaces', i, indentation) if indentation > 0: c = QtGui.QTextCursor(block) c.movePosition(c.StartOfLine, cursor.MoveAnchor) for _ in range(tab_len): txt = block.text() if len(txt) and txt[0] == ' ': c.deleteChar() block = block.next() i += 1 return cursor
Un-indents selected text :param cursor: QTextCursor
entailment
def indent(self): """ Indents text at cursor position. """ cursor = self.editor.textCursor() assert isinstance(cursor, QtGui.QTextCursor) if cursor.hasSelection(): self.indent_selection(cursor) else: # simply insert indentation at the cursor position tab_len = self.editor.tab_length cursor.beginEditBlock() if self.editor.use_spaces_instead_of_tabs: nb_space_to_add = tab_len - cursor.positionInBlock() % tab_len cursor.insertText(nb_space_to_add * " ") else: cursor.insertText('\t') cursor.endEditBlock()
Indents text at cursor position.
entailment
def split(self): """ Split the code editor widget, return a clone of the widget ready to be used (and synchronised with its original). Splitting the widget is done in 2 steps: - first we clone the widget, you can override ``clone`` if your widget needs additional arguments. - then we link the two text document and disable some modes on the cloned instance (such as the watcher mode). """ # cache cursor position so that the clone open at the current cursor # pos l, c = TextHelper(self).cursor_position() clone = self.clone() self.link(clone) TextHelper(clone).goto_line(l, c) self.clones.append(clone) return clone
Split the code editor widget, return a clone of the widget ready to be used (and synchronised with its original). Splitting the widget is done in 2 steps: - first we clone the widget, you can override ``clone`` if your widget needs additional arguments. - then we link the two text document and disable some modes on the cloned instance (such as the watcher mode).
entailment
def link(self, clone): """ Links the clone with its original. We copy the file manager infos (path, mimetype, ...) and setup the clone text document as reference to our text document. :param clone: clone to link. """ clone.file._path = self.file.path clone.file._encoding = self.file.encoding clone.file._mimetype = self.file.mimetype clone.setDocument(self.document()) for original_mode, mode in zip(list(self.modes), list(clone.modes)): mode.enabled = original_mode.enabled mode.clone_settings(original_mode) for original_panel, panel in zip( list(self.panels), list(clone.panels)): panel.enabled = original_panel.isEnabled() panel.clone_settings(original_panel) if not original_panel.isVisible(): panel.setVisible(False) clone.use_spaces_instead_of_tabs = self.use_spaces_instead_of_tabs clone.tab_length = self.tab_length clone._save_on_focus_out = self._save_on_focus_out clone.show_whitespaces = self.show_whitespaces clone.font_name = self.font_name clone.font_size = self.font_size clone.zoom_level = self.zoom_level clone.background = self.background clone.foreground = self.foreground clone.whitespaces_foreground = self.whitespaces_foreground clone.selection_background = self.selection_background clone.selection_foreground = self.selection_foreground clone.word_separators = self.word_separators clone.file.clone_settings(self.file)
Links the clone with its original. We copy the file manager infos (path, mimetype, ...) and setup the clone text document as reference to our text document. :param clone: clone to link.
entailment
def close(self, clear=True): """ Closes the editor, stops the backend and removes any installed mode/panel. This is also where we cache the cursor position. :param clear: True to clear the editor content before closing. """ if self._tooltips_runner: self._tooltips_runner.cancel_requests() self._tooltips_runner = None self.decorations.clear() self.modes.clear() self.panels.clear() self.backend.stop() Cache().set_cursor_position( self.file.path, self.textCursor().position()) super(CodeEdit, self).close()
Closes the editor, stops the backend and removes any installed mode/panel. This is also where we cache the cursor position. :param clear: True to clear the editor content before closing.
entailment
def show_tooltip(self, pos, tooltip, _sender_deco=None): """ Show a tool tip at the specified position :param pos: Tooltip position :param tooltip: Tooltip text :param _sender_deco: TextDecoration which is the sender of the show tooltip request. (for internal use only). """ if _sender_deco is not None and _sender_deco not in self.decorations: return QtWidgets.QToolTip.showText(pos, tooltip[0: 1024], self)
Show a tool tip at the specified position :param pos: Tooltip position :param tooltip: Tooltip text :param _sender_deco: TextDecoration which is the sender of the show tooltip request. (for internal use only).
entailment
def setPlainText(self, txt, mime_type, encoding): """ Extends setPlainText to force the user to setup an encoding and a mime type. Emits the new_text_set signal. :param txt: The new text to set. :param mime_type: Associated mimetype. Setting the mime will update the pygments lexer. :param encoding: text encoding """ self.file.mimetype = mime_type self.file._encoding = encoding self._original_text = txt self._modified_lines.clear() import time t = time.time() super(CodeEdit, self).setPlainText(txt) _logger().log(5, 'setPlainText duration: %fs' % (time.time() - t)) self.new_text_set.emit() self.redoAvailable.emit(False) self.undoAvailable.emit(False)
Extends setPlainText to force the user to setup an encoding and a mime type. Emits the new_text_set signal. :param txt: The new text to set. :param mime_type: Associated mimetype. Setting the mime will update the pygments lexer. :param encoding: text encoding
entailment
def add_action(self, action, sub_menu='Advanced'): """ Adds an action to the editor's context menu. :param action: QAction to add to the context menu. :param sub_menu: The name of a sub menu where to put the action. 'Advanced' by default. If None or empty, the action will be added at the root of the submenu. """ if sub_menu: try: mnu = self._sub_menus[sub_menu] except KeyError: mnu = QtWidgets.QMenu(sub_menu) self.add_menu(mnu) self._sub_menus[sub_menu] = mnu finally: mnu.addAction(action) else: self._actions.append(action) action.setShortcutContext(QtCore.Qt.WidgetShortcut) self.addAction(action)
Adds an action to the editor's context menu. :param action: QAction to add to the context menu. :param sub_menu: The name of a sub menu where to put the action. 'Advanced' by default. If None or empty, the action will be added at the root of the submenu.
entailment
def insert_action(self, action, prev_action): """ Inserts an action to the editor's context menu. :param action: action to insert :param prev_action: the action after which the new action must be inserted or the insert index """ if isinstance(prev_action, QtWidgets.QAction): index = self._actions.index(prev_action) else: index = prev_action action.setShortcutContext(QtCore.Qt.WidgetShortcut) self._actions.insert(index, action)
Inserts an action to the editor's context menu. :param action: action to insert :param prev_action: the action after which the new action must be inserted or the insert index
entailment
def add_separator(self, sub_menu='Advanced'): """ Adds a sepqrator to the editor's context menu. :return: The sepator that has been added. :rtype: QtWidgets.QAction """ action = QtWidgets.QAction(self) action.setSeparator(True) if sub_menu: try: mnu = self._sub_menus[sub_menu] except KeyError: pass else: mnu.addAction(action) else: self._actions.append(action) return action
Adds a sepqrator to the editor's context menu. :return: The sepator that has been added. :rtype: QtWidgets.QAction
entailment
def remove_action(self, action, sub_menu='Advanced'): """ Removes an action/separator from the editor's context menu. :param action: Action/seprator to remove. :param advanced: True to remove the action from the advanced submenu. """ if sub_menu: try: mnu = self._sub_menus[sub_menu] except KeyError: pass else: mnu.removeAction(action) else: try: self._actions.remove(action) except ValueError: pass self.removeAction(action)
Removes an action/separator from the editor's context menu. :param action: Action/seprator to remove. :param advanced: True to remove the action from the advanced submenu.
entailment
def add_menu(self, menu): """ Adds a sub-menu to the editor context menu. Menu are put at the bottom of the context menu. .. note:: to add a menu in the middle of the context menu, you can always add its menuAction(). :param menu: menu to add """ self._menus.append(menu) self._menus = sorted(list(set(self._menus)), key=lambda x: x.title()) for action in menu.actions(): action.setShortcutContext(QtCore.Qt.WidgetShortcut) self.addActions(menu.actions())
Adds a sub-menu to the editor context menu. Menu are put at the bottom of the context menu. .. note:: to add a menu in the middle of the context menu, you can always add its menuAction(). :param menu: menu to add
entailment
def remove_menu(self, menu): """ Removes a sub-menu from the context menu. :param menu: Sub-menu to remove. """ self._menus.remove(menu) for action in menu.actions(): self.removeAction(action)
Removes a sub-menu from the context menu. :param menu: Sub-menu to remove.
entailment
def goto_line(self): """ Shows the *go to line dialog* and go to the selected line. """ helper = TextHelper(self) line, result = DlgGotoLine.get_line( self, helper.current_line_nbr(), helper.line_count()) if not result: return return helper.goto_line(line, move=True)
Shows the *go to line dialog* and go to the selected line.
entailment
def zoom_in(self, increment=1): """ Zooms in the editor (makes the font bigger). :param increment: zoom level increment. Default is 1. """ self.zoom_level += increment TextHelper(self).mark_whole_doc_dirty() self._reset_stylesheet()
Zooms in the editor (makes the font bigger). :param increment: zoom level increment. Default is 1.
entailment
def zoom_out(self, decrement=1): """ Zooms out the editor (makes the font smaller). :param decrement: zoom level decrement. Default is 1. The value is given as an absolute value. """ self.zoom_level -= decrement # make sure font size remains > 0 if self.font_size + self.zoom_level <= 0: self.zoom_level = -self._font_size + 1 TextHelper(self).mark_whole_doc_dirty() self._reset_stylesheet()
Zooms out the editor (makes the font smaller). :param decrement: zoom level decrement. Default is 1. The value is given as an absolute value.
entailment
def duplicate_line(self): """ Duplicates the line under the cursor. If multiple lines are selected, only the last one is duplicated. """ cursor = self.textCursor() assert isinstance(cursor, QtGui.QTextCursor) has_selection = True if not cursor.hasSelection(): cursor.select(cursor.LineUnderCursor) has_selection = False line = cursor.selectedText() line = '\n'.join(line.split('\u2029')) end = cursor.selectionEnd() cursor.setPosition(end) cursor.beginEditBlock() cursor.insertText('\n') cursor.insertText(line) cursor.endEditBlock() if has_selection: pos = cursor.position() cursor.setPosition(end + 1) cursor.setPosition(pos, cursor.KeepAnchor) self.setTextCursor(cursor)
Duplicates the line under the cursor. If multiple lines are selected, only the last one is duplicated.
entailment
def cut(self): """ Cuts the selected text or the whole line if no text was selected. """ tc = self.textCursor() helper = TextHelper(self) tc.beginEditBlock() no_selection = False sText = tc.selection().toPlainText() if not helper.current_line_text() and sText.count("\n") > 1: tc.deleteChar() else: if not self.textCursor().hasSelection(): no_selection = True TextHelper(self).select_whole_line() super(CodeEdit, self).cut() if no_selection: tc.deleteChar() tc.endEditBlock() self.setTextCursor(tc)
Cuts the selected text or the whole line if no text was selected.
entailment
def copy(self): """ Copy the selected text to the clipboard. If no text was selected, the entire line is copied (this feature can be turned off by setting :attr:`select_line_on_copy_empty` to False. """ if self.select_line_on_copy_empty and not self.textCursor().hasSelection(): TextHelper(self).select_whole_line() super(CodeEdit, self).copy()
Copy the selected text to the clipboard. If no text was selected, the entire line is copied (this feature can be turned off by setting :attr:`select_line_on_copy_empty` to False.
entailment
def resizeEvent(self, e): """ Overrides resize event to resize the editor's panels. :param e: resize event """ super(CodeEdit, self).resizeEvent(e) self.panels.resize()
Overrides resize event to resize the editor's panels. :param e: resize event
entailment
def paintEvent(self, e): """ Overrides paint event to update the list of visible blocks and emit the painted event. :param e: paint event """ self._update_visible_blocks(e) super(CodeEdit, self).paintEvent(e) self.painted.emit(e)
Overrides paint event to update the list of visible blocks and emit the painted event. :param e: paint event
entailment
def keyPressEvent(self, event): """ Overrides the keyPressEvent to emit the key_pressed signal. Also takes care of indenting and handling smarter home key. :param event: QKeyEvent """ if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_pressed.emit(event) state = event.isAccepted() if not event.isAccepted(): if event.key() == QtCore.Qt.Key_Tab and event.modifiers() == \ QtCore.Qt.NoModifier: self.indent() event.accept() elif event.key() == QtCore.Qt.Key_Backtab and \ event.modifiers() == QtCore.Qt.NoModifier: self.un_indent() event.accept() elif event.key() == QtCore.Qt.Key_Home and \ int(event.modifiers()) & QtCore.Qt.ControlModifier == 0: self._do_home_key( event, int(event.modifiers()) & QtCore.Qt.ShiftModifier) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).keyPressEvent(event) new_state = event.isAccepted() event.setAccepted(state) self.post_key_pressed.emit(event) event.setAccepted(new_state)
Overrides the keyPressEvent to emit the key_pressed signal. Also takes care of indenting and handling smarter home key. :param event: QKeyEvent
entailment
def keyReleaseEvent(self, event): """ Overrides keyReleaseEvent to emit the key_released signal. :param event: QKeyEvent """ if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_released.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).keyReleaseEvent(event)
Overrides keyReleaseEvent to emit the key_released signal. :param event: QKeyEvent
entailment
def focusInEvent(self, event): """ Overrides focusInEvent to emits the focused_in signal :param event: QFocusEvent """ self.focused_in.emit(event) super(CodeEdit, self).focusInEvent(event)
Overrides focusInEvent to emits the focused_in signal :param event: QFocusEvent
entailment
def mousePressEvent(self, event): """ Overrides mousePressEvent to emits mouse_pressed signal :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_pressed.emit(event) if event.button() == QtCore.Qt.LeftButton: cursor = self.cursorForPosition(event.pos()) for sel in self.decorations: if sel.cursor.blockNumber() == cursor.blockNumber(): if sel.contains_cursor(cursor): sel.signals.clicked.emit(sel) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).mousePressEvent(event)
Overrides mousePressEvent to emits mouse_pressed signal :param event: QMouseEvent
entailment
def mouseReleaseEvent(self, event): """ Emits mouse_released signal. :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_released.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).mouseReleaseEvent(event)
Emits mouse_released signal. :param event: QMouseEvent
entailment
def wheelEvent(self, event): """ Emits the mouse_wheel_activated signal. :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_wheel_activated.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).wheelEvent(event)
Emits the mouse_wheel_activated signal. :param event: QMouseEvent
entailment
def mouseMoveEvent(self, event): """ Overrides mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event. :param event: QMouseEvent """ cursor = self.cursorForPosition(event.pos()) self._last_mouse_pos = event.pos() block_found = False for sel in self.decorations: if sel.contains_cursor(cursor) and sel.tooltip: if (self._prev_tooltip_block_nbr != cursor.blockNumber() or not QtWidgets.QToolTip.isVisible()): pos = event.pos() # add left margin pos.setX(pos.x() + self.panels.margin_size()) # add top margin pos.setY(pos.y() + self.panels.margin_size(0)) self._tooltips_runner.request_job( self.show_tooltip, self.mapToGlobal(pos), sel.tooltip[0: 1024], sel) self._prev_tooltip_block_nbr = cursor.blockNumber() block_found = True break if not block_found and self._prev_tooltip_block_nbr != -1: QtWidgets.QToolTip.hideText() self._prev_tooltip_block_nbr = -1 self._tooltips_runner.cancel_requests() self.mouse_moved.emit(event) super(CodeEdit, self).mouseMoveEvent(event)
Overrides mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event. :param event: QMouseEvent
entailment
def showEvent(self, event): """ Overrides showEvent to update the viewport margins """ super(CodeEdit, self).showEvent(event) self.panels.refresh()
Overrides showEvent to update the viewport margins
entailment
def get_context_menu(self): """ Gets the editor context menu. :return: QMenu """ mnu = QtWidgets.QMenu() mnu.addActions(self._actions) mnu.addSeparator() for menu in self._menus: mnu.addMenu(menu) return mnu
Gets the editor context menu. :return: QMenu
entailment
def _show_context_menu(self, point): """ Shows the context menu """ tc = self.textCursor() nc = self.cursorForPosition(point) if not nc.position() in range(tc.selectionStart(), tc.selectionEnd()): self.setTextCursor(nc) self._mnu = self.get_context_menu() if len(self._mnu.actions()) > 1 and self.show_context_menu: self._mnu.popup(self.mapToGlobal(point))
Shows the context menu
entailment
def _set_whitespaces_flags(self, show): """ Sets show white spaces flag """ doc = self.document() options = doc.defaultTextOption() if show: options.setFlags(options.flags() | QtGui.QTextOption.ShowTabsAndSpaces) else: options.setFlags( options.flags() & ~QtGui.QTextOption.ShowTabsAndSpaces) doc.setDefaultTextOption(options)
Sets show white spaces flag
entailment
def _init_actions(self, create_standard_actions): """ Init context menu action """ menu_advanced = QtWidgets.QMenu(_('Advanced')) self.add_menu(menu_advanced) self._sub_menus = { 'Advanced': menu_advanced } if create_standard_actions: # Undo action = QtWidgets.QAction(_('Undo'), self) action.setShortcut('Ctrl+Z') action.setIcon(icons.icon( 'edit-undo', ':/pyqode-icons/rc/edit-undo.png', 'fa.undo')) action.triggered.connect(self.undo) self.undoAvailable.connect(action.setVisible) action.setVisible(False) self.add_action(action, sub_menu=None) self.action_undo = action # Redo action = QtWidgets.QAction(_('Redo'), self) action.setShortcut('Ctrl+Y') action.setIcon(icons.icon( 'edit-redo', ':/pyqode-icons/rc/edit-redo.png', 'fa.repeat')) action.triggered.connect(self.redo) self.redoAvailable.connect(action.setVisible) action.setVisible(False) self.add_action(action, sub_menu=None) self.action_redo = action # Copy action = QtWidgets.QAction(_('Copy'), self) action.setShortcut(QtGui.QKeySequence.Copy) action.setIcon(icons.icon( 'edit-copy', ':/pyqode-icons/rc/edit-copy.png', 'fa.copy')) action.triggered.connect(self.copy) self.add_action(action, sub_menu=None) self.action_copy = action # cut action = QtWidgets.QAction(_('Cut'), self) action.setShortcut(QtGui.QKeySequence.Cut) action.setIcon(icons.icon( 'edit-cut', ':/pyqode-icons/rc/edit-cut.png', 'fa.cut')) action.triggered.connect(self.cut) self.add_action(action, sub_menu=None) self.action_cut = action # paste action = QtWidgets.QAction(_('Paste'), self) action.setShortcut(QtGui.QKeySequence.Paste) action.setIcon(icons.icon( 'edit-paste', ':/pyqode-icons/rc/edit-paste.png', 'fa.paste')) action.triggered.connect(self.paste) self.add_action(action, sub_menu=None) self.action_paste = action # duplicate line action = QtWidgets.QAction(_('Duplicate line'), self) action.setShortcut('Ctrl+D') action.triggered.connect(self.duplicate_line) self.add_action(action, sub_menu=None) self.action_duplicate_line = action # swap line up action = QtWidgets.QAction(_('Swap line up'), self) action.setShortcut("Alt++") action.triggered.connect(self.swapLineUp) self.add_action(action, sub_menu=None) self.action_swap_line_up = action # swap line down action = QtWidgets.QAction(_('Swap line down'), self) action.setShortcut("Alt+-") action.triggered.connect(self.swapLineDown) self.add_action(action, sub_menu=None) self.action_swap_line_down = action # select all action = QtWidgets.QAction(_('Select all'), self) action.setShortcut(QtGui.QKeySequence.SelectAll) action.triggered.connect(self.selectAll) self.action_select_all = action self.add_action(self.action_select_all, sub_menu=None) self.add_separator(sub_menu=None) if create_standard_actions: # indent action = QtWidgets.QAction(_('Indent'), self) action.setShortcut('Tab') action.setIcon(icons.icon( 'format-indent-more', ':/pyqode-icons/rc/format-indent-more.png', 'fa.indent')) action.triggered.connect(self.indent) self.add_action(action) self.action_indent = action # unindent action = QtWidgets.QAction(_('Un-indent'), self) action.setShortcut('Shift+Tab') action.setIcon(icons.icon( 'format-indent-less', ':/pyqode-icons/rc/format-indent-less.png', 'fa.dedent')) action.triggered.connect(self.un_indent) self.add_action(action) self.action_un_indent = action self.add_separator() # goto action = QtWidgets.QAction(_('Go to line'), self) action.setShortcut('Ctrl+G') action.setIcon(icons.icon( 'go-jump', ':/pyqode-icons/rc/goto-line.png', 'fa.share')) action.triggered.connect(self.goto_line) self.add_action(action) self.action_goto_line = action
Init context menu action
entailment
def _init_settings(self): """ Init setting """ self._show_whitespaces = False self._tab_length = 4 self._use_spaces_instead_of_tabs = True self.setTabStopWidth(self._tab_length * self.fontMetrics().width(" ")) self._set_whitespaces_flags(self._show_whitespaces)
Init setting
entailment
def _init_style(self): """ Inits style options """ self._background = QtGui.QColor('white') self._foreground = QtGui.QColor('black') self._whitespaces_foreground = QtGui.QColor('light gray') app = QtWidgets.QApplication.instance() self._sel_background = app.palette().highlight().color() self._sel_foreground = app.palette().highlightedText().color() self._font_size = 10 self.font_name = ""
Inits style options
entailment
def _update_visible_blocks(self, *args): """ Updates the list of visible blocks """ self._visible_blocks[:] = [] block = self.firstVisibleBlock() block_nbr = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated( self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) ebottom_top = 0 ebottom_bottom = self.height() while block.isValid(): visible = (top >= ebottom_top and bottom <= ebottom_bottom) if not visible: break if block.isVisible(): self._visible_blocks.append((top, block_nbr, block)) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) block_nbr = block.blockNumber()
Updates the list of visible blocks
entailment
def _on_text_changed(self): """ Adjust dirty flag depending on editor's content """ if not self._cleaning: ln = TextHelper(self).cursor_position()[0] self._modified_lines.add(ln)
Adjust dirty flag depending on editor's content
entailment
def _reset_stylesheet(self): """ Resets stylesheet""" self.setFont(QtGui.QFont(self._font_family, self._font_size + self._zoom_level)) flg_stylesheet = hasattr(self, '_flg_stylesheet') if QtWidgets.QApplication.instance().styleSheet() or flg_stylesheet: self._flg_stylesheet = True # On Window, if the application once had a stylesheet, we must # keep on using a stylesheet otherwise strange colors appear # see https://github.com/OpenCobolIDE/OpenCobolIDE/issues/65 # Also happen on plasma 5 try: plasma = os.environ['DESKTOP_SESSION'] == 'plasma' except KeyError: plasma = False if sys.platform == 'win32' or plasma: self.setStyleSheet('''QPlainTextEdit { background-color: %s; color: %s; } ''' % (self.background.name(), self.foreground.name())) else: # on linux/osx we just have to set an empty stylesheet to # cancel any previous stylesheet and still keep a correct # style for scrollbars self.setStyleSheet('') else: p = self.palette() p.setColor(QtGui.QPalette.Base, self.background) p.setColor(QtGui.QPalette.Text, self.foreground) p.setColor(QtGui.QPalette.Highlight, self.selection_background) p.setColor(QtGui.QPalette.HighlightedText, self.selection_foreground) self.setPalette(p) self.repaint()
Resets stylesheet
entailment
def _do_home_key(self, event=None, select=False): """ Performs home key action """ # get nb char to first significative char delta = (self.textCursor().positionInBlock() - TextHelper(self).line_indent()) cursor = self.textCursor() move = QtGui.QTextCursor.MoveAnchor if select: move = QtGui.QTextCursor.KeepAnchor if delta > 0: cursor.movePosition(QtGui.QTextCursor.Left, move, delta) else: cursor.movePosition(QtGui.QTextCursor.StartOfBlock, move) self.setTextCursor(cursor) if event: event.accept()
Performs home key action
entailment
def cached(key, timeout=3600): """Cache the return value of the decorated function with the given key. Key can be a String or a function. If key is a function, it must have the same arguments as the decorated function, otherwise it cannot be called successfully. """ def decorator(f): @wraps(f) def wrapped(*args, **kwargs): cache = get_cache() # Check if key is a function if callable(key): cache_key = key(*args, **kwargs) else: cache_key = key # Try to get the value from cache cached_val = cache.get(cache_key) if cached_val is None: # Call the original function and cache the result cached_val = f(*args, **kwargs) cache.set(cache_key, cached_val, timeout) return cached_val return wrapped return decorator
Cache the return value of the decorated function with the given key. Key can be a String or a function. If key is a function, it must have the same arguments as the decorated function, otherwise it cannot be called successfully.
entailment
def _copy_cell_text(self): """ Copies the description of the selected message to the clipboard """ txt = self.currentItem().text() QtWidgets.QApplication.clipboard().setText(txt)
Copies the description of the selected message to the clipboard
entailment
def clear(self): """ Clears the tables and the message list """ QtWidgets.QTableWidget.clear(self) self.setRowCount(0) self.setColumnCount(4) self.setHorizontalHeaderLabels( ["Type", "File name", "Line", "Description"])
Clears the tables and the message list
entailment
def _make_icon(cls, status): """ Make icon from icon filename/tuple (if you want to use a theme) """ icon = cls.ICONS[status] if isinstance(icon, tuple): return QtGui.QIcon.fromTheme( icon[0], QtGui.QIcon(icon[1])) elif isinstance(icon, str): return QtGui.QIcon(icon) elif isinstance(icon, QtGui.QIcon): return icon else: return None
Make icon from icon filename/tuple (if you want to use a theme)
entailment
def add_message(self, msg): """ Adds a checker message to the table. :param msg: The message to append :type msg: pyqode.core.modes.CheckerMessage """ row = self.rowCount() self.insertRow(row) # type item = QtWidgets.QTableWidgetItem( self._make_icon(msg.status), msg.status_string) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_TYPE, item) # filename item = QtWidgets.QTableWidgetItem( QtCore.QFileInfo(msg.path).fileName()) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_FILE_NAME, item) # line if msg.line < 0: item = QtWidgets.QTableWidgetItem("-") else: item = QtWidgets.QTableWidgetItem(str(msg.line + 1)) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_LINE_NBR, item) # desc item = QtWidgets.QTableWidgetItem(msg.description) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_MSG, item)
Adds a checker message to the table. :param msg: The message to append :type msg: pyqode.core.modes.CheckerMessage
entailment
def _on_item_activated(self, item): """ Emits the message activated signal """ msg = item.data(QtCore.Qt.UserRole) self.msg_activated.emit(msg)
Emits the message activated signal
entailment
def showDetails(self): """ Shows the error details. """ msg = self.currentItem().data(QtCore.Qt.UserRole) desc = msg.description desc = desc.replace('\r\n', '\n').replace('\r', '\n') desc = desc.replace('\n', '<br/>') QtWidgets.QMessageBox.information( self, _('Message details'), _("""<p><b>Description:</b><br/>%s</p> <p><b>File:</b><br/>%s</p> <p><b>Line:</b><br/>%d</p> """) % (desc, msg.path, msg.line + 1, ))
Shows the error details.
entailment
def get_line(cls, parent, current_line, line_count): """ Gets user selected line. :param parent: Parent widget :param current_line: Current line number :param line_count: Number of lines in the current text document. :returns: tuple(line, status) status is False if the dialog has been rejected. """ dlg = DlgGotoLine(parent, current_line + 1, line_count) if dlg.exec_() == dlg.Accepted: return dlg.spinBox.value() - 1, True return current_line, False
Gets user selected line. :param parent: Parent widget :param current_line: Current line number :param line_count: Number of lines in the current text document. :returns: tuple(line, status) status is False if the dialog has been rejected.
entailment
def close_panel(self): """ Closes the panel """ self.hide() self.lineEditReplace.clear() self.lineEditSearch.clear()
Closes the panel
entailment
def request_search(self, txt=None): """ Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead. """ if self.checkBoxRegex.isChecked(): try: re.compile(self.lineEditSearch.text(), re.DOTALL) except sre_constants.error as e: self._show_error(e) return else: self._show_error(None) if txt is None or isinstance(txt, int): txt = self.lineEditSearch.text() if txt: self.job_runner.request_job( self._exec_search, txt, self._search_flags()) else: self.job_runner.cancel_requests() self._clear_occurrences() self._on_search_finished()
Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead.
entailment
def _set_widget_background_color(widget, color): """ Changes the base color of a widget (background). :param widget: widget to modify :param color: the color to apply """ pal = widget.palette() pal.setColor(pal.Base, color) widget.setPalette(pal)
Changes the base color of a widget (background). :param widget: widget to modify :param color: the color to apply
entailment
def select_next(self): """ Selects the next occurrence. :return: True in case of success, false if no occurrence could be selected. """ current_occurence = self._current_occurrence() occurrences = self.get_occurences() if not occurrences: return current = self._occurrences[current_occurence] cursor_pos = self.editor.textCursor().position() if cursor_pos not in range(current[0], current[1] + 1) or \ current_occurence == -1: # search first occurrence that occurs after the cursor position current_occurence = 0 for i, (start, end) in enumerate(self._occurrences): if end > cursor_pos: current_occurence = i break else: if (current_occurence == -1 or current_occurence >= len(occurrences) - 1): current_occurence = 0 else: current_occurence += 1 self._set_current_occurrence(current_occurence) try: cursor = self.editor.textCursor() cursor.setPosition(occurrences[current_occurence][0]) cursor.setPosition(occurrences[current_occurence][1], cursor.KeepAnchor) self.editor.setTextCursor(cursor) return True except IndexError: return False
Selects the next occurrence. :return: True in case of success, false if no occurrence could be selected.
entailment
def replace(self, text=None): """ Replaces the selected occurrence. :param text: The replacement text. If it is None, the lineEditReplace's text is used instead. :return True if the text could be replace properly, False if there is no more occurrences to replace. """ if text is None or isinstance(text, bool): text = self.lineEditReplace.text() current_occurences = self._current_occurrence() occurrences = self.get_occurences() if current_occurences == -1: self.select_next() current_occurences = self._current_occurrence() try: # prevent search request due to editor textChanged try: self.editor.textChanged.disconnect(self.request_search) except (RuntimeError, TypeError): # already disconnected pass occ = occurrences[current_occurences] cursor = self.editor.textCursor() cursor.setPosition(occ[0]) cursor.setPosition(occ[1], cursor.KeepAnchor) len_to_replace = len(cursor.selectedText()) len_replacement = len(text) offset = len_replacement - len_to_replace cursor.insertText(text) self.editor.setTextCursor(cursor) self._remove_occurrence(current_occurences, offset) current_occurences -= 1 self._set_current_occurrence(current_occurences) self.select_next() self.cpt_occurences = len(self.get_occurences()) self._update_label_matches() self._update_buttons() return True except IndexError: return False finally: self.editor.textChanged.connect(self.request_search)
Replaces the selected occurrence. :param text: The replacement text. If it is None, the lineEditReplace's text is used instead. :return True if the text could be replace properly, False if there is no more occurrences to replace.
entailment
def replace_all(self, text=None): """ Replaces all occurrences in the editor's document. :param text: The replacement text. If None, the content of the lineEdit replace will be used instead """ cursor = self.editor.textCursor() cursor.beginEditBlock() remains = self.replace(text=text) while remains: remains = self.replace(text=text) cursor.endEditBlock()
Replaces all occurrences in the editor's document. :param text: The replacement text. If None, the content of the lineEdit replace will be used instead
entailment
def _search_flags(self): """ Returns the user search flag: (regex, case_sensitive, whole_words). """ return (self.checkBoxRegex.isChecked(), self.checkBoxCase.isChecked(), self.checkBoxWholeWords.isChecked(), self.checkBoxInSelection.isChecked())
Returns the user search flag: (regex, case_sensitive, whole_words).
entailment
def _create_decoration(self, selection_start, selection_end): """ Creates the text occurences decoration """ deco = TextDecoration(self.editor.document(), selection_start, selection_end) deco.set_background(QtGui.QBrush(self.background)) deco.set_outline(self._outline) deco.set_foreground(QtCore.Qt.black) deco.draw_order = 1 return deco
Creates the text occurences decoration
entailment
def _send_request(self): """ Sends the request to the backend. """ if isinstance(self._worker, str): classname = self._worker else: classname = '%s.%s' % (self._worker.__module__, self._worker.__name__) self.request_id = str(uuid.uuid4()) self.send({'request_id': self.request_id, 'worker': classname, 'data': self._args})
Sends the request to the backend.
entailment
def send(self, obj, encoding='utf-8'): """ Sends a python object to the backend. The object **must be JSON serialisable**. :param obj: object to send :param encoding: encoding used to encode the json message into a bytes array, this should match CodeEdit.file.encoding. """ comm('sending request: %r', obj) msg = json.dumps(obj) msg = msg.encode(encoding) header = struct.pack('=I', len(msg)) self.write(header) self.write(msg)
Sends a python object to the backend. The object **must be JSON serialisable**. :param obj: object to send :param encoding: encoding used to encode the json message into a bytes array, this should match CodeEdit.file.encoding.
entailment
def _connect(self): """ Connects our client socket to the backend socket """ if self is None: return comm('connecting to 127.0.0.1:%d', self._port) address = QtNetwork.QHostAddress('127.0.0.1') self.connectToHost(address, self._port) if sys.platform == 'darwin': self.waitForConnected()
Connects our client socket to the backend socket
entailment
def _read_payload(self): """ Reads the payload (=data) """ comm('reading payload data') comm('remaining bytes to read: %d', self._to_read) data_read = self.read(self._to_read) nb_bytes_read = len(data_read) comm('%d bytes read', nb_bytes_read) self._data_buf += data_read self._to_read -= nb_bytes_read if self._to_read <= 0: try: data = self._data_buf.decode('utf-8') except AttributeError: data = bytes(self._data_buf.data()).decode('utf-8') comm('payload read: %r', data) comm('payload length: %r', len(self._data_buf)) comm('decoding payload as json object') obj = json.loads(data) comm('response received: %r', obj) try: results = obj['results'] except (KeyError, TypeError): results = None # possible callback if self._callback and self._callback(): self._callback()(results) self._header_complete = False self._data_buf = bytes() self.finished.emit(self)
Reads the payload (=data)
entailment
def _on_ready_read(self): """ Read bytes when ready read """ while self.bytesAvailable(): if not self._header_complete: self._read_header() else: self._read_payload()
Read bytes when ready read
entailment
def _on_process_started(self): """ Logs process started """ comm('backend process started') if self is None: return self.starting = False self.running = True
Logs process started
entailment
def _on_process_error(self, error): """ Logs process error """ if self is None: return if error not in PROCESS_ERROR_STRING: error = -1 if not self._prevent_logs: _logger().warning(PROCESS_ERROR_STRING[error])
Logs process error
entailment
def _on_process_stdout_ready(self): """ Logs process output """ if not self: return o = self.readAllStandardOutput() try: output = bytes(o).decode(self._encoding) except TypeError: output = bytes(o.data()).decode(self._encoding) for line in output.splitlines(): self._srv_logger.log(1, line)
Logs process output
entailment
def _on_process_stderr_ready(self): """ Logs process output (stderr) """ try: o = self.readAllStandardError() except (TypeError, RuntimeError): # widget already deleted return try: output = bytes(o).decode(self._encoding) except TypeError: output = bytes(o.data()).decode(self._encoding) for line in output.splitlines(): self._srv_logger.error(line)
Logs process output (stderr)
entailment
def replace_pattern(tokens, new_pattern): """ Given a RegexLexer token dictionary 'tokens', replace all patterns that match the token specified in 'new_pattern' with 'new_pattern'. """ for state in tokens.values(): for index, pattern in enumerate(state): if isinstance(pattern, tuple) and pattern[1] == new_pattern[1]: state[index] = new_pattern
Given a RegexLexer token dictionary 'tokens', replace all patterns that match the token specified in 'new_pattern' with 'new_pattern'.
entailment
def on_install(self, editor): """ :type editor: pyqode.code.api.CodeEdit """ self._clear_caches() self._update_style() super(PygmentsSH, self).on_install(editor)
:type editor: pyqode.code.api.CodeEdit
entailment
def set_mime_type(self, mime_type): """ Update the highlighter lexer based on a mime type. :param mime_type: mime type of the new lexer to setup. """ try: self.set_lexer_from_mime_type(mime_type) except ClassNotFound: _logger().exception('failed to get lexer from mimetype') self._lexer = TextLexer() return False except ImportError: # import error while loading some pygments plugins, the editor # should not crash _logger().warning('failed to get lexer from mimetype (%s)' % mime_type) self._lexer = TextLexer() return False else: return True
Update the highlighter lexer based on a mime type. :param mime_type: mime type of the new lexer to setup.
entailment
def set_lexer_from_filename(self, filename): """ Change the lexer based on the filename (actually only the extension is needed) :param filename: Filename or extension """ self._lexer = None if filename.endswith("~"): filename = filename[0:len(filename) - 1] try: self._lexer = get_lexer_for_filename(filename) except (ClassNotFound, ImportError): print('class not found for url', filename) try: m = mimetypes.guess_type(filename) print(m) self._lexer = get_lexer_for_mimetype(m[0]) except (ClassNotFound, IndexError, ImportError): self._lexer = get_lexer_for_mimetype('text/plain') if self._lexer is None: _logger().warning('failed to get lexer from filename: %s, using ' 'plain text instead...', filename) self._lexer = TextLexer()
Change the lexer based on the filename (actually only the extension is needed) :param filename: Filename or extension
entailment
def set_lexer_from_mime_type(self, mime, **options): """ Sets the pygments lexer from mime type. :param mime: mime type :param options: optional addtional options. """ self._lexer = get_lexer_for_mimetype(mime, **options) _logger().debug('lexer for mimetype (%s): %r', mime, self._lexer)
Sets the pygments lexer from mime type. :param mime: mime type :param options: optional addtional options.
entailment
def highlight_block(self, text, block): """ Highlights the block using a pygments lexer. :param text: text of the block to highlith :param block: block to highlight """ if self.color_scheme.name != self._pygments_style: self._pygments_style = self.color_scheme.name self._update_style() original_text = text if self.editor and self._lexer and self.enabled: if block.blockNumber(): prev_data = self._prev_block.userData() if prev_data: if hasattr(prev_data, "syntax_stack"): self._lexer._saved_state_stack = prev_data.syntax_stack elif hasattr(self._lexer, '_saved_state_stack'): del self._lexer._saved_state_stack # Lex the text using Pygments index = 0 usd = block.userData() if usd is None: usd = TextBlockUserData() block.setUserData(usd) tokens = list(self._lexer.get_tokens(text)) for token, text in tokens: length = len(text) fmt = self._get_format(token) if token in [Token.Literal.String, Token.Literal.String.Doc, Token.Comment]: fmt.setObjectType(fmt.UserObject) self.setFormat(index, length, fmt) index += length if hasattr(self._lexer, '_saved_state_stack'): setattr(usd, "syntax_stack", self._lexer._saved_state_stack) # Clean up for the next go-round. del self._lexer._saved_state_stack # spaces text = original_text expression = QRegExp(r'\s+') index = expression.indexIn(text, 0) while index >= 0: index = expression.pos(0) length = len(expression.cap(0)) self.setFormat(index, length, self._get_format(Whitespace)) index = expression.indexIn(text, index + length) self._prev_block = block
Highlights the block using a pygments lexer. :param text: text of the block to highlith :param block: block to highlight
entailment