INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin.
def set_option(self, option, value): """ Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin. """ CONF.set(self.CONF_SECTION, str(option), value)
Showing message in main window's status bar. This also changes mouse cursor to Qt.WaitCursor
def starting_long_process(self, message): """ Showing message in main window's status bar. This also changes mouse cursor to Qt.WaitCursor """ self.show_message(message) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents()
Clear main window's status bar and restore mouse cursor.
def ending_long_process(self, message=""): """ Clear main window's status bar and restore mouse cursor. """ QApplication.restoreOverrideCursor() self.show_message(message, timeout=2000) QApplication.processEvents()
Show compatibility message.
def show_compatibility_message(self, message): """ Show compatibility message. """ messageBox = QMessageBox(self) messageBox.setWindowModality(Qt.NonModal) messageBox.setAttribute(Qt.WA_DeleteOnClose) messageBox.setWindowTitle('Compatibility Check') messag...
Create options menu.
def refresh_actions(self): """ Create options menu. """ self.options_menu.clear() # Decide what additional actions to show if self.undocked_window is None: additional_actions = [MENU_SEPARATOR, self.undock_action, ...
Action for '('
def _key_paren_left(self, text): """ Action for '(' """ self.current_prompt_pos = self.parentWidget()._prompt_pos if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_object_info(last_obj) ...
Reimplement Qt Method - Basic keypress event handler
def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if key == Qt.Key_ParenLeft and not self.has_selected_text() \ and self.help_enabled and not self.parent()._reading: self._key_p...
Reimplement Qt method to send focus change notification
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ControlWidget, self).focusInEvent(event)
Reimplement Qt method to send focus change notification
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ControlWidget, self).focusOutEvent(event)
Reimplement Qt Method - Basic keypress event handler
def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if key == Qt.Key_Slash and self.isVisible(): self.show_find_widget.emit()
Reimplement Qt method to send focus change notification
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(PageControlWidget, self).focusInEvent(event)
Reimplement Qt method to send focus change notification
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(PageControlWidget, self).focusOutEvent(event)
Return the screen resolution of the primary screen.
def get_screen_resolution(self): """Return the screen resolution of the primary screen.""" widget = QDesktopWidget() geometry = widget.availableGeometry(widget.primaryScreen()) return geometry.width(), geometry.height()
Set the currently visible fig_browser in the stack widget, refresh the actions of the cog menu button and move it to the layout of the new fig_browser.
def set_current_widget(self, fig_browser): """ Set the currently visible fig_browser in the stack widget, refresh the actions of the cog menu button and move it to the layout of the new fig_browser. """ self.stack.setCurrentWidget(fig_browser) # We update the acti...
Register shell with figure explorer. This function opens a new FigureBrowser for browsing the figures in the shell.
def add_shellwidget(self, shellwidget): """ Register shell with figure explorer. This function opens a new FigureBrowser for browsing the figures in the shell. """ shellwidget_id = id(shellwidget) if shellwidget_id not in self.shellwidgets: self.optio...
Apply configuration file's plugin settings
def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" for fig_browser in list(self.shellwidgets.values()): fig_browser.setup(**self.get_settings())
Override Qt method
def flags(self, index): """Override Qt method""" if not index.isValid(): return Qt.ItemIsEnabled column = index.column() if column in [0]: return Qt.ItemFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | ...
Override Qt method
def data(self, index, role=Qt.DisplayRole): """Override Qt method""" if not index.isValid() or not 0 <= index.row() < len(self._rows): return to_qvariant() row = index.row() column = index.column() name, state = self.row(row) if role == Qt.DisplayRo...
Override Qt method
def setData(self, index, value, role): """Override Qt method""" row = index.row() name, state = self.row(row) if role == Qt.CheckStateRole: self.set_row(row, [name, not state]) self._parent.setCurrentIndex(index) self._parent.setFocus() ...
Disable empty layout name possibility
def check_text(self, text): """Disable empty layout name possibility""" if to_text_string(text) == u'': self.button_ok.setEnabled(False) else: self.button_ok.setEnabled(True)
Retry to execute function, ignoring EINTR error (interruptions)
def temp_fail_retry(error, fun, *args): """Retry to execute function, ignoring EINTR error (interruptions)""" while 1: try: return fun(*args) except error as e: eintr = errno.WSAEINTR if os.name == 'nt' else errno.EINTR if e.args[0] == eintr: ...
Write *data* to socket *sock*
def write_packet(sock, data, already_pickled=False): """Write *data* to socket *sock*""" if already_pickled: sent_data = data else: sent_data = pickle.dumps(data, PICKLE_HIGHEST_PROTOCOL) sent_data = struct.pack("l", len(sent_data)) + sent_data nsend = len(sent_data) whil...
Read data from socket *sock* Returns None if something went wrong
def read_packet(sock, timeout=None): """ Read data from socket *sock* Returns None if something went wrong """ sock.settimeout(timeout) dlen, data = None, None try: if os.name == 'nt': # Windows implementation datalen = sock.recv(SZ) dl...
Communicate with monitor
def communicate(sock, command, settings=[]): """Communicate with monitor""" try: COMMUNICATE_LOCK.acquire() write_packet(sock, command) for option in settings: write_packet(sock, option) return read_packet(sock) finally: COMMUNICATE_LOCK.release()
Parse text and return a time in seconds. The text is of the format 0h : 0.min:0.0s:0 ms:0us:0 ns. Spaces are not taken into account and any of the specifiers can be ignored.
def gettime_s(text): """ Parse text and return a time in seconds. The text is of the format 0h : 0.min:0.0s:0 ms:0us:0 ns. Spaces are not taken into account and any of the specifiers can be ignored. """ pattern = r'([+-]?\d+\.?\d*) ?([munsecinh]+)' matches = re.findall(pattern, text...
Simple test function Taken from http://www.huyng.com/posts/python-performance-analysis/
def primes(n): """ Simple test function Taken from http://www.huyng.com/posts/python-performance-analysis/ """ if n==2: return [2] elif n<2: return [] s=list(range(3,n+1,2)) mroot = n ** 0.5 half=(n+1)//2-1 i=0 m=3 while m <= mroot: ...
Save data
def save_data(self): """Save data""" title = _( "Save profiler result") filename, _selfilter = getsavefilename( self, title, getcwd_or_home(), _("Profiler result")+" (*.Result)") if filename: self.datatree.save_data(filename)
Set tree item user data: filename (string) and line_number (int)
def set_item_data(self, item, filename, line_number): """Set tree item user data: filename (string) and line_number (int)""" set_item_user_text(item, '%s%s%d' % (filename, self.SEP, line_number))
Get tree item user data: (filename, line_number)
def get_item_data(self, item): """Get tree item user data: (filename, line_number)""" filename, line_number_str = get_item_user_text(item).split(self.SEP) return filename, int(line_number_str)
Clean the tree and view parameters
def initialize_view(self): """Clean the tree and view parameters""" self.clear() self.item_depth = 0 # To be use for collapsing/expanding one level self.item_list = [] # To be use for collapsing/expanding one level self.items_to_be_shown = {} self.current_view_de...
Load profiler data saved by profile/cProfile module
def load_data(self, profdatafile): """Load profiler data saved by profile/cProfile module""" import pstats try: stats_indi = [pstats.Stats(profdatafile), ] except (OSError, IOError): return self.profdata = stats_indi[0] if self.co...
Find a function without a caller
def find_root(self): """Find a function without a caller""" self.profdata.sort_stats("cumulative") for func in self.profdata.fcn_list: if ('~', 0) != func[0:2] and not func[2].startswith( '<built-in method exec>'): # This skips the profiler f...
Populate the tree with profiler data and display it.
def show_tree(self): """Populate the tree with profiler data and display it.""" self.initialize_view() # Clear before re-populating self.setItemsExpandable(True) self.setSortingEnabled(False) rootkey = self.find_root() # This root contains profiler overhead if root...
Returns processed information about the function's name and file.
def function_info(self, functionKey): """Returns processed information about the function's name and file.""" node_type = 'function' filename, line_number, function_name = functionKey if function_name == '<module>': modulePath, moduleName = osp.split(filename) ...
Get format and units for data coming from profiler task.
def format_measure(measure): """Get format and units for data coming from profiler task.""" # Convert to a positive value. measure = abs(measure) # For number of calls if isinstance(measure, int): return to_text_string(measure) # For time measuremen...
Return a string formatted delta for the values in x. Args: x: 2-item list of integers (representing number of calls) or 2-item list of floats (representing seconds of runtime). Returns: A list with [formatted x[0], [color, formatted delta]], where ...
def color_string(self, x): """Return a string formatted delta for the values in x. Args: x: 2-item list of integers (representing number of calls) or 2-item list of floats (representing seconds of runtime). Returns: A list with [formatted x[0], [c...
Formats the data. self.stats1 contains a list of one or two pstat.Stats() instances, with the first being the current run and the second, the saved run, if it exists. Each Stats instance is a dictionary mapping a function to 5 data points - cumulative calls, number of calls, total...
def format_output(self, child_key): """ Formats the data. self.stats1 contains a list of one or two pstat.Stats() instances, with the first being the current run and the second, the saved run, if it exists. Each Stats instance is a dictionary mapping a function to 5 data ...
Recursive method to create each item (and associated data) in the tree.
def populate_tree(self, parentItem, children_list): """Recursive method to create each item (and associated data) in the tree.""" for child_key in children_list: self.item_depth += 1 (filename, line_number, function_name, file_and_line, node_type ) = self.functi...
Returns True is a function is a descendant of itself.
def is_recursive(self, child_item): """Returns True is a function is a descendant of itself.""" ancestor = child_item.parent() # FIXME: indexes to data should be defined by a dictionary on init while ancestor: if (child_item.data(0, Qt.DisplayRole ...
Return all items with a level <= `maxlevel`
def get_items(self, maxlevel): """Return all items with a level <= `maxlevel`""" itemlist = [] def add_to_itemlist(item, maxlevel, level=1): level += 1 for index in range(item.childCount()): citem = item.child(index) itemlist.append(...
Change the view depth by expand or collapsing all same-level nodes
def change_view(self, change_in_depth): """Change the view depth by expand or collapsing all same-level nodes""" self.current_view_depth += change_in_depth if self.current_view_depth < 0: self.current_view_depth = 0 self.collapseAll() if self.current_view_depth ...
Returns a QSS stylesheet with Spyder color scheme settings. The stylesheet can contain classes for: Qt: QPlainTextEdit, QFrame, QWidget, etc Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) IPython: .error, .in-prompt, .out-prompt, etc
def create_qss_style(color_scheme): """Returns a QSS stylesheet with Spyder color scheme settings. The stylesheet can contain classes for: Qt: QPlainTextEdit, QFrame, QWidget, etc Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) IPython: .error, .in-prompt, .out-prompt, etc """ ...
Create a dictionary that saves the given color scheme as a Pygments style.
def create_pygments_dict(color_scheme_name): """ Create a dictionary that saves the given color scheme as a Pygments style. """ def give_font_weight(is_bold): if is_bold: return 'bold' else: return '' def give_font_style(is_italic): if is_italic:...
Eventually remove .pyc and .pyo files associated to a Python script
def __remove_pyc_pyo(fname): """Eventually remove .pyc and .pyo files associated to a Python script""" if osp.splitext(fname)[1] == '.py': for ending in ('c', 'o'): if osp.exists(fname+ending): os.remove(fname+ending)
Move file from *source* to *dest* If file is a Python script, also rename .pyc and .pyo files if any
def move_file(source, dest): """ Move file from *source* to *dest* If file is a Python script, also rename .pyc and .pyo files if any """ import shutil shutil.copy(source, dest) remove_file(source)
Error handler for `shutil.rmtree`. If the error is due to an access error (read-only file), it attempts to add write permission and then retries. If the error is for another reason, it re-raises the error. Usage: `shutil.rmtree(path, onerror=onerror)
def onerror(function, path, excinfo): """Error handler for `shutil.rmtree`. If the error is due to an access error (read-only file), it attempts to add write permission and then retries. If the error is for another reason, it re-raises the error. Usage: `shutil.rmtree(path, onerror=onerror)...
Find and return a non used port
def select_port(default_port=20128): """Find and return a non used port""" import socket while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # sock.setsockopt(so...
Return number of source code lines for all filenames in subdirectories of *path* with names ending with *extensions* Directory names *excluded_dirnames* will be ignored
def count_lines(path, extensions=None, excluded_dirnames=None): """Return number of source code lines for all filenames in subdirectories of *path* with names ending with *extensions* Directory names *excluded_dirnames* will be ignored""" if extensions is None: extensions = ['.py', '.pyw', ...
Remove backslashes in *path* For Windows platforms only. Returns the path unchanged on other platforms. This is especially useful when formatting path strings on Windows platforms for which folder paths may contain backslashes and provoke unicode decoding errors in Python 3 (or in Python 2 ...
def remove_backslashes(path): """Remove backslashes in *path* For Windows platforms only. Returns the path unchanged on other platforms. This is especially useful when formatting path strings on Windows platforms for which folder paths may contain backslashes and provoke unicode decodi...
Add the decorated method to the given class; replace as needed. If the named method already exists on the given class, it will be replaced, and a reference to the old method is created as cls._old<patch_name><name>. If the "_old_<patch_name>_<name>" attribute already exists, KeyError is raised.
def monkeypatch_method(cls, patch_name): # This function's code was inspired from the following thread: # "[Python-Dev] Monkeypatching idioms -- elegant or ugly?" # by Robert Brewer <fumanchu at aminus.org> # (Tue Jan 15 19:13:25 CET 2008) """ Add the decorated method to the given class; r...
Return common path for all paths in pathlist
def get_common_path(pathlist): """Return common path for all paths in pathlist""" common = osp.normpath(osp.commonprefix(pathlist)) if len(common) > 1: if not osp.isdir(common): return abspardir(common) else: for path in pathlist: if not osp.is...
Memoize objects to trade memory for execution speed Use a limited size cache to store the value, which takes into account The calling args and kwargs See https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
def memoize(obj): """ Memoize objects to trade memory for execution speed Use a limited size cache to store the value, which takes into account The calling args and kwargs See https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize """ cache = obj.cache = {} @functools....
Return None if the pattern is a valid regular expression or a string describing why the pattern is invalid.
def regexp_error_msg(pattern): """ Return None if the pattern is a valid regular expression or a string describing why the pattern is invalid. """ try: re.compile(pattern) except re.error as e: return str(e) return None
Gets the fold region range (start and end line). .. note:: Start line do no encompass the trigger line. :param ignore_blank_lines: True to ignore blank lines at the end of the scope (the method will rewind to find that last meaningful block that is part of the fold scope). ...
def get_range(self, ignore_blank_lines=True): """ Gets the fold region range (start and end line). .. note:: Start line do no encompass the trigger line. :param ignore_blank_lines: True to ignore blank lines at the end of the scope (the method will rewind to find that last ...
Folds the region.
def fold(self): """Folds the region.""" start, end = self.get_range() TextBlockHelper.set_collapsed(self._trigger, True) block = self._trigger.next() while block.blockNumber() <= end and block.isValid(): block.setVisible(False) block = block.next()
Unfolds the region.
def unfold(self): """Unfolds the region.""" # set all direct child blocks which are not triggers to be visible self._trigger.setVisible(True) TextBlockHelper.set_collapsed(self._trigger, False) for block in self.blocks(ignore_blank_lines=False): block.setVisible(True)...
This generator generates the list of blocks directly under the fold region. This list does not contain blocks from child regions. :param ignore_blank_lines: True to ignore last blank lines.
def blocks(self, ignore_blank_lines=True): """ This generator generates the list of blocks directly under the fold region. This list does not contain blocks from child regions. :param ignore_blank_lines: True to ignore last blank lines. """ start, end = self.get_range(ig...
This generator generates the list of direct child regions.
def child_regions(self): """This generator generates the list of direct child regions.""" start, end = self.get_range() block = self._trigger.next() ref_lvl = self.scope_level while block.blockNumber() <= end and block.isValid(): lvl = TextBlockHelper.get_fold_lvl(blo...
Return the parent scope. :return: FoldScope or None
def parent(self): """ Return the parent scope. :return: FoldScope or None """ if TextBlockHelper.get_fold_lvl(self._trigger) > 0 and \ self._trigger.blockNumber(): block = self._trigger.previous() ref_lvl = self.trigger_level - 1 ...
Get the scope text, with a possible maximum number of lines. :param max_lines: limit the number of lines returned to a maximum. :return: str
def text(self, max_lines=sys.maxsize): """ Get the scope text, with a possible maximum number of lines. :param max_lines: limit the number of lines returned to a maximum. :return: str """ ret_val = [] block = self._trigger.next() _, end = self.get_range()...
Detects fold level by looking at the block indentation. :param prev_block: previous text block :param block: current block to highlight
def detect_fold_level(self, prev_block, block): """ Detects fold level by looking at the block indentation. :param prev_block: previous text block :param block: current block to highlight """ text = block.text() prev_lvl = TextBlockHelper().get_fold_lvl(prev_bloc...
Add a extension to the editor. :param extension: The extension instance to add.
def add(self, extension): """ Add a extension to the editor. :param extension: The extension instance to add. """ logger.debug('adding extension {}'.format(extension.name)) self._extensions[extension.name] = extension extension.on_install(self.editor) re...
Remove a extension from the editor. :param name_or_klass: The name (or class) of the extension to remove. :returns: The removed extension.
def remove(self, name_or_klass): """ Remove a extension from the editor. :param name_or_klass: The name (or class) of the extension to remove. :returns: The removed extension. """ logger.debug('removing extension {}'.format(name_or_klass)) extension = self.get(na...
Remove all extensions from the editor. All extensions are removed fromlist and deleted.
def clear(self): """ Remove all extensions from the editor. All extensions are removed fromlist and deleted. """ while len(self._extensions): key = sorted(list(self._extensions.keys()))[0] self.remove(key)
Get a extension by name (or class). :param name_or_klass: The name or the class of the extension to get :type name_or_klass: str or type :rtype: spyder.api.mode.EditorExtension
def get(self, name_or_klass): """ Get a extension by name (or class). :param name_or_klass: The name or the class of the extension to get :type name_or_klass: str or type :rtype: spyder.api.mode.EditorExtension """ if not isinstance(name_or_klass, str): ...
Helper to print text, taking into account backspaces
def insert_text_to(cursor, text, fmt): """Helper to print text, taking into account backspaces""" while True: index = text.find(chr(8)) # backspace if index == -1: break cursor.insertText(text[:index], fmt) if cursor.positionInBlock() > 0: cursor.deletePr...
Set font style with the following attributes: 'foreground_color', 'background_color', 'italic', 'bold' and 'underline'
def set_style(self): """ Set font style with the following attributes: 'foreground_color', 'background_color', 'italic', 'bold' and 'underline' """ if self.current_format is None: assert self.base_format is not None self.current_format = QTextCharF...
Set color scheme (foreground and background).
def set_color_scheme(self, foreground_color, background_color): """Set color scheme (foreground and background).""" if dark_color(foreground_color): self.default_foreground_color = 30 else: self.default_foreground_color = 37 if dark_color(background_color): ...
Set color scheme of the console (foreground and background).
def set_color_scheme(self, foreground_color, background_color): """Set color scheme of the console (foreground and background).""" self.ansi_handler.set_color_scheme(foreground_color, background_color) background_color = QColor(background_color) foreground_color = QColor(foreground_colo...
Reimplement TextEditBaseWidget method
def insert_text(self, text): """Reimplement TextEditBaseWidget method""" # Eventually this maybe should wrap to insert_text_to if # backspace-handling is required self.textCursor().insertText(text, self.default_style.format)
Reimplement Qt method
def paste(self): """Reimplement Qt method""" if self.has_selected_text(): self.remove_selected_text() self.insert_text(QApplication.clipboard().text())
Append text to Python shell In a way, this method overrides the method 'insert_text' when text is inserted at the end of the text widget for a Python shell Handles error messages and show blue underlined links Handles ANSI color sequences Handles ANSI FF sequence
def append_text_to_shell(self, text, error, prompt): """ Append text to Python shell In a way, this method overrides the method 'insert_text' when text is inserted at the end of the text widget for a Python shell Handles error messages and show blue underlined links Hand...
Python Shell only
def set_pythonshell_font(self, font=None): """Python Shell only""" if font is None: font = QFont() for style in self.font_styles: style.apply_style(font=font, is_default=style is self.default_style) self.ansi_handler.set_base_format(s...
Return widget icon
def get_plugin_icon(self): """Return widget icon""" path = osp.join(self.PLUGIN_PATH, self.IMG_PATH) return ima.icon('pylint', icon_path=path)
Register plugin in Spyder's main window
def register_plugin(self): """Register plugin in Spyder's main window""" self.pylint.treewidget.sig_edit_goto.connect(self.main.editor.load) self.pylint.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.main.add_dockwidget(self) pyli...
Run pylint code analysis
def run_pylint(self): """Run pylint code analysis""" if (self.get_option('save_before', True) and not self.main.editor.save()): return self.switch_to_plugin() self.analyze(self.main.editor.get_current_filename())
Reimplement analyze method
def analyze(self, filename): """Reimplement analyze method""" if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.setFocus() self.dockwidget.raise_() self.pylint.analyze(filename)
Set global font used in Spyder.
def set_font(self, font, option): """Set global font used in Spyder.""" # Update fonts in all plugins set_font(font, option=option) plugins = self.main.widgetlist + self.main.thirdparty_plugins for plugin in plugins: plugin.update_font()
Recreates the combobox contents.
def update_combobox(self): """Recreates the combobox contents.""" index = self.current_scheme_index self.schemes_combobox.blockSignals(True) names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass cus...
Enable/disable the Qt style combobox.
def update_qt_style_combobox(self): """Enable/disable the Qt style combobox.""" if is_dark_interface(): self.style_combobox.setEnabled(False) else: self.style_combobox.setEnabled(True)
Updates the enable status of delete and reset buttons.
def update_buttons(self): """Updates the enable status of delete and reset buttons.""" current_scheme = self.current_scheme names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass delete_enabled = current_sch...
Update the color scheme of the preview editor and adds text. Note ---- 'index' is needed, because this is triggered by a signal that sends the selected index.
def update_preview(self, index=None, scheme_name=None): """ Update the color scheme of the preview editor and adds text. Note ---- 'index' is needed, because this is triggered by a signal that sends the selected index. """ text = ('"""A string"""\n\n' ...
Creates a new color scheme with a custom name.
def create_new_scheme(self): """Creates a new color scheme with a custom name.""" names = self.get_option('names') custom_names = self.get_option('custom_names', []) # Get the available number this new color scheme counter = len(custom_names) - 1 custom_index = [int(n.sp...
Edit current scheme.
def edit_scheme(self): """Edit current scheme.""" dlg = self.scheme_editor_dialog dlg.set_scheme(self.current_scheme) if dlg.exec_(): # Update temp scheme to reflect instant edits on the preview temporal_color_scheme = dlg.get_edited_color_scheme() fo...
Deletes the currently selected custom color scheme.
def delete_scheme(self): """Deletes the currently selected custom color scheme.""" scheme_name = self.current_scheme answer = QMessageBox.warning(self, _("Warning"), _("Are you sure you want to delete " "this scheme?"),...
Restore initial values for default color schemes.
def reset_to_default(self): """Restore initial values for default color schemes.""" # Checks that this is indeed a default scheme scheme = self.current_scheme names = self.get_option('names') if scheme in names: for key in syntaxhighlighters.COLOR_SCHEME_KEYS: ...
Set the current stack by 'scheme_name'.
def set_scheme(self, scheme_name): """Set the current stack by 'scheme_name'.""" self.stack.setCurrentIndex(self.order.index(scheme_name)) self.last_used_scheme = scheme_name
Get the values of the last edited color scheme to be used in an instant preview in the preview editor, without using `apply`.
def get_edited_color_scheme(self): """ Get the values of the last edited color scheme to be used in an instant preview in the preview editor, without using `apply`. """ color_scheme = {} scheme_name = self.last_used_scheme for key in self.widgets[scheme_name]: ...
Add a stack for a given scheme and connects the CONF values.
def add_color_scheme_stack(self, scheme_name, custom=False): """Add a stack for a given scheme and connects the CONF values.""" color_scheme_groups = [ (_('Text'), ["normal", "comment", "string", "number", "keyword", "builtin", "definition", "instance", ]), ...
Remove stack widget by 'scheme_name'.
def delete_color_scheme_stack(self, scheme_name): """Remove stack widget by 'scheme_name'.""" self.set_scheme(scheme_name) widget = self.stack.currentWidget() self.stack.removeWidget(widget) index = self.order.index(scheme_name) self.order.pop(index)
Return a list of actions related to plugin
def get_plugin_actions(self): """Return a list of actions related to plugin""" self.new_project_action = create_action(self, _("New Project..."), triggered=self.create_new_project) self.open_project_action = create_acti...
Perform actions before parent main window is closed
def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" self.save_config() self.explorer.closing_widget() return True
Register plugin in Spyder's main window
def register_plugin(self): """Register plugin in Spyder's main window""" ipyconsole = self.main.ipyconsole treewidget = self.explorer.treewidget lspmgr = self.main.lspmanager self.main.add_dockwidget(self) self.explorer.sig_open_file.connect(self.main.open_file) ...
Switch to plugin.
def switch_to_plugin(self): """Switch to plugin.""" # Unmaxizime currently maximized plugin if (self.main.last_plugin is not None and self.main.last_plugin.ismaximized and self.main.last_plugin is not self): self.main.maximize_dockwidget() ...
Setup and update the menu actions.
def setup_menu_actions(self): """Setup and update the menu actions.""" self.recent_project_menu.clear() self.recent_projects_actions = [] if self.recent_projects: for project in self.recent_projects: if self.is_valid_project(project): ...
Update actions of the Projects menu
def update_project_actions(self): """Update actions of the Projects menu""" if self.recent_projects: self.clear_recent_projects_action.setEnabled(True) else: self.clear_recent_projects_action.setEnabled(False) active = bool(self.get_active_project_path()) ...
Edit Spyder active project preferences
def edit_project_preferences(self): """Edit Spyder active project preferences""" from spyder.plugins.projects.confpage import ProjectPreferences if self.project_active: active_project = self.project_list[0] dlg = ProjectPreferences(self, active_project) # ...
Create new project
def create_new_project(self): """Create new project""" self.switch_to_plugin() active_project = self.current_active_project dlg = ProjectDialog(self) dlg.sig_project_creation_requested.connect(self._create_project) dlg.sig_project_creation_requested.connect(self.sig...
Create a new project.
def _create_project(self, path): """Create a new project.""" self.open_project(path=path) self.setup_menu_actions() self.add_to_recent(path)
Open the project located in `path`
def open_project(self, path=None, restart_consoles=True, save_previous_files=True): """Open the project located in `path`""" self.switch_to_plugin() if path is None: basedir = get_home_dir() path = getexistingdirectory(parent=self, ...