text
stringlengths
81
112k
Remove autosave file for specified file. This function also updates `self.autosave_mapping` and clears the `changed_since_autosave` flag. def remove_autosave_file(self, fileinfo): """ Remove autosave file for specified file. This function also updates `self.autosave_mapping` a...
Get name of autosave file for specified file name. This function uses the dict in `self.name_mapping`. If `filename` is in the mapping, then return the corresponding autosave file name. Otherwise, construct a unique file name and update the mapping. Args: filename (str): or...
Autosave a file. Do nothing if the `changed_since_autosave` flag is not set or the file is newly created (and thus not named by the user). Otherwise, save a copy of the file with the name given by `self.get_autosave_filename()` and clear the `changed_since_autosave` flag. Errors raised ...
Autosave all opened files. def autosave_all(self): """Autosave all opened files.""" for index in range(self.stack.get_stack_count()): self.autosave(index)
Fixtures that returns a temporary CONF element. def tmpconfig(request): """ Fixtures that returns a temporary CONF element. """ SUBFOLDER = tempfile.mkdtemp() CONF = UserConfig('spyder-test', defaults=DEFAULTS, version=CONF_VERSION, ...
Log last error in filename *fname* -- *context*: string (optional) def log_last_error(fname, context=None): """Log last error in filename *fname* -- *context*: string (optional)""" fd = open(fname, 'a') log_time(fd) if context: print("Context", file=fd) print("-------", file=fd) ...
Hack `some_class` to log all method calls into `fname` file. If `prefix` format is not set, each log entry is prefixed with: --[ asked / called / defined ] -- asked - name of `some_class` called - name of class for which a method is called defined - name of class where method i...
This property holds the vertical offset of the scroll flag area relative to the top of the text editor. def offset(self): """This property holds the vertical offset of the scroll flag area relative to the top of the text editor.""" vsb = self.editor.verticalScrollBar() style = v...
Override Qt method. Painting the scroll flag area def paintEvent(self, event): """ Override Qt method. Painting the scroll flag area """ make_flag = self.make_flag_qrect # Fill the whole painting area painter = QPainter(self) painter.fillRect(eve...
Override Qt method def mousePressEvent(self, event): """Override Qt method""" if self.slider and event.button() == Qt.LeftButton: vsb = self.editor.verticalScrollBar() value = self.position_to_value(event.pos().y()) vsb.setValue(value-vsb.pageStep()/2)
Override Qt method. def keyReleaseEvent(self, event): """Override Qt method.""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = False self.update()
Override Qt method def keyPressEvent(self, event): """Override Qt method""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = True self.update()
Return the pixel span height of the scrollbar area in which the slider handle may move def get_scrollbar_position_height(self): """Return the pixel span height of the scrollbar area in which the slider handle may move""" vsb = self.editor.verticalScrollBar() style = vsb.style() ...
Return the value span height of the scrollbar def get_scrollbar_value_height(self): """Return the value span height of the scrollbar""" vsb = self.editor.verticalScrollBar() return vsb.maximum()-vsb.minimum()+vsb.pageStep()
Convert value to position in pixels def value_to_position(self, y): """Convert value to position in pixels""" vsb = self.editor.verticalScrollBar() return (y-vsb.minimum())*self.get_scale_factor()+self.offset
Convert position in pixels to value def position_to_value(self, y): """Convert position in pixels to value""" vsb = self.editor.verticalScrollBar() return vsb.minimum()+max([0, (y-self.offset)/self.get_scale_factor()])
Make flag QRect def make_flag_qrect(self, value): """Make flag QRect""" if self.slider: position = self.value_to_position(value+0.5) # The 0.5 offset is used to align the flags with the center of # their corresponding text edit block before scaling. retu...
Make slider range QRect def make_slider_range(self, cursor_pos): """Make slider range QRect""" # The slider range indicator position follows the mouse vertical # position while its height corresponds to the part of the file that # is currently visible on screen. vsb = self.edit...
Set scroll flag area painter pen and brush colors def set_painter(self, painter, light_color): """Set scroll flag area painter pen and brush colors""" painter.setPen(QColor(light_color).darker(120)) painter.setBrush(QBrush(QColor(light_color)))
Action to be performed on first plugin registration def on_first_registration(self): """Action to be performed on first plugin registration""" self.main.tabify_plugins(self.main.help, self) self.dockwidget.hide()
Register plugin in Spyder's main window def register_plugin(self): """Register plugin in Spyder's main window""" self.profiler.datatree.sig_edit_goto.connect(self.main.editor.load) self.profiler.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.main.add_do...
Run profiler def run_profiler(self): """Run profiler""" if self.main.editor.save(): 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_() pythonpath = self.main.get_spyder_python...
Return physical memory usage (float) Works on Windows platforms only def windows_memory_usage(): """Return physical memory usage (float) Works on Windows platforms only""" from ctypes import windll, Structure, c_uint64, sizeof, byref from ctypes.wintypes import DWORD class MemoryStatus(St...
Return physical memory usage (float) Requires the cross-platform psutil (>=v0.3) library (https://github.com/giampaolo/psutil) def psutil_phymem_usage(): """ Return physical memory usage (float) Requires the cross-platform psutil (>=v0.3) library (https://github.com/giampaolo/psutil) ...
Return color that is lighter or darker than the base color. If base_color.lightness is higher than 128, the returned color is darker otherwise is is lighter. :param base_color: The base color to drift from ;:param factor: drift factor (%) :return A lighter or darker color. def drift_color(base_co...
Gets the list of ParenthesisInfo for specific text block. :param editor: Code editor instance :param block: block to parse def get_block_symbol_data(editor, block): """ Gets the list of ParenthesisInfo for specific text block. :param editor: Code editor instance :param block: block to parse ...
Cache text cursor position and restore it when the wrapped function exits. This decorator can only be used on modes or panels. :param func: wrapped function def keep_tc_pos(func): """ Cache text cursor position and restore it when the wrapped function exits. This decorator can only be us...
Show a wait cursor while the wrapped function is running. The cursor is restored as soon as the function exits. :param func: wrapped function def with_wait_cursor(func): """ Show a wait cursor while the wrapped function is running. The cursor is restored as soon as the function exits. :param ...
Return whether the block of user data is empty. def is_empty(self): """Return whether the block of user data is empty.""" return (not self.breakpoint and not self.code_analysis and not self.todo and not self.bookmarks)
Request a job execution. The job will be executed after the delay specified in the DelayJobRunner contructor elapsed if no other job is requested until then. :param job: job. :type job: callable :param args: job's position arguments :param kwargs: job's keyworde...
Cancels pending requests. def cancel_requests(self): """Cancels pending requests.""" self._timer.stop() self._job = None self._args = None self._kwargs = None
Execute the requested job after the timer has timeout. def _exec_requested_job(self): """Execute the requested job after the timer has timeout.""" self._timer.stop() self._job(*self._args, **self._kwargs)
Moves the text cursor to the specified position. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. ...
Unfold parent fold trigger if the block is collapsed. :param block: Block to unfold. def unfold_if_colapsed(self, block): """Unfold parent fold trigger if the block is collapsed. :param block: Block to unfold. """ try: folding_panel = self._editor.panels.get('Foldi...
Gets the word under cursor using the separators defined by :attr:`spyder.plugins.editor.widgets.codeeditor.CodeEditor.word_separators`. FIXME: This is not working because CodeEditor have no attribute word_separators .. note: Instead of returning the word string, this function returns ...
Selects the word under the **mouse** cursor. :return: A QTextCursor with the word under mouse cursor selected. def word_under_mouse_cursor(self): """ Selects the word under the **mouse** cursor. :return: A QTextCursor with the word under mouse cursor selected. """ edit...
Returns the QTextCursor position. The position is a tuple made up of the line number (0 based) and the column number (0 based). :return: tuple(line, column) def cursor_position(self): """ Returns the QTextCursor position. The position is a tuple made up of the line number (0 ba...
Gets the text of the specified line. :param line_nbr: The line number of the text to get :return: Entire line's text :rtype: str def line_text(self, line_nbr): """ Gets the text of the specified line. :param line_nbr: The line number of the text to get :retur...
Replace an entire line with ``new_text``. :param line_nbr: line number of the line to change. :param new_text: The replacement text. def set_line_text(self, line_nbr, new_text): """ Replace an entire line with ``new_text``. :param line_nbr: line number of the line to change. ...
Removes the last line of the document. def remove_last_line(self): """Removes the last line of the document.""" editor = self._editor text_cursor = editor.textCursor() text_cursor.movePosition(text_cursor.End, text_cursor.MoveAnchor) text_cursor.select(text_cursor.LineUnderCurso...
Removes trailing whitespaces and ensure one single blank line at the end of the QTextDocument. FIXME: It was deprecated in pyqode, maybe It should be deleted def clean_document(self): """ Removes trailing whitespaces and ensure one single blank line at the end of the QTextDocum...
Selects an entire line. :param line: Line to select. If None, the current line will be selected :param apply_selection: True to apply selection on the text editor widget, False to just return the text cursor without setting it on the editor. :return: QTextCursor def sel...
Returns the selected lines boundaries (start line, end line) :return: tuple(int, int) def selection_range(self): """ Returns the selected lines boundaries (start line, end line) :return: tuple(int, int) """ editor = self._editor doc = editor.document() ...
Computes line position on Y-Axis (at the center of the line) from line number. :param line_number: The line number for which we want to know the position in pixels. :return: The center position of the line. def line_pos_from_number(self, line_number): """ ...
Returns the line number from the y_pos. :param y_pos: Y pos in the editor :return: Line number (0 based), -1 if out of range def line_nbr_from_position(self, y_pos): """ Returns the line number from the y_pos. :param y_pos: Y pos in the editor :return: Line number (0 b...
Marks the whole document as dirty to force a full refresh. **SLOW** def mark_whole_doc_dirty(self): """ Marks the whole document as dirty to force a full refresh. **SLOW** """ text_cursor = self._editor.textCursor() text_cursor.select(text_cursor.Document) self._editor.d...
Gets the character that is on the right of the text cursor. :param cursor: QTextCursor that defines the position where the search will start. def get_right_character(self, cursor=None): """ Gets the character that is on the right of the text cursor. :param cursor: QTextCur...
Inserts text at the cursor position. :param text: text to insert :param keep_position: Flag that specifies if the cursor position must be kept. Pass False for a regular insert (the cursor will be at the end of the inserted text). def insert_text(self, text, keep_position=True):...
Clears text cursor selection. def clear_selection(self): """Clears text cursor selection.""" text_cursor = self._editor.textCursor() text_cursor.clearSelection() self._editor.setTextCursor(text_cursor)
Moves the cursor on the right. :param keep_anchor: True to keep anchor (to select text) or False to move the anchor (no selection) :param nb_chars: Number of characters to move. def move_right(self, keep_anchor=False, nb_chars=1): """ Moves the cursor on the right. ...
Performs extended word selection. Extended selection consists in selecting the word under cursor and any other words that are linked by a ``continuation_chars``. :param continuation_chars: the list of characters that may extend a word. def select_extended_word(self, continuation_ch...
Sets the user state, generally used for syntax highlighting. :param block: block to modify :param state: new state value. :return: def set_state(block, state): """ Sets the user state, generally used for syntax highlighting. :param block: block to modify :param...
Sets the block fold level. :param block: block to modify :param val: The new fold level [0-7] def set_fold_lvl(block, val): """ Sets the block fold level. :param block: block to modify :param val: The new fold level [0-7] """ if block is None: ...
Checks if the block is a fold trigger. :param block: block to check :return: True if the block is a fold trigger (represented as a node in the fold panel) def is_fold_trigger(block): """ Checks if the block is a fold trigger. :param block: block to check :r...
Set the block fold trigger flag (True means the block is a fold trigger). :param block: block to set :param val: value to set def set_fold_trigger(block, val): """ Set the block fold trigger flag (True means the block is a fold trigger). :param block: block to ...
Checks if the block is expanded or collased. :param block: QTextBlock :return: False for an open trigger, True for for closed trigger def is_collapsed(block): """ Checks if the block is expanded or collased. :param block: QTextBlock :return: False for an open trigger, ...
Sets the fold trigger state (collapsed or expanded). :param block: The block to modify :param val: The new trigger state (True=collapsed, False=expanded) def set_collapsed(block, val): """ Sets the fold trigger state (collapsed or expanded). :param block: The block to modify ...
:param filename: File to open and get the first little chunk of. :param length: Number of bytes to read, default 1024. :returns: Starting chunk of bytes. def get_starting_chunk(filename, length=1024): """ :param filename: File to open and get the first little chunk of. :param length: Number of byte...
Uses a simplified version of the Perl detection algorithm, based roughly on Eli Bendersky's translation to Python: https://eli.thegreenplace.net/2011/10/19/perls-guess-if-file-is-text-or-binary-implemented-in-python/ This is biased slightly more in favour of deeming files as text files than the Perl al...
Set formatted text value. def set_value(self, value): """Set formatted text value.""" self.value = value if self.isVisible(): self.label_value.setText(value)
Override Qt method to stops timers if widget is not visible. def setVisible(self, value): """Override Qt method to stops timers if widget is not visible.""" if self.timer is not None: if value: self.timer.start(self._interval) else: self.timer.sto...
Set timer interval (ms). def set_interval(self, interval): """Set timer interval (ms).""" self._interval = interval if self.timer is not None: self.timer.setInterval(interval)
Return memory usage. def get_value(self): """Return memory usage.""" from spyder.utils.system import memory_usage text = '%d%%' % memory_usage() return 'Mem ' + text.rjust(3)
Print a warning message on the rich text view def warning(message, css_path=CSS_PATH): """Print a warning message on the rich text view""" env = Environment() env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates')) warning = env.get_template("warning.html") return warning.render(css_path...
Print a usage message on the rich text view def usage(title, message, tutorial_message, tutorial, css_path=CSS_PATH): """Print a usage message on the rich text view""" env = Environment() env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates')) usage = env.get_template("usage.html") retur...
Generate the html_context dictionary for our Sphinx conf file. This is a set of variables to be passed to the Jinja template engine and that are used to control how the webpage is rendered in connection with Sphinx Parameters ---------- name : str Object's name. note : str ...
Runs Sphinx on a docstring and outputs the processed documentation. Parameters ---------- docstring : str a ReST-formatted docstring context : dict Variables to be passed to the layout template to control how its rendered (through the Sphinx variable *html_context*). build...
Generates a Sphinx configuration in `directory`. Parameters ---------- directory : str Base directory to use def generate_configuration(directory): """ Generates a Sphinx configuration in `directory`. Parameters ---------- directory : str Base directory to use """ ...
Update end of line status. def update_eol(self, os_name): """Update end of line status.""" os_name = to_text_string(os_name) value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR") self.set_value(value)
Update encoding of current file. def update_encoding(self, encoding): """Update encoding of current file.""" value = str(encoding).upper() self.set_value(value)
Update cursor position. def update_cursor_position(self, line, index): """Update cursor position.""" value = 'Line {}, Col {}'.format(line + 1, index + 1) self.set_value(value)
Update vcs status. def update_vcs(self, fname, index): """Update vcs status.""" fpath = os.path.dirname(fname) branches, branch, files_modified = get_git_refs(fpath) text = branch if branch else '' if len(files_modified): text = text + ' [{}]'.format(len(files_modif...
Retrieve all Variable Explorer configuration settings. Specifically, return the settings in CONF_SECTION with keys in REMOTE_SETTINGS, and the setting 'dataframe_format'. Returns: dict: settings def get_settings(self): """ Retrieve all Vari...
Change a config option. This function is called if sig_option_changed is received. If the option changed is the dataframe format, then the leading '%' character is stripped (because it can't be stored in the user config). Then, the signal is emitted again, so that the new value is ...
Free memory signal. def free_memory(self): """Free memory signal.""" self.main.free_memory() QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER, lambda: self.main.free_memory()) QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER, ...
Register shell with variable explorer. This function opens a new NamespaceBrowser for browsing the variables in the shell. def add_shellwidget(self, shellwidget): """ Register shell with variable explorer. This function opens a new NamespaceBrowser for browsing the vari...
Import data in current namespace def import_data(self, fname): """Import data in current namespace""" if self.count(): nsb = self.current_widget() nsb.refresh_table() nsb.import_data(filenames=fname) if self.dockwidget and not self.ismaximized: ...
Return True if string is valid def is_valid(self, qstr=None): """Return True if string is valid""" if not self.help.source_is_console(): return True if qstr is None: qstr = self.currentText() if not re.search(r'^[a-zA-Z0-9_\.]*$', str(qstr), 0): retur...
Reimplemented to avoid formatting actions def validate(self, qstr, editing=True): """Reimplemented to avoid formatting actions""" valid = self.is_valid(qstr) if self.hasFocus() and valid is not None: if editing and not valid: # Combo box text is being modified: inval...
Set font def set_font(self, font, fixed_font=None): """Set font""" self.webview.set_font(font, fixed_font=fixed_font)
Set font def set_font(self, font, color_scheme=None): """Set font""" self.editor.set_font(font, color_scheme=color_scheme)
Find tasks in source code (TODO, FIXME, XXX, ...) def find_tasks(source_code): """Find tasks in source code (TODO, FIXME, XXX, ...)""" results = [] for line, text in enumerate(source_code.splitlines()): for todo in re.findall(TASKS_PATTERN, text): todo_text = (todo[-1].strip(' :')....
Check source code with pyflakes Returns an empty list if pyflakes is not installed def check_with_pyflakes(source_code, filename=None): """Check source code with pyflakes Returns an empty list if pyflakes is not installed""" try: if filename is None: filename = '<string>' ...
Return checker executable in the form of a list of arguments for subprocess.Popen def get_checker_executable(name): """Return checker executable in the form of a list of arguments for subprocess.Popen""" if programs.is_program_installed(name): # Checker is properly installed retur...
Check source code with checker defined with *args* (list) Returns an empty list if checker is not installed def check(args, source_code, filename=None, options=None): """Check source code with checker defined with *args* (list) Returns an empty list if checker is not installed""" if args is None: ...
Check source code with pycodestyle def check_with_pep8(source_code, filename=None): """Check source code with pycodestyle""" try: args = get_checker_executable('pycodestyle') results = check(args, source_code, filename=filename, options=['-r']) except Exception: # Never return...
Return image inside a QLabel object def get_image_label(name, default="not_found.png"): """Return image inside a QLabel object""" label = QLabel() label.setPixmap(QPixmap(get_image_path(name, default))) return label
Return QApplication instance Creates it if it doesn't already exist test_time: Time to maintain open the application when testing. It's given in seconds def qapplication(translate=True, test_time=3): """ Return QApplication instance Creates it if it doesn't already exist ...
Select the right file uri scheme according to the operating system def file_uri(fname): """Select the right file uri scheme according to the operating system""" if os.name == 'nt': # Local file if re.search(r'^[a-zA-Z]:', fname): return 'file:///' + fname # UNC based p...
Install Qt translator to the QApplication instance def install_translator(qapp): """Install Qt translator to the QApplication instance""" global QT_TRANSLATOR if QT_TRANSLATOR is None: qt_translator = QTranslator() if qt_translator.load("qt_"+QLocale.system().name(), ...
Return keybinding def keybinding(attr): """Return keybinding""" ks = getattr(QKeySequence, attr) return from_qvariant(QKeySequence.keyBindings(ks)[0], str)
Extract url list from MIME data extlist: for example ('.py', '.pyw') def mimedata2url(source, extlist=None): """ Extract url list from MIME data extlist: for example ('.py', '.pyw') """ pathlist = [] if source.hasUrls(): for url in source.urls(): path = _process...
Convert QKeyEvent instance into a tuple def keyevent2tuple(event): """Convert QKeyEvent instance into a tuple""" return (event.type(), event.key(), event.modifiers(), event.text(), event.isAutoRepeat(), event.count())
Create a QToolButton def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, autoraise=True, text_beside_icon=False): """Create a QToolButton""" button = QToolButton(parent) if text is not None: but...
Create a QToolButton directly from a QAction object def action2button(action, autoraise=True, text_beside_icon=False, parent=None): """Create a QToolButton directly from a QAction object""" if parent is None: parent = action.parent() button = QToolButton(parent) button.setDefaultAction(act...
Enable/disable actions def toggle_actions(actions, enable): """Enable/disable actions""" if actions is not None: for action in actions: if action is not None: action.setEnabled(enable)
Create a QAction def create_action(parent, text, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, data=None, menurole=None, context=Qt.WindowShortcut): """Create a QAction""" action = SpyderAction(text, parent) if triggered is not None: act...
Add the shortcut associated with a given action to its tooltip def add_shortcut_to_tooltip(action, context, name): """Add the shortcut associated with a given action to its tooltip""" action.setToolTip(action.toolTip() + ' (%s)' % get_shortcut(context=context, name=name))
Add actions to a QMenu or a QToolBar. def add_actions(target, actions, insert_before=None): """Add actions to a QMenu or a QToolBar.""" previous_action = None target_actions = list(target.actions()) if target_actions: previous_action = target_actions[-1] if previous_action.isSepar...