INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Insert text at the current cursor position
or at the end of the command line | def insert_text(self, text, at_end=False, error=False, prompt=False):
"""
Insert text at the current cursor position
or at the end of the command line
"""
if at_end:
# Insert text at the end of the command line
self.append_text_to_shell(text, error,... |
Drag and Drop - Drop event | def dropEvent(self, event):
"""Drag and Drop - Drop event"""
if (event.mimeData().hasFormat("text/plain")):
text = to_text_string(event.mimeData().text())
if self.new_input_line:
self.on_new_line()
self.insert_text(text, at_end=True)
... |
Reimplements ShellBaseWidget method | def setup_context_menu(self):
"""Reimplements ShellBaseWidget method"""
ShellBaseWidget.setup_context_menu(self)
self.copy_without_prompts_action = create_action(self,
_("Copy without prompts"),
icon=ima.icon('copywop... |
Reimplements ShellBaseWidget method | def contextMenuEvent(self, event):
"""Reimplements ShellBaseWidget method"""
state = self.has_selected_text()
self.copy_without_prompts_action.setEnabled(state)
ShellBaseWidget.contextMenuEvent(self, event) |
Copy text to clipboard without prompts | def copy_without_prompts(self):
"""Copy text to clipboard without prompts"""
text = self.get_selected_text()
lines = text.split(os.linesep)
for index, line in enumerate(lines):
if line.startswith('>>> ') or line.startswith('... '):
lines[index] = line[4:... |
Process keypress event | def postprocess_keyevent(self, event):
"""Process keypress event"""
ShellBaseWidget.postprocess_keyevent(self, event)
if QToolTip.isVisible():
_event, _text, key, _ctrl, _shift = restore_keyevent(event)
self.hide_tooltip_if_necessary(key) |
Action for Backspace key | def _key_backspace(self, cursor_position):
"""Action for Backspace key"""
if self.has_selected_text():
self.check_selection()
self.remove_selected_text()
elif self.current_prompt_pos == cursor_position:
# Avoid deleting prompt
return
... |
Action for TAB key | def _key_tab(self):
"""Action for TAB key"""
if self.is_cursor_on_last_line():
empty_line = not self.get_current_line_to_cursor().strip()
if empty_line:
self.stdkey_tab()
else:
self.show_code_completion() |
Action for '? | def _key_question(self, text):
"""Action for '?'"""
if self.get_current_line_to_cursor():
last_obj = self.get_last_obj()
if last_obj and not last_obj.isdigit():
self.show_object_info(last_obj)
self.insert_text(text)
# In case calltip and com... |
Action for '( | def _key_parenleft(self, text):
"""Action for '('"""
self.hide_completion_widget()
if self.get_current_line_to_cursor():
last_obj = self.get_last_obj()
if last_obj and not last_obj.isdigit():
self.insert_text(text)
self.show_object_i... |
Action for '. | def _key_period(self, text):
"""Action for '.'"""
self.insert_text(text)
if self.codecompletion_auto:
# Enable auto-completion only if last token isn't a float
last_obj = self.get_last_obj()
if last_obj and not last_obj.isdigit():
self.s... |
Reimplemented slot to handle multiline paste action | def paste(self):
"""Reimplemented slot to handle multiline paste action"""
text = to_text_string(QApplication.clipboard().text())
if len(text.splitlines()) > 1:
# Multiline paste
if self.new_input_line:
self.on_new_line()
self.remove_sel... |
Display the possible completions | def show_completion_list(self, completions, completion_text=""):
"""Display the possible completions"""
if not completions:
return
if not isinstance(completions[0], tuple):
completions = [(c, '') for c in completions]
if len(completions) == 1 and completions... |
Display a completion list based on the current line | def show_code_completion(self):
"""Display a completion list based on the current line"""
# Note: unicode conversion is needed only for ExternalShellBase
text = to_text_string(self.get_current_line_to_cursor())
last_obj = self.get_last_obj()
if not text:
return
... |
Drop path list | def drop_pathlist(self, pathlist):
"""Drop path list"""
if pathlist:
files = ["r'%s'" % path for path in pathlist]
if len(files) == 1:
text = files[0]
else:
text = "[" + ", ".join(files) + "]"
if self.new_input_line:... |
Command to start kernels | def argv(self):
"""Command to start kernels"""
# Python interpreter used to start kernels
if CONF.get('main_interpreter', 'default'):
pyexec = get_python_executable()
else:
# Avoid IPython adding the virtualenv on which Spyder is running
# to the kerne... |
Env vars for kernels | def env(self):
"""Env vars for kernels"""
# Add our PYTHONPATH to the kernel
pathlist = CONF.get('main', 'spyder_pythonpath', default=[])
default_interpreter = CONF.get('main_interpreter', 'default')
pypath = add_pathlist_to_PYTHONPATH([], pathlist, ipyconsole=True,
... |
Setup context menu common actions | def setup_common_actions(self):
"""Setup context menu common actions"""
actions = FilteredDirView.setup_common_actions(self)
# Toggle horizontal scrollbar
hscrollbar_action = create_action(self, _("Show horizontal scrollbar"),
toggled=self... |
Toggle horizontal scrollbar | def toggle_hscrollbar(self, checked):
"""Toggle horizontal scrollbar"""
self.parent_widget.sig_option_changed.emit('show_hscrollbar', checked)
self.show_hscrollbar = checked
self.header().setStretchLastSection(not checked)
self.header().setHorizontalScrollMode(QAbstractItemV... |
Reimplement Qt method | def dragMoveEvent(self, event):
"""Reimplement Qt method"""
index = self.indexAt(event.pos())
if index:
dst = self.get_filename(index)
if osp.isdir(dst):
event.acceptProposedAction()
else:
event.ignore()
else:
... |
Reimplement Qt method | def dropEvent(self, event):
"""Reimplement Qt method"""
event.ignore()
action = event.dropAction()
if action not in (Qt.MoveAction, Qt.CopyAction):
return
# QTreeView must not remove the source items even in MoveAction mode:
# event.setDropAction(Qt.C... |
Delete files | def delete(self, fnames=None):
"""Delete files"""
if fnames is None:
fnames = self.get_selected_filenames()
multiple = len(fnames) > 1
yes_to_all = None
for fname in fnames:
if fname == self.proxymodel.path_list[0]:
self.sig_delete_... |
Set the project directory | def set_project_dir(self, directory):
"""Set the project directory"""
if directory is not None:
self.treewidget.set_root_path(osp.dirname(directory))
self.treewidget.set_folder_names([osp.basename(directory)])
self.treewidget.setup_project_view()
try:
... |
Setup project | def setup_project(self, directory):
"""Setup project"""
self.emptywidget.hide()
self.treewidget.show()
# Setup the directory shown by the tree
self.set_project_dir(directory) |
Start Python interpreter | def start_interpreter(self, namespace):
"""Start Python interpreter"""
self.clear()
if self.interpreter is not None:
self.interpreter.closing()
self.interpreter = Interpreter(namespace, self.exitfunc,
SysOutput, WidgetPro... |
Exit interpreter | def exit_interpreter(self):
"""Exit interpreter"""
self.interpreter.exit_flag = True
if self.multithreaded:
self.interpreter.stdin_write.write(to_binary_string('\n'))
self.interpreter.restore_stds() |
Data is available in stdout, let's empty the queue and write it! | def stdout_avail(self):
"""Data is available in stdout, let's empty the queue and write it!"""
data = self.interpreter.stdout_write.empty_queue()
if data:
self.write(data) |
Data is available in stderr, let's empty the queue and write it! | def stderr_avail(self):
"""Data is available in stderr, let's empty the queue and write it!"""
data = self.interpreter.stderr_write.empty_queue()
if data:
self.write(data, error=True)
self.flush(error=True) |
Wait for input (raw_input support) | def wait_input(self, prompt=''):
"""Wait for input (raw_input support)"""
self.new_prompt(prompt)
self.setFocus()
self.input_mode = True
self.input_loop = QEventLoop()
self.input_loop.exec_()
self.input_loop = None |
End of wait_input mode | def end_input(self, cmd):
"""End of wait_input mode"""
self.input_mode = False
self.input_loop.exit()
self.interpreter.widget_proxy.end_input(cmd) |
Reimplement PythonShellWidget method | def setup_context_menu(self):
"""Reimplement PythonShellWidget method"""
PythonShellWidget.setup_context_menu(self)
self.help_action = create_action(self, _("Help..."),
icon=ima.icon('DialogHelpButton'),
triggered=self.help)
sel... |
Help on Spyder console | def help(self):
"""Help on Spyder console"""
QMessageBox.about(self, _("Help"),
"""<b>%s</b>
<p><i>%s</i><br> edit foobar.py
<p><i>%s</i><br> xedit foobar.py
<p><i>%s</i><br> run foobar... |
Load file in external Spyder's editor, if available
This method is used only for embedded consoles
(could also be useful if we ever implement the magic %edit command) | def open_with_external_spyder(self, text):
"""Load file in external Spyder's editor, if available
This method is used only for embedded consoles
(could also be useful if we ever implement the magic %edit command)"""
match = get_error_match(to_text_string(text))
if match:
... |
Edit in an external editor
Recommended: SciTE (e.g. to go to line where an error did occur) | def external_editor(self, filename, goto=-1):
"""Edit in an external editor
Recommended: SciTE (e.g. to go to line where an error did occur)"""
editor_path = CONF.get('internal_console', 'external_editor/path')
goto_option = CONF.get('internal_console', 'external_editor/gotoline')
... |
Reimplement ShellBaseWidget method | def flush(self, error=False, prompt=False):
"""Reimplement ShellBaseWidget method"""
PythonShellWidget.flush(self, error=error, prompt=prompt)
if self.interrupted:
self.interrupted = False
raise KeyboardInterrupt |
Reimplement ShellBaseWidget method | def clear_terminal(self):
"""Reimplement ShellBaseWidget method"""
self.clear()
self.new_prompt(self.interpreter.p2 if self.interpreter.more else self.interpreter.p1) |
on_enter | def on_enter(self, command):
"""on_enter"""
if self.profile:
# Simple profiling test
t0 = time()
for _ in range(10):
self.execute_command(command)
self.insert_text(u"\n<Δt>=%dms\n" % (1e2*(time()-t0)))
self.new_prompt(se... |
Flush keyboard event queue | def __flush_eventqueue(self):
"""Flush keyboard event queue"""
while self.eventqueue:
past_event = self.eventqueue.pop(0)
self.postprocess_keyevent(past_event) |
Simulate keyboard interrupt | def keyboard_interrupt(self):
"""Simulate keyboard interrupt"""
if self.multithreaded:
self.interpreter.raise_keyboard_interrupt()
else:
if self.interpreter.more:
self.write_error("\nKeyboardInterrupt\n")
self.interpreter.more = Fals... |
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands | def execute_lines(self, lines):
"""
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands
"""
for line in lines.splitlines():
stripped_line = line.strip()
if stripped_line.startswith('#'):
... |
Execute a command
cmd: one-line command only, with '\n' at the end | def execute_command(self, cmd):
"""
Execute a command
cmd: one-line command only, with '\n' at the end
"""
if self.input_mode:
self.end_input(cmd)
return
if cmd.endswith('\n'):
cmd = cmd[:-1]
# cls command
if ... |
Run command in interpreter | def run_command(self, cmd, history=True, new_prompt=True):
"""Run command in interpreter"""
if not cmd:
cmd = ''
else:
if history:
self.add_to_history(cmd)
if not self.multithreaded:
if 'input' not in cmd:
self.... |
Return dir(object) | def get_dir(self, objtxt):
"""Return dir(object)"""
obj, valid = self._eval(objtxt)
if valid:
return getobjdir(obj) |
Is object callable? | def iscallable(self, objtxt):
"""Is object callable?"""
obj, valid = self._eval(objtxt)
if valid:
return callable(obj) |
Get func/method argument list | def get_arglist(self, objtxt):
"""Get func/method argument list"""
obj, valid = self._eval(objtxt)
if valid:
return getargtxt(obj) |
Get object documentation dictionary | def get_doc(self, objtxt):
"""Get object documentation dictionary"""
obj, valid = self._eval(objtxt)
if valid:
return getdoc(obj) |
Get object source | def get_source(self, objtxt):
"""Get object source"""
obj, valid = self._eval(objtxt)
if valid:
return getsource(obj) |
Return True if object is defined | def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import) |
Override Qt method | def paintEvent(self, event):
"""Override Qt method"""
painter = QPainter(self)
size = self.size()
color = QColor(self.color)
color.setAlphaF(.5)
painter.setPen(color)
for column in self.columns:
x = self.editor.fontMetrics().width(column * '9')
... |
Set edge line columns values. | def set_columns(self, columns):
"""Set edge line columns values."""
if isinstance(columns, tuple):
self.columns = columns
elif is_text_string(columns):
self.columns = tuple(int(e) for e in columns.split(','))
self.update() |
Simple socket client used to send the args passed to the Spyder
executable to an already running instance.
Args can be Python scripts or files with these extensions: .spydata, .mat,
.npy, or .h5, which can be imported by the Variable Explorer. | def send_args_to_spyder(args):
"""
Simple socket client used to send the args passed to the Spyder
executable to an already running instance.
Args can be Python scripts or files with these extensions: .spydata, .mat,
.npy, or .h5, which can be imported by the Variable Explorer.
"""
... |
Start Spyder application.
If single instance mode is turned on (default behavior) and an instance of
Spyder is already running, this will just parse and send command line
options to the application. | def main():
"""
Start Spyder application.
If single instance mode is turned on (default behavior) and an instance of
Spyder is already running, this will just parse and send command line
options to the application.
"""
# Parse command line options
if running_under_pytest():
... |
Returns a compiled regex pattern to search for query letters in order.
Parameters
----------
query : str
String to search in another string (in order of character occurrence).
ignore_case : True
Optional value perform a case insensitive search (True by default).
Returns
-------... | def get_search_regex(query, ignore_case=True):
"""Returns a compiled regex pattern to search for query letters in order.
Parameters
----------
query : str
String to search in another string (in order of character occurrence).
ignore_case : True
Optional value perform a case insensit... |
Returns a tuple with the enriched text (if a template is provided) and
a score for the match.
Parameters
----------
query : str
String with letters to search in choice (in order of appearance).
choice : str
Sentence/words in which to search for the 'query' letters.
ignore_case :... | def get_search_score(query, choice, ignore_case=True, apply_regex=True,
template='{}'):
"""Returns a tuple with the enriched text (if a template is provided) and
a score for the match.
Parameters
----------
query : str
String with letters to search in choice (in order o... |
Search for query inside choices and return a list of tuples.
Returns a list of tuples of text with the enriched text (if a template is
provided) and a score for the match. Lower scores imply a better match.
Parameters
----------
query : str
String with letters to search in each choice (in ... | def get_search_scores(query, choices, ignore_case=True, template='{}',
valid_only=False, sort=False):
"""Search for query inside choices and return a list of tuples.
Returns a list of tuples of text with the enriched text (if a template is
provided) and a score for the match. Lower sc... |
Return True if text is the beginning of the function definition. | def is_start_of_function(text):
"""Return True if text is the beginning of the function definition."""
if isinstance(text, str) or isinstance(text, unicode):
function_prefix = ['def', 'async def']
text = text.lstrip()
for prefix in function_prefix:
if text.startswith(... |
Get indent of text.
https://stackoverflow.com/questions/2268532/grab-a-lines-whitespace-
indention-with-python | def get_indent(text):
"""Get indent of text.
https://stackoverflow.com/questions/2268532/grab-a-lines-whitespace-
indention-with-python
"""
indent = ''
ret = re.match(r'(\s*)', text)
if ret:
indent = ret.group(1)
return indent |
Get func def when the cursor is located on the first def line. | def get_function_definition_from_first_line(self):
"""Get func def when the cursor is located on the first def line."""
document = self.code_editor.document()
cursor = QTextCursor(
document.findBlockByLineNumber(self.line_number_cursor - 1))
func_text = ''
fun... |
Get func def when the cursor is located below the last def line. | def get_function_definition_from_below_last_line(self):
"""Get func def when the cursor is located below the last def line."""
cursor = self.code_editor.textCursor()
func_text = ''
is_first_line = True
line_number = cursor.blockNumber() + 1
number_of_lines_of_functi... |
Get the function body text. | def get_function_body(self, func_indent):
"""Get the function body text."""
cursor = self.code_editor.textCursor()
line_number = cursor.blockNumber() + 1
number_of_lines = self.code_editor.blockCount()
body_list = []
for idx in range(number_of_lines - line_number ... |
Write docstring to editor. | def write_docstring(self):
"""Write docstring to editor."""
line_to_cursor = self.code_editor.get_text('sol', 'cursor')
if self.is_beginning_triple_quotes(line_to_cursor):
cursor = self.code_editor.textCursor()
prev_pos = cursor.position()
quote = line... |
Write docstring to editor at mouse position. | def write_docstring_at_first_line_of_function(self):
"""Write docstring to editor at mouse position."""
result = self.get_function_definition_from_first_line()
editor = self.code_editor
if result:
func_text, number_of_line_func = result
line_number_function ... |
Write docstring to editor by shortcut of code editor. | def write_docstring_for_shortcut(self):
"""Write docstring to editor by shortcut of code editor."""
# cursor placed below function definition
result = self.get_function_definition_from_below_last_line()
if result is not None:
__, number_of_lines_of_function = result
... |
Generate docstring. | def _generate_docstring(self, doc_type, quote):
"""Generate docstring."""
docstring = None
self.quote3 = quote * 3
if quote == '"':
self.quote3_other = "'''"
else:
self.quote3_other = '"""'
result = self.get_function_definition_from_bel... |
Generate a docstring of numpy type. | def _generate_numpy_doc(self, func_info):
"""Generate a docstring of numpy type."""
numpy_doc = ''
arg_names = func_info.arg_name_list
arg_types = func_info.arg_type_list
arg_values = func_info.arg_value_list
if len(arg_names) > 0 and arg_names[0] == 'self':
... |
Get the locations of top-level brackets in a string. | def find_top_level_bracket_locations(string_toparse):
"""Get the locations of top-level brackets in a string."""
bracket_stack = []
replace_args_list = []
bracket_type = None
literal_type = ''
brackets = {'(': ')', '[': ']', '{': '}'}
for idx, character in ... |
Return the appropriate text for a group of return elements. | def parse_return_elements(return_vals_group, return_element_name,
return_element_type, placeholder):
"""Return the appropriate text for a group of return elements."""
all_eq = (return_vals_group.count(return_vals_group[0])
== len(return_vals_group))
... |
Generate the Returns section of a function/method docstring. | def _generate_docstring_return_section(self, return_vals, header,
return_element_name,
return_element_type,
placeholder, indent):
"""Generate the Returns section of a function/met... |
Return True if the charactor is in pairs of brackets or quotes. | def is_char_in_pairs(pos_char, pairs):
"""Return True if the charactor is in pairs of brackets or quotes."""
for pos_left, pos_right in pairs.items():
if pos_left < pos_char < pos_right:
return True
return False |
Return the start and end position of pairs of quotes. | def _find_quote_position(text):
"""Return the start and end position of pairs of quotes."""
pos = {}
is_found_left_quote = False
for idx, character in enumerate(text):
if is_found_left_quote is False:
if character == "'" or character == '"':
... |
Return the start and end position of pairs of brackets.
https://stackoverflow.com/questions/29991917/
indices-of-matching-parentheses-in-python | def _find_bracket_position(self, text, bracket_left, bracket_right,
pos_quote):
"""Return the start and end position of pairs of brackets.
https://stackoverflow.com/questions/29991917/
indices-of-matching-parentheses-in-python
"""
pos = {}
... |
Split argument text to name, type, value. | def split_arg_to_name_type_value(self, args_list):
"""Split argument text to name, type, value."""
for arg in args_list:
arg_type = None
arg_value = None
has_type = False
has_value = False
pos_colon = arg.find(':')
pos_e... |
Split the text including multiple arguments to list.
This function uses a comma to separate arguments and ignores a comma in
brackets ans quotes. | def split_args_text_to_list(self, args_text):
"""Split the text including multiple arguments to list.
This function uses a comma to separate arguments and ignores a comma in
brackets ans quotes.
"""
args_list = []
idx_find_start = 0
idx_arg_start = 0
... |
Parse the function definition text. | def parse_def(self, text):
"""Parse the function definition text."""
self.__init__()
if not is_start_of_function(text):
return
self.func_indent = get_indent(text)
text = text.strip()
text = text.replace('\r\n', '')
text = text.replace('\n... |
Parse the function body text. | def parse_body(self, text):
"""Parse the function body text."""
re_raise = re.findall(r'[ \t]raise ([a-zA-Z0-9_]*)', text)
if len(re_raise) > 0:
self.raise_list = [x.strip() for x in re_raise]
# remove duplicates from list while keeping it in the order
#... |
Close the instance if key is not enter key. | def keyPressEvent(self, event):
"""Close the instance if key is not enter key."""
key = event.key()
if key not in (Qt.Key_Enter, Qt.Key_Return):
self.code_editor.keyPressEvent(event)
self.close()
else:
super(QMenuOnlyForEnter, self).keyPressEven... |
Check if a process is running on windows systems based on the pid. | def _is_pid_running_on_windows(pid):
"""Check if a process is running on windows systems based on the pid."""
pid = str(pid)
# Hide flashing command prompt
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(r'tasklis... |
Show message on splash screen. | def _show_message(self, text):
"""Show message on splash screen."""
self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter |
Qt.AlignAbsolute, QColor(Qt.white)) |
Animate dots at the end of the splash screen message. | def animate_ellipsis(self):
"""Animate dots at the end of the splash screen message."""
ellipsis = self.ellipsis.pop(0)
text = ' '*len(ellipsis) + self.splash_text + ellipsis
self.ellipsis.append(ellipsis)
self._show_message(text) |
Sets the text in the bottom of the Splash screen. | def set_splash_message(self, text):
"""Sets the text in the bottom of the Splash screen."""
self.splash_text = text
self._show_message(text)
self.timer_ellipsis.start(500) |
Launch a message box with a predefined error message.
Parameters
----------
error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR]
Possible error codes when restarting/reseting spyder.
error : Exception
Actual Python exception error caught. | def launch_error_message(self, error_type, error=None):
"""Launch a message box with a predefined error message.
Parameters
----------
error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR]
Possible error codes when restarting/reseting spyder.
error : Exce... |
Refresh tabwidget | def refresh_plugin(self):
"""Refresh tabwidget"""
if self.tabwidget.count():
editor = self.tabwidget.currentWidget()
else:
editor = None
self.find_widget.set_editor(editor) |
Return a list of actions related to plugin | def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
self.history_action = create_action(self, _("History..."),
None, ima.icon('history'),
_("Set history maximum entries"),
... |
Register plugin in Spyder's main window | def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.focus_changed.connect(self.main.plugin_focus_changed)
self.main.add_dockwidget(self)
# self.main.console.set_historylog(self)
self.main.console.shell.refresh.connect(self.refresh_plugin) |
Update font from Preferences | def update_font(self):
"""Update font from Preferences"""
color_scheme = self.get_color_scheme()
font = self.get_plugin_font()
for editor in self.editors:
editor.set_font(font, color_scheme) |
Apply configuration file's plugin settings | def apply_plugin_settings(self, options):
"""Apply configuration file's plugin settings"""
color_scheme_n = 'color_scheme_name'
color_scheme_o = self.get_color_scheme()
font_n = 'plugin_font'
font_o = self.get_plugin_font()
wrap_n = 'wrap'
wrap_o = self.get... |
Add new history tab
Slot for add_history signal emitted by shell instance | def add_history(self, filename):
"""
Add new history tab
Slot for add_history signal emitted by shell instance
"""
filename = encoding.to_unicode_from_fs(filename)
if filename in self.filenames:
return
editor = codeeditor.CodeEditor(self)
... |
Toggle line numbers. | def toggle_line_numbers(self, checked):
"""Toggle line numbers."""
if self.tabwidget is None:
return
for editor in self.editors:
editor.toggle_line_numbers(linenumbers=checked, markers=False)
self.set_option('line_numbers', checked) |
Toggle wrap mode | def toggle_wrap_mode(self, checked):
"""Toggle wrap mode"""
if self.tabwidget is None:
return
for editor in self.editors:
editor.toggle_wrap_mode(checked)
self.set_option('wrap', checked) |
Handle the textDocument/didSave message received from an LSP server. | def document_did_save_notification(self, params):
"""
Handle the textDocument/didSave message received from an LSP server.
"""
text = None
if 'text' in params:
text = params['text']
params = {
'textDocument': {
'uri': path_as_uri(pa... |
Overloaded method to handle links ourselves | def acceptNavigationRequest(self, url, navigation_type, isMainFrame):
"""
Overloaded method to handle links ourselves
"""
if navigation_type == QWebEnginePage.NavigationTypeLinkClicked:
self.linkClicked.emit(url)
return False
return True |
Find text | def find_text(self, text, changed=True,
forward=True, case=False, words=False,
regexp=False):
"""Find text"""
if not WEBENGINE:
findflag = QWebEnginePage.FindWrapsAroundDocument
else:
findflag = 0
if not forward:
... |
Apply zoom factor | def apply_zoom_factor(self):
"""Apply zoom factor"""
if hasattr(self, 'setZoomFactor'):
# Assuming Qt >=v4.5
self.setZoomFactor(self.zoom_factor)
else:
# Qt v4.4
self.setTextSizeMultiplier(self.zoom_factor) |
Reimplement Qt method to prevent WebEngine to steal focus
when setting html on the page
Solution taken from
https://bugreports.qt.io/browse/QTBUG-52999 | def setHtml(self, html, baseUrl=QUrl()):
"""
Reimplement Qt method to prevent WebEngine to steal focus
when setting html on the page
Solution taken from
https://bugreports.qt.io/browse/QTBUG-52999
"""
if WEBENGINE:
self.setEnabled(False)
... |
Go to page *address* | def go_to(self, url_or_text):
"""Go to page *address*"""
if is_text_string(url_or_text):
url = QUrl(url_or_text)
else:
url = url_or_text
self.webview.load(url) |
Load URL from combo box first item | def url_combo_activated(self, valid):
"""Load URL from combo box first item"""
text = to_text_string(self.url_combo.currentText())
self.go_to(self.text_to_url(text)) |
Initialize plugin: connect signals, setup actions, etc.
It must be run at the end of __init__ | def initialize_plugin(self):
"""
Initialize plugin: connect signals, setup actions, etc.
It must be run at the end of __init__
"""
self.create_toggle_view_action()
self.plugin_actions = self.get_plugin_actions() + [MENU_SEPARATOR,
... |
Register QAction or QShortcut to Spyder main application.
if add_sc_to_tip is True, the shortcut is added to the
action's tooltip | def register_shortcut(self, qaction_or_qshortcut, context, name,
add_sc_to_tip=False):
"""
Register QAction or QShortcut to Spyder main application.
if add_sc_to_tip is True, the shortcut is added to the
action's tooltip
"""
self.main.register_s... |
Register widget shortcuts.
Widget interface must have a method called 'get_shortcut_data' | def register_widget_shortcuts(self, widget):
"""
Register widget shortcuts.
Widget interface must have a method called 'get_shortcut_data'
"""
for qshortcut, context, name in widget.get_shortcut_data():
self.register_shortcut(qshortcut, context, name) |
Dock widget visibility has changed. | def visibility_changed(self, enable):
"""
Dock widget visibility has changed.
"""
if self.dockwidget is None:
return
if enable:
self.dockwidget.raise_()
widget = self.get_focus_widget()
if widget is not None and self.undocked_window... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.