INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Add a plugin to the File Switcher. | def add_to_fileswitcher(self, plugin, tabs, data, icon):
"""Add a plugin to the File Switcher."""
if self.fileswitcher is None:
from spyder.widgets.fileswitcher import FileSwitcher
self.fileswitcher = FileSwitcher(self, plugin, tabs, data, icon)
else:
se... |
Called by WorkerUpdates when ready | def _check_updates_ready(self):
"""Called by WorkerUpdates when ready"""
from spyder.widgets.helperwidgets import MessageCheckBox
# feedback` = False is used on startup, so only positive feedback is
# given. `feedback` = True is used when after startup (when using the
# me... |
Check for spyder updates on github releases using a QThread. | def check_updates(self, startup=False):
"""
Check for spyder updates on github releases using a QThread.
"""
from spyder.workers.updates import WorkerUpdates
# Disable check_updates_action while the thread is working
self.check_updates_action.setDisabled(True)
... |
Private set method | def _set(self, section, option, value, verbose):
"""
Private set method
"""
if not self.has_section(section):
self.add_section( section )
if not is_text_string(value):
value = repr( value )
if verbose:
print('%s[ %s ] = %s' % (... |
Save config into the associated .ini file | def _save(self):
"""
Save config into the associated .ini file
"""
# See Issue 1086 and 1242 for background on why this
# method contains all the exception handling.
fname = self.filename()
def _write_file(fname):
if PY2:
# P... |
Defines the name of the configuration file to use. | def filename(self):
"""Defines the name of the configuration file to use."""
# Needs to be done this way to be used by the project config.
# To fix on a later PR
self._filename = getattr(self, '_filename', None)
self._root_path = getattr(self, '_root_path', None)
... |
Create a .ini filename located in user home directory.
This .ini files stores the global spyder preferences. | def _filename_global(self):
"""Create a .ini filename located in user home directory.
This .ini files stores the global spyder preferences.
"""
if self.subfolder is None:
config_file = osp.join(get_home_dir(), '.%s.ini' % self.name)
return config_file
... |
Set configuration (not application!) version | def set_version(self, version='0.0.0', save=True):
"""Set configuration (not application!) version"""
self.set(self.DEFAULT_SECTION_NAME, 'version', version, save=save) |
Load config from the associated .ini file | def load_from_ini(self):
"""
Load config from the associated .ini file
"""
try:
if PY2:
# Python 2
fname = self.filename()
if osp.isfile(fname):
try:
with codecs.open(fname, ... |
Read old defaults | def _load_old_defaults(self, old_version):
"""Read old defaults"""
old_defaults = cp.ConfigParser()
if check_version(old_version, '3.0.0', '<='):
path = get_module_source_path('spyder')
else:
path = osp.dirname(self.filename())
path = osp.join(path,... |
Save new defaults | def _save_new_defaults(self, defaults, new_version, subfolder):
"""Save new defaults"""
new_defaults = DefaultsConfig(name='defaults-'+new_version,
subfolder=subfolder)
if not osp.isfile(new_defaults.filename()):
new_defaults.set_defaults(de... |
Update defaults after a change in version | def _update_defaults(self, defaults, old_version, verbose=False):
"""Update defaults after a change in version"""
old_defaults = self._load_old_defaults(old_version)
for section, options in defaults:
for option in options:
new_value = options[ option ]
... |
Remove options which are present in the .ini file but not in defaults | def _remove_deprecated_options(self, old_version):
"""
Remove options which are present in the .ini file but not in defaults
"""
old_defaults = self._load_old_defaults(old_version)
for section in old_defaults.sections():
for option, _ in old_defaults.items(secti... |
Set defaults from the current config | def set_as_defaults(self):
"""
Set defaults from the current config
"""
self.defaults = []
for section in self.sections():
secdict = {}
for option, value in self.items(section, raw=self.raw):
secdict[option] = value
sel... |
Reset config to Default values | def reset_to_defaults(self, save=True, verbose=False, section=None):
"""
Reset config to Default values
"""
for sec, options in self.defaults:
if section == None or section == sec:
for option in options:
value = options[ option ]
... |
Private method to check section and option types | def _check_section_option(self, section, option):
"""
Private method to check section and option types
"""
if section is None:
section = self.DEFAULT_SECTION_NAME
elif not is_text_string(section):
raise RuntimeError("Argument 'section' must be a str... |
Get Default value for a given (section, option)
-> useful for type checking in 'get' method | def get_default(self, section, option):
"""
Get Default value for a given (section, option)
-> useful for type checking in 'get' method
"""
section = self._check_section_option(section, option)
for sec, options in self.defaults:
if sec == section:
... |
Get an option
section=None: attribute a default section name
default: default value (if not specified, an exception
will be raised if option doesn't exist) | def get(self, section, option, default=NoDefault):
"""
Get an option
section=None: attribute a default section name
default: default value (if not specified, an exception
will be raised if option doesn't exist)
"""
section = self._check_section_option(secti... |
Set Default value for a given (section, option)
-> called when a new (section, option) is set and no default exists | def set_default(self, section, option, default_value):
"""
Set Default value for a given (section, option)
-> called when a new (section, option) is set and no default exists
"""
section = self._check_section_option(section, option)
for sec, options in self.defaults... |
Set an option
section=None: attribute a default section name | def set(self, section, option, value, verbose=False, save=True):
"""
Set an option
section=None: attribute a default section name
"""
section = self._check_section_option(section, option)
default_value = self.get_default(section, option)
if default_value is... |
Return temporary Spyder directory, checking previously that it exists. | def get_temp_dir(suffix=None):
"""
Return temporary Spyder directory, checking previously that it exists.
"""
to_join = [tempfile.gettempdir()]
if os.name == 'nt':
to_join.append('spyder')
else:
username = encoding.to_unicode_from_fs(getuser())
to_join.append('... |
Return program absolute path if installed in PATH.
Otherwise, return None | def is_program_installed(basename):
"""
Return program absolute path if installed in PATH.
Otherwise, return None
"""
for path in os.environ["PATH"].split(os.pathsep):
abspath = osp.join(path, basename)
if osp.isfile(abspath):
return abspath |
Find program in PATH and return absolute path
Try adding .exe or .bat to basename on Windows platforms
(return None if not found) | def find_program(basename):
"""
Find program in PATH and return absolute path
Try adding .exe or .bat to basename on Windows platforms
(return None if not found)
"""
names = [basename]
if os.name == 'nt':
# Windows platforms
extensions = ('.exe', '.bat', '.cmd')
... |
Given a dict, populate kwargs to create a generally
useful default setup for running subprocess processes
on different platforms. For example, `close_fds` is
set on posix and creation of a new console window is
disabled on Windows.
This function will alter the given kwargs and return
the... | def alter_subprocess_kwargs_by_platform(**kwargs):
"""
Given a dict, populate kwargs to create a generally
useful default setup for running subprocess processes
on different platforms. For example, `close_fds` is
set on posix and creation of a new console window is
disabled on Windows.
... |
Execute the given shell command.
Note that *args and **kwargs will be passed to the subprocess call.
If 'shell' is given in subprocess_kwargs it must be True,
otherwise ProgramError will be raised.
.
If 'executable' is not given in subprocess_kwargs, it will
be set to the value of ... | def run_shell_command(cmdstr, **subprocess_kwargs):
"""
Execute the given shell command.
Note that *args and **kwargs will be passed to the subprocess call.
If 'shell' is given in subprocess_kwargs it must be True,
otherwise ProgramError will be raised.
.
If 'executable' is no... |
Run program in a separate process.
NOTE: returns the process object created by
`subprocess.Popen()`. This can be used with
`proc.communicate()` for example.
If 'shell' appears in the kwargs, it must be False,
otherwise ProgramError will be raised.
If only the program name is given an... | def run_program(program, args=None, **subprocess_kwargs):
"""
Run program in a separate process.
NOTE: returns the process object created by
`subprocess.Popen()`. This can be used with
`proc.communicate()` for example.
If 'shell' appears in the kwargs, it must be False,
otherwise ... |
Generalized os.startfile for all platforms supported by Qt
This function is simply wrapping QDesktopServices.openUrl
Returns True if successfull, otherwise returns False. | def start_file(filename):
"""
Generalized os.startfile for all platforms supported by Qt
This function is simply wrapping QDesktopServices.openUrl
Returns True if successfull, otherwise returns False.
"""
from qtpy.QtCore import QUrl
from qtpy.QtGui import QDesktopServices
... |
Return absolute path if Python script exists (otherwise, return None)
package=None -> module is in sys.path (standard library modules) | def python_script_exists(package=None, module=None):
"""
Return absolute path if Python script exists (otherwise, return None)
package=None -> module is in sys.path (standard library modules)
"""
assert module is not None
try:
if package is None:
path = imp.find_modul... |
Run Python script in a separate process
package=None -> module is in sys.path (standard library modules) | def run_python_script(package=None, module=None, args=[], p_args=[]):
"""
Run Python script in a separate process
package=None -> module is in sys.path (standard library modules)
"""
assert module is not None
assert isinstance(args, (tuple, list)) and isinstance(p_args, (tuple, list))
... |
Split the string `text` using shell-like syntax
This avoids breaking single/double-quoted strings (e.g. containing
strings with spaces). This function is almost equivalent to the shlex.split
function (see standard library `shlex`) except that it is supporting
unicode strings (shlex does not suppor... | def shell_split(text):
"""
Split the string `text` using shell-like syntax
This avoids breaking single/double-quoted strings (e.g. containing
strings with spaces). This function is almost equivalent to the shlex.split
function (see standard library `shlex`) except that it is supporting
u... |
Construct Python interpreter arguments | def get_python_args(fname, python_args, interact, debug, end_args):
"""Construct Python interpreter arguments"""
p_args = []
if python_args is not None:
p_args += python_args.split()
if interact:
p_args.append('-i')
if debug:
p_args.extend(['-m', 'pdb'])
if fname... |
Run Python script in an external system terminal.
:str wdir: working directory, may be empty. | def run_python_script_in_terminal(fname, wdir, args, interact,
debug, python_args, executable=None):
"""
Run Python script in an external system terminal.
:str wdir: working directory, may be empty.
"""
if executable is None:
executable = get_python... |
Check version string of an active module against a required version.
If dev/prerelease tags result in TypeError for string-number comparison,
it is assumed that the dependency is satisfied.
Users on dev branches are responsible for keeping their own packages up to
date.
Copyright (C) 20... | def check_version(actver, version, cmp_op):
"""
Check version string of an active module against a required version.
If dev/prerelease tags result in TypeError for string-number comparison,
it is assumed that the dependency is satisfied.
Users on dev branches are responsible for keeping their... |
Return True if module *module_name* is installed
If version is not None, checking module version
(module must have an attribute named '__version__')
version may starts with =, >=, > or < to specify the exact requirement ;
multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0')
in... | def is_module_installed(module_name, version=None, installed_version=None,
interpreter=None):
"""
Return True if module *module_name* is installed
If version is not None, checking module version
(module must have an attribute named '__version__')
version may starts ... |
Check that the python interpreter file has a valid name. | def is_python_interpreter_valid_name(filename):
"""Check that the python interpreter file has a valid name."""
pattern = r'.*python(\d\.?\d*)?(w)?(.exe)?$'
if re.match(pattern, filename, flags=re.I) is None:
return False
else:
return True |
Evaluate wether a file is a python interpreter or not. | def is_python_interpreter(filename):
"""Evaluate wether a file is a python interpreter or not."""
real_filename = os.path.realpath(filename) # To follow symlink if existent
if (not osp.isfile(real_filename) or
not is_python_interpreter_valid_name(filename)):
return False
elif is_... |
Check that the python interpreter has 'pythonw'. | def is_pythonw(filename):
"""Check that the python interpreter has 'pythonw'."""
pattern = r'.*python(\d\.?\d*)?w(.exe)?$'
if re.match(pattern, filename, flags=re.I) is None:
return False
else:
return True |
Check that the python interpreter can execute help. | def check_python_help(filename):
"""Check that the python interpreter can execute help."""
try:
proc = run_program(filename, ["-h"])
output = to_text_string(proc.communicate()[0])
valid = ("Options and arguments (and corresponding environment "
"variables)")
... |
Override Qt method.
Returns the widget size hint (based on the editor font size). | def sizeHint(self):
"""Override Qt method.
Returns the widget size hint (based on the editor font size).
"""
fm = QFontMetrics(self.editor.font())
size_hint = QSize(fm.height(), fm.height())
if size_hint.width() > 16:
size_hint.setWidth(16)
return siz... |
Draw the given breakpoint pixmap.
Args:
top (int): top of the line to draw the breakpoint icon.
painter (QPainter)
icon_name (srt): key of icon to draw (see: self.icons) | def _draw_breakpoint_icon(self, top, painter, icon_name):
"""Draw the given breakpoint pixmap.
Args:
top (int): top of the line to draw the breakpoint icon.
painter (QPainter)
icon_name (srt): key of icon to draw (see: self.icons)
"""
rect = QRect(0, ... |
Override Qt method.
Paint breakpoints icons. | def paintEvent(self, event):
"""Override Qt method.
Paint breakpoints icons.
"""
super(DebuggerPanel, self).paintEvent(event)
painter = QPainter(self)
painter.fillRect(event.rect(), self.editor.sideareas_color)
for top, line_number, block in self.editor.visible_... |
Override Qt method
Add/remove breakpoints by single click. | def mousePressEvent(self, event):
"""Override Qt method
Add/remove breakpoints by single click.
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
shift = event.modifiers() & Qt.ShiftModifier
self.editor.debugger.toogle_breakpoint(line_number,
... |
Override Qt method.
Draw semitransparent breakpoint hint. | def mouseMoveEvent(self, event):
"""Override Qt method.
Draw semitransparent breakpoint hint.
"""
self.line_number_hint = self.editor.get_linenumber_from_mouse_event(
event)
self.update() |
Change visibility and connect/disconnect signal.
Args:
state (bool): Activate/deactivate. | def on_state_changed(self, state):
"""Change visibility and connect/disconnect signal.
Args:
state (bool): Activate/deactivate.
"""
if state:
self.editor.sig_breakpoints_changed.connect(self.repaint)
self.editor.sig_debug_stop.connect(self.set_current... |
Qt/Python2/3 compatibility helper. | def handle_qbytearray(obj, encoding):
"""Qt/Python2/3 compatibility helper."""
if isinstance(obj, QByteArray):
obj = obj.data()
return to_text_string(obj, encoding=encoding) |
This methods illustrates how the workers can be used. | def sleeping_func(arg, secs=10, result_queue=None):
"""This methods illustrates how the workers can be used."""
import time
time.sleep(secs)
if result_queue is not None:
result_queue.put(arg)
else:
return arg |
Start the worker (emits sig_started signal with worker as arg). | def start(self):
"""Start the worker (emits sig_started signal with worker as arg)."""
if not self._started:
self.sig_started.emit(self)
self._started = True |
Start process worker for given method args and kwargs. | def _start(self):
"""Start process worker for given method args and kwargs."""
error = None
output = None
try:
output = self.func(*self.args, **self.kwargs)
except Exception as err:
error = err
if not self._is_finished:
self.sig_finis... |
Return the encoding/codepage to use. | def _get_encoding(self):
"""Return the encoding/codepage to use."""
enco = 'utf-8'
# Currently only cp1252 is allowed?
if WIN:
import ctypes
codepage = to_text_string(ctypes.cdll.kernel32.GetACP())
# import locale
# locale.getpreferredenc... |
Set the environment on the QProcess. | def _set_environment(self, environ):
"""Set the environment on the QProcess."""
if environ:
q_environ = self._process.processEnvironment()
for k, v in environ.items():
q_environ.insert(k, v)
self._process.setProcessEnvironment(q_environ) |
Callback for partial output. | def _partial(self):
"""Callback for partial output."""
raw_stdout = self._process.readAllStandardOutput()
stdout = handle_qbytearray(raw_stdout, self._get_encoding())
if self._partial_stdout is None:
self._partial_stdout = stdout
else:
self._partial_stdou... |
Callback for communicate. | def _communicate(self):
"""Callback for communicate."""
if (not self._communicate_first and
self._process.state() == QProcess.NotRunning):
self.communicate()
elif self._fired:
self._timer.stop() |
Retrieve information. | def communicate(self):
"""Retrieve information."""
self._communicate_first = True
self._process.waitForFinished()
enco = self._get_encoding()
if self._partial_stdout is None:
raw_stdout = self._process.readAllStandardOutput()
stdout = handle_qbytearray(ra... |
Start process. | def _start(self):
"""Start process."""
if not self._fired:
self._partial_ouput = None
self._process.start(self._cmd_list[0], self._cmd_list[1:])
self._timer.start() |
Terminate running processes. | def terminate(self):
"""Terminate running processes."""
if self._process.state() == QProcess.Running:
try:
self._process.terminate()
except Exception:
pass
self._fired = True |
Delete periodically workers in workers bag. | def _clean_workers(self):
"""Delete periodically workers in workers bag."""
while self._bag_collector:
self._bag_collector.popleft()
self._timer_worker_delete.stop() |
Start threads and check for inactive workers. | def _start(self, worker=None):
"""Start threads and check for inactive workers."""
if worker:
self._queue_workers.append(worker)
if self._queue_workers and self._running_threads < self._max_threads:
#print('Queue: {0} Running: {1} Workers: {2} '
# 'Thre... |
Create a new python worker instance. | def create_python_worker(self, func, *args, **kwargs):
"""Create a new python worker instance."""
worker = PythonWorker(func, args, kwargs)
self._create_worker(worker)
return worker |
Create a new process worker instance. | def create_process_worker(self, cmd_list, environ=None):
"""Create a new process worker instance."""
worker = ProcessWorker(cmd_list, environ=environ)
self._create_worker(worker)
return worker |
Terminate all worker processes. | def terminate_all(self):
"""Terminate all worker processes."""
for worker in self._workers:
worker.terminate()
# for thread in self._threads:
# try:
# thread.terminate()
# thread.wait()
# except Exception:
# pas... |
Common worker setup. | def _create_worker(self, worker):
"""Common worker setup."""
worker.sig_started.connect(self._start)
self._workers.append(worker) |
Gather data about a given file.
Returns a dict with fields name, mtime and size, containing the relevant
data for the fiel. | def gather_file_data(name):
"""
Gather data about a given file.
Returns a dict with fields name, mtime and size, containing the relevant
data for the fiel.
"""
res = {'name': name}
try:
res['mtime'] = osp.getmtime(name)
res['size'] = osp.getsize(name)
except OSError:
... |
Convert file data to a string for display.
This function takes the file data produced by gather_file_data(). | def file_data_to_str(data):
"""
Convert file data to a string for display.
This function takes the file data produced by gather_file_data().
"""
if not data:
return _('<i>File name not recorded</i>')
res = data['name']
try:
mtime_as_str = time.strftime('%Y-%m-%d %H:%M:%S',
... |
Make temporary files to simulate a recovery use case.
Create a directory under tempdir containing some original files and another
directory with autosave files. Return a tuple with the name of the
directory with the original files, the name of the directory with the
autosave files, and the autosave map... | def make_temporary_files(tempdir):
"""
Make temporary files to simulate a recovery use case.
Create a directory under tempdir containing some original files and another
directory with autosave files. Return a tuple with the name of the
directory with the original files, the name of the directory wi... |
Add label with explanation at top of dialog window. | def add_label(self):
"""Add label with explanation at top of dialog window."""
txt = _('Autosave files found. What would you like to do?\n\n'
'This dialog will be shown again on next startup if any '
'autosave files are not restored, moved or deleted.')
label = QL... |
Add a label to specified cell in table. | def add_label_to_table(self, row, col, txt):
"""Add a label to specified cell in table."""
label = QLabel(txt)
label.setMargin(5)
label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.table.setCellWidget(row, col, label) |
Add table with info about files to be recovered. | def add_table(self):
"""Add table with info about files to be recovered."""
table = QTableWidget(len(self.data), 3, self)
self.table = table
labels = [_('Original file'), _('Autosave file'), _('Actions')]
table.setHorizontalHeaderLabels(labels)
table.verticalHeader().hid... |
Add a cancel button at the bottom of the dialog window. | def add_cancel_button(self):
"""Add a cancel button at the bottom of the dialog window."""
button_box = QDialogButtonBox(QDialogButtonBox.Cancel, self)
button_box.rejected.connect(self.reject)
self.layout.addWidget(button_box) |
Register plugin in Spyder's main window | def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
self.main.console.shell.refresh.connect(self.refresh_plugin)
iconsize = 24
self.toolbar.setIconSize(QSize(iconsize, iconsize))
... |
Refresh widget | def refresh_plugin(self):
"""Refresh widget"""
curdir = getcwd_or_home()
self.pathedit.add_text(curdir)
self.save_wdhistory()
self.set_previous_enabled.emit(
self.histindex is not None and self.histindex > 0)
self.set_next_enabled.emit(... |
Load history from a text file in user home directory | def load_wdhistory(self, workdir=None):
"""Load history from a text file in user home directory"""
if osp.isfile(self.LOG_PATH):
wdhistory, _ = encoding.readlines(self.LOG_PATH)
wdhistory = [name for name in wdhistory if os.path.isdir(name)]
else:
if wor... |
Save history to a text file in user home directory | def save_wdhistory(self):
"""Save history to a text file in user home directory"""
text = [ to_text_string( self.pathedit.itemText(index) ) \
for index in range(self.pathedit.count()) ]
try:
encoding.writelines(text, self.LOG_PATH)
except EnvironmentErr... |
Select directory | def select_directory(self):
"""Select directory"""
self.redirect_stdio.emit(False)
directory = getexistingdirectory(self.main, _("Select directory"),
getcwd_or_home())
if directory:
self.chdir(directory)
self.redirect_st... |
Change working directory to parent directory | def parent_directory(self):
"""Change working directory to parent directory"""
self.chdir(os.path.join(getcwd_or_home(), os.path.pardir)) |
Set directory as working directory | def chdir(self, directory, browsing_history=False,
refresh_explorer=True, refresh_console=True):
"""Set directory as working directory"""
if directory:
directory = osp.abspath(to_text_string(directory))
# Working directory history management
if browsing_... |
Add/remove breakpoint. | def toogle_breakpoint(self, line_number=None, condition=None,
edit_condition=False):
"""Add/remove breakpoint."""
if not self.editor.is_python_like():
return
if line_number is None:
block = self.editor.textCursor().block()
else:
... |
Get breakpoints | def get_breakpoints(self):
"""Get breakpoints"""
breakpoints = []
block = self.editor.document().firstBlock()
for line_number in range(1, self.editor.document().blockCount()+1):
data = block.userData()
if data and data.breakpoint:
breakpoints.appen... |
Clear breakpoints | def clear_breakpoints(self):
"""Clear breakpoints"""
self.breakpoints = []
for data in self.editor.blockuserdata_list[:]:
data.breakpoint = False
# data.breakpoint_condition = None # not necessary, but logical
if data.is_empty():
# This is not... |
Set breakpoints | def set_breakpoints(self, breakpoints):
"""Set breakpoints"""
self.clear_breakpoints()
for line_number, condition in breakpoints:
self.toogle_breakpoint(line_number, condition)
self.breakpoints = self.get_breakpoints() |
Breakpoint list has changed | def breakpoints_changed(self):
"""Breakpoint list has changed"""
breakpoints = self.get_breakpoints()
if self.breakpoints != breakpoints:
self.breakpoints = breakpoints
self.save_breakpoints() |
Return whether a string has open quotes.
This simply counts whether the number of quote characters of either
type in the string is odd.
Take from the IPython project (in IPython/core/completer.py in v0.13)
Spyder team: Add some changes to deal with escaped quotes
- Copyright (C) 2008-2011 IPython... | def unmatched_quotes_in_line(text):
"""Return whether a string has open quotes.
This simply counts whether the number of quote characters of either
type in the string is odd.
Take from the IPython project (in IPython/core/completer.py in v0.13)
Spyder team: Add some changes to deal with escaped qu... |
Connect/disconnect sig_key_pressed signal. | def on_state_changed(self, state):
"""Connect/disconnect sig_key_pressed signal."""
if state:
self.editor.sig_key_pressed.connect(self._on_key_pressed)
else:
self.editor.sig_key_pressed.disconnect(self._on_key_pressed) |
Control how to automatically insert quotes in various situations. | def _autoinsert_quotes(self, key):
"""Control how to automatically insert quotes in various situations."""
char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: '\''}[key]
line_text = self.editor.get_text('sol', 'eol')
line_to_cursor = self.editor.get_text('sol', 'cursor')
cursor = s... |
Populate the given ``combobox`` with the class or function names.
Parameters
----------
combobox : :class:`qtpy.QtWidets.QComboBox`
The combobox to populate
data : list of :class:`FoldScopeHelper`
The data to populate with. There should be one list element per
class or function ... | def populate(combobox, data):
"""
Populate the given ``combobox`` with the class or function names.
Parameters
----------
combobox : :class:`qtpy.QtWidets.QComboBox`
The combobox to populate
data : list of :class:`FoldScopeHelper`
The data to populate with. There should be one l... |
Return a list of all the class/function definition ranges.
Parameters
----------
editor : :class:`spyder.plugins.editor.widgets.codeeditor.CodeEditor`
Returns
-------
folds : list of :class:`FoldScopeHelper`
A list of all the class or function defintion fold points. | def _get_fold_levels(editor):
"""
Return a list of all the class/function definition ranges.
Parameters
----------
editor : :class:`spyder.plugins.editor.widgets.codeeditor.CodeEditor`
Returns
-------
folds : list of :class:`FoldScopeHelper`
A list of all the class or function ... |
Adjust the parent stack in-place as the trigger level changes.
Parameters
----------
fsh : :class:`FoldScopeHelper`
The :class:`FoldScopeHelper` object to act on.
prev : :class:`FoldScopeHelper`
The previous :class:`FoldScopeHelper` object.
parents : list of :class:`FoldScopeHelper`... | def _adjust_parent_stack(fsh, prev, parents):
"""
Adjust the parent stack in-place as the trigger level changes.
Parameters
----------
fsh : :class:`FoldScopeHelper`
The :class:`FoldScopeHelper` object to act on.
prev : :class:`FoldScopeHelper`
The previous :class:`FoldScopeHelp... |
Split out classes and methods into two separate lists.
Parameters
----------
folds : list of :class:`FoldScopeHelper`
The result of :func:`_get_fold_levels`.
Returns
-------
classes, functions: list of :class:`FoldScopeHelper`
Two separate lists of :class:`FoldScopeHelper` obje... | def _split_classes_and_methods(folds):
"""
Split out classes and methods into two separate lists.
Parameters
----------
folds : list of :class:`FoldScopeHelper`
The result of :func:`_get_fold_levels`.
Returns
-------
classes, functions: list of :class:`FoldScopeHelper`
... |
Get the parents at a given linenum.
If parents is empty, then the linenum belongs to the module.
Parameters
----------
folds : list of :class:`FoldScopeHelper`
linenum : int
The line number to get parents for. Typically this would be the
cursor position.
Returns
-------
... | def _get_parents(folds, linenum):
"""
Get the parents at a given linenum.
If parents is empty, then the linenum belongs to the module.
Parameters
----------
folds : list of :class:`FoldScopeHelper`
linenum : int
The line number to get parents for. Typically this would be the
... |
Update the combobox with the selected item based on the parents.
Parameters
----------
parents : list of :class:`FoldScopeHelper`
combobox : :class:`qtpy.QtWidets.QComboBox`
The combobox to populate
Returns
-------
None | def update_selected_cb(parents, combobox):
"""
Update the combobox with the selected item based on the parents.
Parameters
----------
parents : list of :class:`FoldScopeHelper`
combobox : :class:`qtpy.QtWidets.QComboBox`
The combobox to populate
Returns
-------
None
"""... |
Update the internal data values. | def _update_data(self):
"""Update the internal data values."""
_old = self.folds
self.folds = _get_fold_levels(self.editor)
# only update our dropdown lists if the folds have changed.
if self.folds != _old:
self.classes, self.funcs = _split_classes_and_methods(self.f... |
Move the cursor to the selected definition. | def combobox_activated(self):
"""Move the cursor to the selected definition."""
sender = self.sender()
data = sender.itemData(sender.currentIndex())
if isinstance(data, FoldScopeHelper):
self.editor.go_to_line(data.line + 1) |
Updates the dropdowns to reflect the current class and function. | def update_selected(self, linenum):
"""Updates the dropdowns to reflect the current class and function."""
self.parents = _get_parents(self.funcs, linenum)
update_selected_cb(self.parents, self.method_cb)
self.parents = _get_parents(self.classes, linenum)
update_selected_cb(self... |
Set text editor palette colors:
background color and caret (text cursor) color | def set_palette(self, background, foreground):
"""
Set text editor palette colors:
background color and caret (text cursor) color
"""
palette = QPalette()
palette.setColor(QPalette.Base, background)
palette.setColor(QPalette.Text, foreground)
self.... |
Set extra selections for a key.
Also assign draw orders to leave current_cell and current_line
in the backgrund (and avoid them to cover other decorations)
NOTE: This will remove previous decorations added to the same key.
Args:
key (str) name of the extra selecti... | def set_extra_selections(self, key, extra_selections):
"""Set extra selections for a key.
Also assign draw orders to leave current_cell and current_line
in the backgrund (and avoid them to cover other decorations)
NOTE: This will remove previous decorations added to the same key... |
Add extra selections to DecorationsManager.
TODO: This method could be remove it and decorations could be
added/removed in set_extra_selections/clear_extra_selections. | def update_extra_selections(self):
"""Add extra selections to DecorationsManager.
TODO: This method could be remove it and decorations could be
added/removed in set_extra_selections/clear_extra_selections.
"""
extra_selections = []
for key, extra in list(self.ex... |
Remove decorations added through set_extra_selections.
Args:
key (str) name of the extra selections group. | def clear_extra_selections(self, key):
"""Remove decorations added through set_extra_selections.
Args:
key (str) name of the extra selections group.
"""
for decoration in self.extra_selections_dict.get(key, []):
self.decorations.remove(decoration)
... |
Highlight current line | def highlight_current_line(self):
"""Highlight current line"""
selection = TextDecoration(self.textCursor())
selection.format.setProperty(QTextFormat.FullWidthSelection,
to_qvariant(True))
selection.format.setBackground(self.currentline_color)
... |
Highlight current cell | def highlight_current_cell(self):
"""Highlight current cell"""
if self.cell_separators is None or \
not self.highlight_current_cell_enabled:
return
cursor, whole_file_selected, whole_screen_selected =\
self.select_current_cell_in_visible_portion()
... |
Brace matching | def cursor_position_changed(self):
"""Brace matching"""
if self.bracepos is not None:
self.__highlight(self.bracepos, cancel=True)
self.bracepos = None
cursor = self.textCursor()
if cursor.position() == 0:
return
cursor.movePosition(QTe... |
Set wrap mode
Valid *mode* values: None, 'word', 'character' | def set_wrap_mode(self, mode=None):
"""
Set wrap mode
Valid *mode* values: None, 'word', 'character'
"""
if mode == 'word':
wrap_mode = QTextOption.WrapAtWordBoundaryOrAnywhere
elif mode == 'character':
wrap_mode = QTextOption.WrapAnywhere
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.