INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Reimplement Qt method Fix PyQt4 bug on Windows and Python 3
def toPlainText(self): """ Reimplement Qt method Fix PyQt4 bug on Windows and Python 3 """ # Fix what appears to be a PyQt4 bug when getting file # contents under Windows and PY3. This bug leads to # corruptions when saving files with certain combinations ...
Return selected text as a processed text, to be executable in a Python/IPython interpreter
def get_selection_as_executable_code(self): """Return selected text as a processed text, to be executable in a Python/IPython interpreter""" ls = self.get_line_separator() _indent = lambda line: len(line)-len(line.lstrip()) line_from, line_to = self.get_selection_bounds(...
Return True if cursor (or text block) is on a block separator
def is_cell_separator(self, cursor=None, block=None): """Return True if cursor (or text block) is on a block separator""" assert cursor is not None or block is not None if cursor is not None: cursor0 = QTextCursor(cursor) cursor0.select(QTextCursor.BlockUnderCursor) ...
Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating if the entire file is selected
def select_current_cell(self): """Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating if the entire file is selected""" cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) ...
Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns -the textCursor -a boolean indicating if the entire file is selected -a boolean indicating if the entire visible portion of the file is selected
def select_current_cell_in_visible_portion(self): """Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns -the textCursor -a boolean indicating if the entire file is selected -a boolean indicating ...
Go to the next cell of lines
def go_to_next_cell(self): """Go to the next cell of lines""" cursor = self.textCursor() cursor.movePosition(QTextCursor.NextBlock) cur_pos = prev_pos = cursor.position() while not self.is_cell_separator(cursor): # Moving to the next code cell curso...
Go to the previous cell of lines
def go_to_previous_cell(self): """Go to the previous cell of lines""" cursor = self.textCursor() cur_pos = prev_pos = cursor.position() if self.is_cell_separator(cursor): # Move to the previous cell cursor.movePosition(QTextCursor.PreviousBlock) ...
Restore cursor selection from position bounds
def __restore_selection(self, start_pos, end_pos): """Restore cursor selection from position bounds""" cursor = self.textCursor() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) self.setTextCursor(cursor)
Duplicate current line or selected text
def __duplicate_line_or_selection(self, after_current_line=True): """Duplicate current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() if to_text_string(cursor.selectedText()): cursor.setPo...
Move current line or selected text
def __move_line_or_selection(self, after_current_line=True): """Move current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() last_line = False # ------ Select text # Get selection ...
Go to the end of the current line and create a new line
def go_to_new_line(self): """Go to the end of the current line and create a new line""" self.stdkey_end(False, False) self.insert_text(self.get_line_separator())
Extend current selection to complete lines
def extend_selection_to_complete_lines(self): """Extend current selection to complete lines""" cursor = self.textCursor() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) ...
Delete current line
def delete_line(self): """Delete current line""" cursor = self.textCursor() if self.has_selected_text(): self.extend_selection_to_complete_lines() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) ...
Unselect read-only parts in shell, like prompt
def truncate_selection(self, position_from): """Unselect read-only parts in shell, like prompt""" position_from = self.get_position(position_from) cursor = self.textCursor() start, end = cursor.selectionStart(), cursor.selectionEnd() if start < end: start = max(...
In shell, avoid editing text except between prompt and EOF
def restrict_cursor_position(self, position_from, position_to): """In shell, avoid editing text except between prompt and EOF""" position_from = self.get_position(position_from) position_to = self.get_position(position_to) cursor = self.textCursor() cursor_position = cursor....
Hide calltip when necessary
def hide_tooltip_if_necessary(self, key): """Hide calltip when necessary""" try: calltip_char = self.get_character(self.calltip_position) before = self.is_cursor_before(self.calltip_position, char_offset=1) other = key ...
Smart HOME feature: cursor is first moved at indentation position, then at the start of the line
def stdkey_home(self, shift, ctrl, prompt_pos=None): """Smart HOME feature: cursor is first moved at indentation position, then at the start of the line""" move_mode = self.__get_move_mode(shift) if ctrl: self.moveCursor(QTextCursor.Start, move_mode) else: ...
Reimplement Qt method
def mousePressEvent(self, event): """Reimplement Qt method""" if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() self.setFocus() event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), ...
Reimplemented to handle focus
def focusInEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() self.focus_in.emit() self.highlight_current_cell() QPlainTextEdit.focusInEvent(self, event)
Reimplemented to handle focus
def focusOutEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() QPlainTextEdit.focusOutEvent(self, event)
Reimplemented to emit zoom in/out signals when Ctrl is pressed
def wheelEvent(self, event): """Reimplemented to emit zoom in/out signals when Ctrl is pressed""" # This feature is disabled on MacOS, see Issue 1510 if sys.platform != 'darwin': if event.modifiers() & Qt.ControlModifier: if hasattr(event, 'angleDelta'): ...
Convert options into commands return commands, message
def get_options(argv=None): """ Convert options into commands return commands, message """ parser = argparse.ArgumentParser(usage="spyder [options] files") parser.add_argument('--new-instance', action='store_true', default=False, help="Run a new instance of Spyder, even if ...
Set a list of files opened by the project.
def set_recent_files(self, recent_files): """Set a list of files opened by the project.""" for recent_file in recent_files[:]: if not os.path.isfile(recent_file): recent_files.remove(recent_file) try: self.CONF[WORKSPACE].set('main', 'recent_files', ...
Return a list of files opened by the project.
def get_recent_files(self): """Return a list of files opened by the project.""" try: recent_files = self.CONF[WORKSPACE].get('main', 'recent_files', default=[]) except EnvironmentError: return [] for rec...
Set project root path.
def set_root_path(self, root_path): """Set project root path.""" if self.name is None: self.name = osp.basename(root_path) self.root_path = to_text_string(root_path) config_path = self.__get_project_config_path() if osp.exists(config_path): self.loa...
Rename project and rename its root path accordingly.
def rename(self, new_name): """Rename project and rename its root path accordingly.""" old_name = self.name self.name = new_name pypath = self.relative_pythonpath # ?? self.root_path = self.root_path[:-len(old_name)]+new_name self.relative_pythonpath = pypath # ??...
Start pydoc server
def initialize(self): """Start pydoc server""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() self.start_server()
Start pydoc server
def start_server(self): """Start pydoc server""" if self.server is None: self.port = select_port(default_port=self.DEFAULT_PORT) self.set_home_url('http://localhost:%d/' % self.port) elif self.server.isRunning(): self.server.server_started.disconnect(sel...
Convert text address into QUrl object
def text_to_url(self, text): """Convert text address into QUrl object""" if text.startswith('/'): text = text[1:] return QUrl(self.home_url.toString()+text+'.html')
Instruct current editorstack to autosave files where necessary.
def do_autosave(self): """Instruct current editorstack to autosave files where necessary.""" logger.debug('Autosave triggered') stack = self.editor.get_current_editorstack() stack.autosave.autosave_all() self.start_autosave_timer()
Offer to recover files from autosave.
def try_recover_from_autosave(self): """Offer to recover files from autosave.""" autosave_dir = get_conf_path('autosave') autosave_mapping = CONF.get('editor', 'autosave_mapping', {}) dialog = RecoveryDialog(autosave_dir, autosave_mapping, parent=self.edit...
Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored
def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored """ basename = osp.b...
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` and clears the `changed_since_autosave` flag. """ filename = fileinfo.filename if filename not in self.name_mapping: ...
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...
def get_autosave_filename(self, filename): """ 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 up...
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 ...
def autosave(self, index): """ 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 th...
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, subfolder=SUBFOLDER, raw_mo...
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) print("", file=fd) if PY2: print(u' '....
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...
def log_methods_calls(fname, some_class, prefix=None): """ 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 whi...
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 = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in which t...
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(event.rect(), self.editor.sideareas_color) # Paint wa...
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() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in w...
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. return QRect(self.FLA...
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.editor.verticalScrollBar() ...
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_dockwidget(self) profiler_act = cr...
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_pythonpath() runconf = get...
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(Structure): _fields_ = [('dwLength', DWORD), ('...
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) """ import psutil # This is needed to avoid a deprecation warning error with # newer psutil versions try: pe...
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_color, factor=110): """ 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 (%) :retur...
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 """ def list_symbols(editor, block, character): """ Retuns a list of symbols found in the block text ...
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 used on modes or panels. :param func: wrapped function """ @functools.wraps(func) def wrapper(editor, *args, **kwds): """ Decorator """ sb = ...
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 func: wrapped function """ @functools.wraps(func) def wrapper(*args, **kwargs): QApplication.setOverrideCursor( QCursor(...
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...
def request_job(self, job, *args, **kwargs): """ 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 arg...
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. ...
def goto_line(self, line, column=0, end_column=0, move=True, word=''): """ 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 curso...
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('FoldingPanel') except KeyError: pass else: from spyder.plugi...
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 ...
def word_under_cursor(self, select_whole_word=False, text_cursor=None): """ 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 wor...
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. """ editor = self._editor text_cursor = editor.cursorForPosition(editor._last_mouse_pos) text_cursor = self.word_...
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 based) and the column number (0 based). :return: tuple(line, column) """ return (self._editor.textCursor().blockNumber(), self._editor.t...
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 :return: Entire line's text :rtype: str """ doc = self._editor.document() block = doc.findBlockByNumber(line_nbr) return b...
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. :param new_text: The replacement text. """ editor = self._editor text_cursor = self._move_cursor_to(line_nbr) t...
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.LineUnderCursor) text_cursor.removeSelectedTex...
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 QTextDocument. FIXME: It was deprecated in pyqode, maybe It should be deleted """ editor = self._editor value = editor.verticalScrollBar().value() ...
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 select_whole_line(self, line=None, apply_selection=True): """ 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 w...
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() start = doc.findBlock( editor.textCursor().selectionStart()).blockNumber() e...
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): """ 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 l...
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 based), -1 if out of range """ editor = self._editor height = editor.fontMetrics().height() for top, line, block...
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.document().markContentsDirty(text_cursor.selectionStart(), ...
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: QTextCursor that defines the position where the search will start. """ next_char = self.get_right_word(cursor=cursor) if len(next_char):...
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): """ 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 ...
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. :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. """ text_cursor = self._...
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_chars=('.',)): """ 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...
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 state: new state value. :return: """ if block is None: return user_state = block.userState() if user_sta...
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: return state = block.userState() if state == -1: state = 0 if val >= 0x3F...
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 :return: True if the block is a fold trigger (represented as a node in the fold panel) """ if block is None: return False state = block.use...
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 set :param val: value to set """ if block is None: return state = block.userState() if state == -1: ...
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, True for for closed trigger """ if block is None: return False state = block.userState() if state == -1: ...
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 val: The new trigger state (True=collapsed, False=expanded) """ if block is None: return state = block.userState() ...
: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 bytes to read, default 1024. :returns: Starting chunk of bytes. """ # Ensure we open the file in binary mode with open(filename, 'rb') as f: ch...
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...
def is_binary_string(bytes_to_check): """ 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 o...
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.stop() super(BaseTimerStatus, self).setVisible(value)
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=css_path, text=message)
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") return usage.render(css_path=css_path, title=title...
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 ...
def generate_context(name='', argspec='', note='', math=False, collapse=False, img_path='', css_path=CSS_PATH): """ 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 h...
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...
def sphinxify(docstring, context, buildername='html'): """ 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 ...