text stringlengths 81 112k |
|---|
Return layout state
def get_layout_settings(self):
"""Return layout state"""
splitsettings = self.editorwidget.editorsplitter.get_layout_settings()
return dict(size=(self.window_size.width(), self.window_size.height()),
pos=(self.pos().x(), self.pos().y()),
... |
Restore layout state
def set_layout_settings(self, settings):
"""Restore layout state"""
size = settings.get('size')
if size is not None:
self.resize( QSize(*size) )
self.window_size = self.size()
pos = settings.get('pos')
if pos is not None:
... |
A file was saved in editorstack, this notifies others
def file_saved_in_editorstack(self, editorstack_id_str,
original_filename, filename):
"""A file was saved in editorstack, this notifies others"""
for editorstack in self.editorstacks:
if str(id(edito... |
A file was renamed in data in editorstack, this notifies others
def file_renamed_in_data_in_editorstack(self, editorstack_id_str,
original_filename, filename):
"""A file was renamed in data in editorstack, this notifies others"""
for editorstack in self.ed... |
Find in files callback
def findinfiles_callback(self):
"""Find in files callback"""
widget = QApplication.focusWidget()
if not self.ismaximized:
self.dockwidget.setVisible(True)
self.dockwidget.raise_()
text = ''
try:
if widget.has_sel... |
Register plugin in Spyder's main window
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.main.add_dockwidget(self)
self.findinfiles.result_browser.sig_edit_goto.connect(
self.main.editor.load)
sel... |
Perform actions before parent main window is closed
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.findinfiles.closing_widget() # stop search thread and clean-up
options = self.findinfiles.find_options.get_options(to_save=True)
... |
Draw the fold region when the mouse is over and non collapsed
indicator.
:param top: Top position
:param block: Current block.
:param painter: QPainter
def _draw_fold_region_background(self, block, painter):
"""
Draw the fold region when the mouse is over and non collap... |
Draw the background rectangle using the current style primitive color.
:param rect: The fold zone rect to draw
:param painter: The widget's painter.
def _draw_rect(self, rect, painter):
"""
Draw the background rectangle using the current style primitive color.
:param rect: Th... |
Draw the fold indicator/trigger (arrow).
:param top: Top position
:param mouse_over: Whether the mouse is over the indicator
:param collapsed: Whether the trigger is collapsed or not.
:param painter: QPainter
def _draw_fold_indicator(self, top, mouse_over, collapsed, painter):
... |
Find parent scope, if the block is not a fold trigger.
def find_parent_scope(block):
"""Find parent scope, if the block is not a fold trigger."""
original = block
if not TextBlockHelper.is_fold_trigger(block):
# search level of next non blank line
while block.text().stri... |
Clear scope decorations (on the editor)
def _clear_scope_decos(self):
"""Clear scope decorations (on the editor)"""
for deco in self._scope_decos:
self.editor.decorations.remove(deco)
self._scope_decos[:] = [] |
Gets the base scope highlight color (derivated from the editor
background)
For lighter themes will be a darker color,
and for darker ones will be a lighter color
def _get_scope_highlight_color(self):
"""
Gets the base scope highlight color (derivated from the editor
ba... |
Create a decoration and add it to the editor.
Args:
start (int) start line of the decoration
end (int) end line of the decoration
def _decorate_block(self, start, end):
"""
Create a decoration and add it to the editor.
Args:
start (int) start line o... |
Highlights the current fold scope.
:param block: Block that starts the current fold scope.
def _highlight_block(self, block):
"""
Highlights the current fold scope.
:param block: Block that starts the current fold scope.
"""
scope = FoldScope(block)
if (self._c... |
Detect mouser over indicator and highlight the current scope in the
editor (up and down decoration arround the foldable text when the mouse
is over an indicator).
:param event: event
def mouseMoveEvent(self, event):
"""
Detect mouser over indicator and highlight the current sco... |
Folds/unfolds the pressed indicator if any.
def mousePressEvent(self, event):
"""Folds/unfolds the pressed indicator if any."""
if self._mouse_over_line is not None:
block = self.editor.document().findBlockByNumber(
self._mouse_over_line)
self.toggle_fold_trigger... |
Show the block previous blank lines
def _show_previous_blank_lines(block):
"""
Show the block previous blank lines
"""
# set previous blank lines visibles
pblock = block.previous()
while (pblock.text().strip() == '' and
pblock.blockNumber() >= 0):
... |
Refresh decorations colors. This function is called by the syntax
highlighter when the style changed so that we may update our
decorations colors according to the new style.
def refresh_decorations(self, force=False):
"""
Refresh decorations colors. This function is called by the syntax... |
Refrehes editor content and scollbars.
We generate a fake resize event to refresh scroll bar.
We have the same problem as described here:
http://www.qtcentre.org/threads/44803 and we apply the same solution
(don't worry, there is no visual effect, the editor does not grow up
at... |
Collapses all triggers and makes all blocks with fold level > 0
invisible.
def collapse_all(self):
"""
Collapses all triggers and makes all blocks with fold level > 0
invisible.
"""
self._clear_block_deco()
block = self.editor.document().firstBlock()
last... |
Clear the folded block decorations.
def _clear_block_deco(self):
"""Clear the folded block decorations."""
for deco in self._block_decos:
self.editor.decorations.remove(deco)
self._block_decos[:] = [] |
Expands all fold triggers.
def expand_all(self):
"""Expands all fold triggers."""
block = self.editor.document().firstBlock()
while block.isValid():
TextBlockHelper.set_collapsed(block, False)
block.setVisible(True)
block = block.next()
self._clear_bl... |
Toggle the current fold trigger.
def _on_action_toggle(self):
"""Toggle the current fold trigger."""
block = FoldScope.find_parent_scope(self.editor.textCursor().block())
self.toggle_fold_trigger(block) |
Highlight the scope of the current caret position.
This get called only if :attr:`
spyder.widgets.panels.FoldingPanel.highlight_care_scope` is True.
def _highlight_caret_scope(self):
"""
Highlight the scope of the current caret position.
This get called only if :attr:`
... |
Add options to corner menu.
def set_menu_actions(self, menu_actions):
"""Add options to corner menu."""
if self.menu_actions is not None:
add_actions(self.menu, self.menu_actions) |
Refresh tabwidget.
def refresh(self):
"""Refresh tabwidget."""
if self.tabwidget.count():
editor = self.tabwidget.currentWidget()
else:
editor = None
self.find_widget.set_editor(editor) |
Move tab.
(tabs themselves have already been moved by the history.tabwidget)
def move_tab(self, index_from, index_to):
"""
Move tab.
(tabs themselves have already been moved by the history.tabwidget)
"""
filename = self.filenames.pop(index_from)
editor = self.e... |
Add new history tab.
Args:
filename (str): file to be loaded in a new tab.
def add_history(self, filename, color_scheme, font, wrap):
"""
Add new history tab.
Args:
filename (str): file to be loaded in a new tab.
"""
filename = encoding.to_unico... |
Append an entry to history filename.
Args:
filename (str): file to be updated in a new tab.
command (str): line to be added.
go_to_eof (bool): scroll to the end of file.
def append_to_history(self, filename, command, go_to_eof):
"""
Append an entry to histor... |
Call function req and then emit its results to the LSP server.
def request(req=None, method=None, requires_response=True):
"""Call function req and then emit its results to the LSP server."""
if req is None:
return functools.partial(request, method=method,
requires_resp... |
Class decorator that allows to map LSP method names to class methods.
def class_register(cls):
"""Class decorator that allows to map LSP method names to class methods."""
cls.handler_registry = {}
for method_name in dir(cls):
method = getattr(cls, method_name)
if hasattr(method, '_handle'):... |
Update font from Preferences
def update_font(self):
"""Update font from Preferences"""
font = self.get_plugin_font()
for client in self.clients:
client.set_font(font) |
Apply configuration file's plugin settings
def apply_plugin_settings(self, options):
"""Apply configuration file's plugin settings"""
font_n = 'plugin_font'
font_o = self.get_plugin_font()
help_n = 'connect_to_oi'
help_o = CONF.get('help', 'connect/ipython_console')
... |
Toggle view
def toggle_view(self, checked):
"""Toggle view"""
if checked:
self.dockwidget.show()
self.dockwidget.raise_()
# Start a client in case there are none shown
if not self.clients:
if self.main.is_setting_up:
... |
Perform actions before parent main window is closed
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.mainwindow_close = True
for client in self.clients:
client.shutdown()
client.remove_stderr_file()
... |
Refresh tabwidget
def refresh_plugin(self):
"""Refresh tabwidget"""
client = None
if self.tabwidget.count():
client = self.tabwidget.currentWidget()
# Decide what to show for each client
if client.info_page != client.blank_page:
# Sho... |
Return a list of actions related to plugin.
def get_plugin_actions(self):
"""Return a list of actions related to plugin."""
create_client_action = create_action(
self,
_("New console (default settings)"),
... |
Register plugin in Spyder's main window
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.main.add_dockwidget(self)
self.focus_changed.connect(self.main.plugin_focus_changed)
self.edit_goto.connect(self.main.editor.load)
self.edit_goto[str, int... |
Return current client with focus, if any
def get_focus_client(self):
"""Return current client with focus, if any"""
widget = QApplication.focusWidget()
for client in self.get_clients():
if widget is client or widget is client.get_control():
return client |
Run script in current or dedicated client
def run_script(self, filename, wdir, args, debug, post_mortem,
current_client, clear_variables):
"""Run script in current or dedicated client"""
norm = lambda text: remove_backslashes(to_text_string(text))
# Run Cython files in ... |
Run cell in current or dedicated client.
def run_cell(self, code, cell_name, filename, run_cell_copy):
"""Run cell in current or dedicated client."""
def norm(text):
return remove_backslashes(to_text_string(text))
self.run_cell_filename = filename
# Select client ... |
Set current client working directory.
def set_current_client_working_directory(self, directory):
"""Set current client working directory."""
shellwidget = self.get_current_shellwidget()
if shellwidget is not None:
shellwidget.set_cwd(directory) |
Set current working directory.
In the workingdirectory and explorer plugins.
def set_working_directory(self, dirname):
"""Set current working directory.
In the workingdirectory and explorer plugins.
"""
if dirname:
self.main.workingdirectory.chdir(dirname, refr... |
Execute code instructions.
def execute_code(self, lines, current_client=True, clear_variables=False):
"""Execute code instructions."""
sw = self.get_current_shellwidget()
if sw is not None:
if sw._reading:
pass
else:
if not current_... |
Create a new client
def create_new_client(self, give_focus=True, filename='', is_cython=False,
is_pylab=False, is_sympy=False, given_name=None):
"""Create a new client"""
self.master_clients += 1
client_id = dict(int_id=to_text_string(self.master_clients),
... |
Create a client connected to an existing kernel
def create_client_for_kernel(self):
"""Create a client connected to an existing kernel"""
connect_output = KernelConnectionDialog.get_connection_parameters(self)
(connection_file, hostname, sshkey, password, ok) = connect_output
if not... |
Connect a client to its kernel
def connect_client_to_kernel(self, client, is_cython=False,
is_pylab=False, is_sympy=False):
"""Connect a client to its kernel"""
connection_file = client.connection_file
stderr_handle = None if self.test_no_stderr else client.... |
Handle %edit magic petitions.
def edit_file(self, filename, line):
"""Handle %edit magic petitions."""
if encoding.is_text_file(filename):
# The default line number sent by ipykernel is always the last
# one, but we prefer to use the first.
self.edit_goto.emit(f... |
Generate a Trailets Config instance for shell widgets using our
config system
This lets us create each widget with its own config
def config_options(self):
"""
Generate a Trailets Config instance for shell widgets using our
config system
This lets us create eac... |
Python and IPython versions used by clients
def interpreter_versions(self):
"""Python and IPython versions used by clients"""
if CONF.get('main_interpreter', 'default'):
from IPython.core import release
versions = dict(
python_version = sys.version.split("\n... |
Additional options for shell widgets that are not defined
in JupyterWidget config options
def additional_options(self, is_pylab=False, is_sympy=False):
"""
Additional options for shell widgets that are not defined
in JupyterWidget config options
"""
options = dict(... |
Register new client
def register_client(self, client, give_focus=True):
"""Register new client"""
client.configure_shellwidget(give_focus=give_focus)
# Local vars
shellwidget = client.shellwidget
control = shellwidget._control
page_control = shellwidget._page_con... |
Close client tab from index or widget (or close current tab)
def close_client(self, index=None, client=None, force=False):
"""Close client tab from index or widget (or close current tab)"""
if not self.tabwidget.count():
return
if client is not None:
index = self.ta... |
Return client index from id
def get_client_index_from_id(self, client_id):
"""Return client index from id"""
for index, client in enumerate(self.clients):
if id(client) == client_id:
return index |
Get all other clients that are connected to the same kernel as `client`
def get_related_clients(self, client):
"""
Get all other clients that are connected to the same kernel as `client`
"""
related_clients = []
for cl in self.get_clients():
if cl.connection_fi... |
Close all clients related to *client*, except itself
def close_related_clients(self, client):
"""Close all clients related to *client*, except itself"""
related_clients = self.get_related_clients(client)
for cl in related_clients:
self.close_client(client=cl, force=True) |
Restart the console
This is needed when we switch projects to update PYTHONPATH
and the selected interpreter
def restart(self):
"""
Restart the console
This is needed when we switch projects to update PYTHONPATH
and the selected interpreter
"""
... |
Python debugger has just stopped at frame (fname, lineno)
def pdb_has_stopped(self, fname, lineno, shellwidget):
"""Python debugger has just stopped at frame (fname, lineno)"""
# This is a unique form of the edit_goto signal that is intended to
# prevent keyboard input from accidentally ente... |
Create a client with its cwd pointing to path.
def create_client_from_path(self, path):
"""Create a client with its cwd pointing to path."""
self.create_new_client()
sw = self.get_current_shellwidget()
sw.set_cwd(path) |
Create a client to execute code related to a file.
def create_client_for_file(self, filename, is_cython=False):
"""Create a client to execute code related to a file."""
# Create client
self.create_new_client(filename=filename, is_cython=is_cython)
# Don't increase the count of mas... |
Get client associated with a given file.
def get_client_for_file(self, filename):
"""Get client associated with a given file."""
client = None
for idx, cl in enumerate(self.get_clients()):
if self.filenames[idx] == filename:
self.tabwidget.setCurrentIndex(idx)
... |
Set elapsed time for slave clients.
def set_elapsed_time(self, client):
"""Set elapsed time for slave clients."""
related_clients = self.get_related_clients(client)
for cl in related_clients:
if cl.timer is not None:
client.create_time_label()
c... |
Tunnel connections to a kernel via ssh.
Remote ports are specified in the connection info ci.
def tunnel_to_kernel(self, connection_info, hostname, sshkey=None,
password=None, timeout=10):
"""
Tunnel connections to a kernel via ssh.
Remote ports are spe... |
Create a kernel spec for our own kernels
def create_kernel_spec(self, is_cython=False,
is_pylab=False, is_sympy=False):
"""Create a kernel spec for our own kernels"""
# Before creating our kernel spec, we always need to
# set this value in spyder.ini
CONF... |
Create kernel manager and client.
def create_kernel_manager_and_kernel_client(self, connection_file,
stderr_handle,
is_cython=False,
is_pylab=False,
... |
Restart kernel of current client.
def restart_kernel(self):
"""Restart kernel of current client."""
client = self.get_current_client()
if client is not None:
self.switch_to_plugin()
client.restart_kernel() |
Reset kernel of current client.
def reset_kernel(self):
"""Reset kernel of current client."""
client = self.get_current_client()
if client is not None:
self.switch_to_plugin()
client.reset_namespace() |
Interrupt kernel of current client.
def interrupt_kernel(self):
"""Interrupt kernel of current client."""
client = self.get_current_client()
if client is not None:
self.switch_to_plugin()
client.stop_button_click_handler() |
Update actions following the execution state of the kernel.
def update_execution_state_kernel(self):
"""Update actions following the execution state of the kernel."""
client = self.get_current_client()
if client is not None:
executing = client.stop_button.isEnabled()
... |
Connect an external kernel to the Variable Explorer and Help, if
it is a Spyder kernel.
def connect_external_kernel(self, shellwidget):
"""
Connect an external kernel to the Variable Explorer and Help, if
it is a Spyder kernel.
"""
sw = shellwidget
kc = sh... |
Add tab
def add_tab(self, widget, name, filename=''):
"""Add tab"""
self.clients.append(widget)
index = self.tabwidget.addTab(widget, name)
self.filenames.insert(index, filename)
self.tabwidget.setCurrentIndex(index)
if self.dockwidget and not self.main.is_setting_... |
Move tab (tabs themselves have already been moved by the tabwidget)
def move_tab(self, index_from, index_to):
"""
Move tab (tabs themselves have already been moved by the tabwidget)
"""
filename = self.filenames.pop(index_from)
client = self.clients.pop(index_from)
... |
Generate a file name without ambiguation.
def disambiguate_fname(self, fname):
"""Generate a file name without ambiguation."""
files_path_list = [filename for filename in self.filenames
if filename]
return sourcecode.disambiguate_fname(files_path_list, fname) |
Update the text from the tabs.
def update_tabs_text(self):
"""Update the text from the tabs."""
# This is needed to prevent that hanged consoles make reference
# to an index that doesn't exist. See issue 4881
try:
for index, fname in enumerate(self.filenames):
... |
Rename client's tab
def rename_client_tab(self, client, given_name):
"""Rename client's tab"""
index = self.get_client_index_from_id(id(client))
if given_name is not None:
client.given_name = given_name
self.tabwidget.setTabText(index, client.get_name()) |
Rename tabs after a change in name.
def rename_tabs_after_change(self, given_name):
"""Rename tabs after a change in name."""
client = self.get_current_client()
# Prevent renames that want to assign the same name of
# a previous tab
repeated = False
for cl in sel... |
Trigger the tab name editor.
def tab_name_editor(self):
"""Trigger the tab name editor."""
index = self.tabwidget.currentIndex()
self.tabwidget.tabBar().tab_name_editor.edit_tab(index) |
Go to error if relevant
def go_to_error(self, text):
"""Go to error if relevant"""
match = get_error_match(to_text_string(text))
if match:
fname, lnb = match.groups()
if ("<ipython-input-" in fname and
self.run_cell_filename is not None):
... |
Show intro to IPython help
def show_intro(self):
"""Show intro to IPython help"""
from IPython.core.usage import interactive_usage
self.main.help.show_rich_text(interactive_usage) |
Show qtconsole help
def show_guiref(self):
"""Show qtconsole help"""
from qtconsole.usage import gui_reference
self.main.help.show_rich_text(gui_reference, collapse=True) |
Show IPython Cheat Sheet
def show_quickref(self):
"""Show IPython Cheat Sheet"""
from IPython.core.usage import quick_reference
self.main.help.show_plain_text(quick_reference) |
Generate a new connection file
Taken from jupyter_client/console_app.py
Licensed under the BSD license
def _new_connection_file(self):
"""
Generate a new connection file
Taken from jupyter_client/console_app.py
Licensed under the BSD license
"""
... |
Remove stderr files left by previous Spyder instances.
This is only required on Windows because we can't
clean up stderr files while Spyder is running on it.
def _remove_old_stderr_files(self):
"""
Remove stderr files left by previous Spyder instances.
This is only requ... |
Rotate the kill ring, then yank back the new top.
Returns
-------
A text string or None.
def rotate(self):
""" Rotate the kill ring, then yank back the new top.
Returns
-------
A text string or None.
"""
self._index -= 1
if self._index >... |
Kills the text selected by the give cursor.
def kill_cursor(self, cursor):
""" Kills the text selected by the give cursor.
"""
text = cursor.selectedText()
if text:
cursor.removeSelectedText()
self.kill(text) |
Yank back the most recently killed text.
def yank(self):
""" Yank back the most recently killed text.
"""
text = self._ring.yank()
if text:
self._skip_cursor = True
cursor = self._text_edit.textCursor()
cursor.insertText(text)
self._prev_y... |
Show files in external file explorer
Args:
fnames (list): Names of files to show.
def show_in_external_file_explorer(fnames=None):
"""Show files in external file explorer
Args:
fnames (list): Names of files to show.
"""
if not isinstance(fnames, (tuple, list)):
f... |
Normalize path fixing case, making absolute and removing symlinks
def fixpath(path):
"""Normalize path fixing case, making absolute and removing symlinks"""
norm = osp.normcase if os.name == 'nt' else osp.normpath
return norm(osp.abspath(osp.realpath(path))) |
Create a new Python script
def create_script(fname):
"""Create a new Python script"""
text = os.linesep.join(["# -*- coding: utf-8 -*-", "", ""])
try:
encoding.write(to_text_string(text), fname, 'utf-8')
except EnvironmentError as error:
QMessageBox.critical(_("Save Error"),
... |
List files and directories
def listdir(path, include=r'.', exclude=r'\.pyc$|^\.', show_all=False,
folders_only=False):
"""List files and directories"""
namelist = []
dirlist = [to_text_string(osp.pardir)]
for item in os.listdir(to_text_string(path)):
if re.search(exclude, item... |
Return True if path has subdirectories
def has_subdirectories(path, include, exclude, show_all):
"""Return True if path has subdirectories"""
try:
# > 1 because of '..'
return len( listdir(path, include, exclude,
show_all, folders_only=True) ) > 1
except (I... |
Reimplement Qt method
def icon(self, icontype_or_qfileinfo):
"""Reimplement Qt method"""
if isinstance(icontype_or_qfileinfo, QFileIconProvider.IconType):
return super(IconProvider, self).icon(icontype_or_qfileinfo)
else:
qfileinfo = icontype_or_qfileinfo
... |
Setup filesystem model
def setup_fs_model(self):
"""Setup filesystem model"""
filters = QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot
self.fsmodel = QFileSystemModel(self)
self.fsmodel.setFilter(filters)
self.fsmodel.setNameFilterDisables(False) |
Setup view
def setup_view(self):
"""Setup view"""
self.install_model()
self.fsmodel.directoryLoaded.connect(
lambda: self.resizeColumnToContents(0))
self.setAnimated(False)
self.setSortingEnabled(True)
self.sortByColumn(0, Qt.AscendingOrder)
s... |
Set single click to open items.
def set_single_click_to_open(self, value):
"""Set single click to open items."""
self.single_click_to_open = value
self.parent_widget.sig_option_changed.emit('single_click_to_open',
value) |
Set name filters
def set_name_filters(self, name_filters):
"""Set name filters"""
self.name_filters = name_filters
self.fsmodel.setNameFilters(name_filters) |
Toggle 'show all files' state
def set_show_all(self, state):
"""Toggle 'show all files' state"""
if state:
self.fsmodel.setNameFilters([])
else:
self.fsmodel.setNameFilters(self.name_filters) |
Return filename associated with *index*
def get_filename(self, index):
"""Return filename associated with *index*"""
if index:
return osp.normpath(to_text_string(self.fsmodel.filePath(index))) |
Return selected filenames
def get_selected_filenames(self):
"""Return selected filenames"""
if self.selectionMode() == self.ExtendedSelection:
if self.selectionModel() is None:
return []
return [self.get_filename(idx) for idx in
self.se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.