text
stringlengths
81
112k
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() #...
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>': ...
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): retur...
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 ...
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...
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_numb...
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 (ch...
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.c...
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 ...
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 ...
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: ...
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.remov...
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) ...
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): "...
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)...
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 subdirectori...
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 ...
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. d...
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 pa...
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 ...
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) ...
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). ...
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 = b...
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): b...
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 direc...
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.i...
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.pre...
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 numb...
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 ...
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._e...
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 rem...
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._ext...
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: ...
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 cur...
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 ...
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' ...
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(backg...
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_tex...
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_handle...
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...
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...
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)
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 ValueE...
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 ValueErro...
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 a...
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(cu...
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_s...
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 " ...
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 k...
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 `appl...
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", ...
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...
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) ...
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...
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
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_...
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_p...
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 = ...
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 = ProjectPrefere...
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_reques...
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 = getexisting...
Close current project and return to a window without an active project def close_project(self): """ Close current project and return to a window without an active project """ if self.current_active_project: self.switch_to_plugin() if self....
Delete the current project without deleting the files in the directory. def delete_project(self): """ Delete the current project without deleting the files in the directory. """ if self.current_active_project: self.switch_to_plugin() path = self.current_act...
Reopen the active project when Spyder was closed last time, if any def reopen_last_project(self): """ Reopen the active project when Spyder was closed last time, if any """ current_project_path = self.get_option('current_project_path', ...
Get the list of recent filenames of a project def get_project_filenames(self): """Get the list of recent filenames of a project""" recent_files = [] if self.current_active_project: recent_files = self.current_active_project.get_recent_files() elif self.latest_project: ...
Set the list of open file names in a project def set_project_filenames(self, recent_files): """Set the list of open file names in a project""" if (self.current_active_project and self.is_valid_project( self.current_active_project.root_path)): sel...
Get path of the active project def get_active_project_path(self): """Get path of the active project""" active_project_path = None if self.current_active_project: active_project_path = self.current_active_project.root_path return active_project_path
Get project path as a list to be added to PYTHONPATH def get_pythonpath(self, at_start=False): """Get project path as a list to be added to PYTHONPATH""" if at_start: current_path = self.get_option('current_project_path', default=None) ...
Save configuration: opened projects & tree widget state. Also save whether dock widget is visible if a project is open. def save_config(self): """ Save configuration: opened projects & tree widget state. Also save whether dock widget is visible if a project is open. """...
Show the explorer def show_explorer(self): """Show the explorer""" if self.dockwidget is not None: if self.dockwidget.isHidden(): self.dockwidget.show() self.dockwidget.raise_() self.dockwidget.update()
Check if a directory is a valid Spyder project def is_valid_project(self, path): """Check if a directory is a valid Spyder project""" spy_project_dir = osp.join(path, '.spyproject') if osp.isdir(path) and osp.isdir(spy_project_dir): return True else: return...
Add an entry to recent projetcs We only maintain the list of the 10 most recent projects def add_to_recent(self, project): """ Add an entry to recent projetcs We only maintain the list of the 10 most recent projects """ if project not in self.recent_projects: ...
Show/hide system console window attached to current process. Return it's previous state. Availability: Windows def set_attached_console_visible(state): """Show/hide system console window attached to current process. Return it's previous state. Availability: Windows""" flag...
Return the first installed font family in family list def get_family(families): """Return the first installed font family in family list""" if not isinstance(families, list): families = [ families ] for family in families: if font_is_installed(family): return family else: ...
Get console font properties depending on OS and user options def get_font(section='appearance', option='font', font_size_delta=0): """Get console font properties depending on OS and user options""" font = FONT_CACHE.get((section, option)) if font is None: families = CONF.get(section, option+"/fami...
Set font def set_font(font, section='appearance', option='font'): """Set font""" CONF.set(section, option+'/family', to_text_string(font.family())) CONF.set(section, option+'/size', float(font.pointSize())) CONF.set(section, option+'/italic', int(font.italic())) CONF.set(section, option+'/bold', in...
DEPRECATED: This function will be removed in Spyder 4.0 Define a fixed shortcut according to a keysequence string def fixed_shortcut(keystr, parent, action): """ DEPRECATED: This function will be removed in Spyder 4.0 Define a fixed shortcut according to a keysequence string """ sc = QShortcu...
Create a Shortcut namedtuple for a widget The data contained in this tuple will be registered in our shortcuts preferences page def config_shortcut(action, context, name, parent): """ Create a Shortcut namedtuple for a widget The data contained in this tuple will be registered in our ...
Iterate over keyboard shortcuts. def iter_shortcuts(): """Iterate over keyboard shortcuts.""" for context_name, keystr in CONF.items('shortcuts'): context, name = context_name.split("/", 1) yield context, name, keystr
Get syntax color scheme def get_color_scheme(name): """Get syntax color scheme""" color_scheme = {} for key in sh.COLOR_SCHEME_KEYS: color_scheme[key] = CONF.get("appearance", "%s/%s" % (name, key)) return color_scheme
Set syntax color scheme def set_color_scheme(name, color_scheme, replace=True): """Set syntax color scheme""" section = "appearance" names = CONF.get("appearance", "names", []) for key in sh.COLOR_SCHEME_KEYS: option = "%s/%s" % (name, key) value = CONF.get(section, option, default=None...
Reset color scheme to default values def set_default_color_scheme(name, replace=True): """Reset color scheme to default values""" assert name in sh.COLOR_SCHEME_NAMES set_color_scheme(name, sh.get_color_scheme(name), replace=replace)
Check if the font color used in the color scheme is dark. def is_dark_font_color(color_scheme): """Check if the font color used in the color scheme is dark.""" color_scheme = get_color_scheme(color_scheme) font_color, fon_fw, fon_fs = color_scheme['normal'] return dark_color(font_color)
Filter mouse press events. Events that are captured and not propagated return True. Events that are not captured and are propagated return False. def eventFilter(self, obj, event): """Filter mouse press events. Events that are captured and not propagated return True. Events that ...
Method called when a tab from a QTabBar has been pressed. def tab_pressed(self, event): """Method called when a tab from a QTabBar has been pressed.""" self.from_index = self.dock_tabbar.tabAt(event.pos()) self.dock_tabbar.setCurrentIndex(self.from_index) if event.button() == Qt.RightB...
Show the context menu assigned to nontabs section. def show_nontab_menu(self, event): """Show the context menu assigned to nontabs section.""" menu = self.main.createPopupMenu() menu.exec_(self.dock_tabbar.mapToGlobal(event.pos()))
Install an event filter to capture mouse events in the tabs of a QTabBar holding tabified dockwidgets. def install_tab_event_filter(self, value): """ Install an event filter to capture mouse events in the tabs of a QTabBar holding tabified dockwidgets. """ dock_tabbar = ...
Load all bookmarks from config. def _load_all_bookmarks(): """Load all bookmarks from config.""" slots = CONF.get('editor', 'bookmarks', {}) for slot_num in list(slots.keys()): if not osp.isfile(slots[slot_num][0]): slots.pop(slot_num) return slots
Load all bookmarks for a specific file from config. def load_bookmarks(filename): """Load all bookmarks for a specific file from config.""" bookmarks = _load_all_bookmarks() return {k: v for k, v in bookmarks.items() if v[0] == filename}
Load all bookmarks but those from a specific file. def load_bookmarks_without_file(filename): """Load all bookmarks but those from a specific file.""" bookmarks = _load_all_bookmarks() return {k: v for k, v in bookmarks.items() if v[0] != filename}
Save all bookmarks from specific file to config. def save_bookmarks(filename, bookmarks): """Save all bookmarks from specific file to config.""" if not osp.isfile(filename): return slots = load_bookmarks_without_file(filename) for slot_num, content in bookmarks.items(): slots[slot_num] ...
Request to start a LSP server to attend a language. def report_open_file(self, options): """Request to start a LSP server to attend a language.""" filename = options['filename'] logger.debug('Call LSP for %s' % filename) language = options['language'] callback = options['co...
Register LSP server settings. def register_lsp_server_settings(self, settings, language): """Register LSP server settings.""" self.lsp_editor_settings[language] = settings logger.debug('LSP server settings for {!s} are: {!r}'.format( language, settings)) self.lsp_server...