text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Gather data about files which may be recovered.
<END_TASK>
<USER_TASK:>
Description:
def gather_data(self):
"""
Gather data about files which may be recovered.
The data is stored in self.data as a list of tuples with the data
pertaining to the original file and the autosave file. Each element of
the tuple is a dict as returned by gather_file_data().
"""
|
self.data = []
try:
FileNotFoundError
except NameError: # Python 2
FileNotFoundError = OSError
# In Python 3, easier to use os.scandir()
try:
for name in os.listdir(self.autosave_dir):
full_name = osp.join(self.autosave_dir, name)
if osp.isdir(full_name):
continue
for orig, autosave in self.autosave_mapping.items():
if autosave == full_name:
orig_dict = gather_file_data(orig)
break
else:
orig_dict = None
autosave_dict = gather_file_data(full_name)
self.data.append((orig_dict, autosave_dict))
except FileNotFoundError: # autosave dir does not exist
pass
self.data.sort(key=recovery_data_key_function)
self.num_enabled = len(self.data)
|
<SYSTEM_TASK:>
Add label with explanation at top of dialog window.
<END_TASK>
<USER_TASK:>
Description:
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 = QLabel(txt, self)
label.setWordWrap(True)
self.layout.addWidget(label)
|
<SYSTEM_TASK:>
Add a label to specified cell in table.
<END_TASK>
<USER_TASK:>
Description:
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)
|
<SYSTEM_TASK:>
Add table with info about files to be recovered.
<END_TASK>
<USER_TASK:>
Description:
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().hide()
table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
table.setSelectionMode(QTableWidget.NoSelection)
# Show horizontal grid lines
table.setShowGrid(False)
table.setStyleSheet('::item { border-bottom: 1px solid gray }')
for idx, (original, autosave) in enumerate(self.data):
self.add_label_to_table(idx, 0, file_data_to_str(original))
self.add_label_to_table(idx, 1, file_data_to_str(autosave))
widget = QWidget()
layout = QHBoxLayout()
tooltip = _('Recover the autosave file to its original location, '
'replacing the original if it exists.')
button = QPushButton(_('Restore'))
button.setToolTip(tooltip)
button.clicked.connect(
lambda checked, my_idx=idx: self.restore(my_idx))
layout.addWidget(button)
tooltip = _('Delete the autosave file.')
button = QPushButton(_('Discard'))
button.setToolTip(tooltip)
button.clicked.connect(
lambda checked, my_idx=idx: self.discard(my_idx))
layout.addWidget(button)
tooltip = _('Display the autosave file (and the original, if it '
'exists) in Spyder\'s Editor. You will have to move '
'or delete it manually.')
button = QPushButton(_('Open'))
button.setToolTip(tooltip)
button.clicked.connect(
lambda checked, my_idx=idx: self.open_files(my_idx))
layout.addWidget(button)
widget.setLayout(layout)
self.table.setCellWidget(idx, 2, widget)
table.resizeRowsToContents()
table.resizeColumnsToContents()
# Need to add the "+ 2" because otherwise the table scrolls a tiny
# amount; no idea why
width = table.horizontalHeader().length() + 2
height = (table.verticalHeader().length()
+ table.horizontalHeader().height() + 2)
table.setFixedSize(width, height)
self.layout.addWidget(table)
|
<SYSTEM_TASK:>
Add a cancel button at the bottom of the dialog window.
<END_TASK>
<USER_TASK:>
Description:
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)
|
<SYSTEM_TASK:>
Change working directory to parent directory
<END_TASK>
<USER_TASK:>
Description:
def parent_directory(self):
"""Change working directory to parent directory"""
|
self.chdir(os.path.join(getcwd_or_home(), os.path.pardir))
|
<SYSTEM_TASK:>
Breakpoint list has changed
<END_TASK>
<USER_TASK:>
Description:
def breakpoints_changed(self):
"""Breakpoint list has changed"""
|
breakpoints = self.get_breakpoints()
if self.breakpoints != breakpoints:
self.breakpoints = breakpoints
self.save_breakpoints()
|
<SYSTEM_TASK:>
Return whether a string has open quotes.
<END_TASK>
<USER_TASK:>
Description:
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 quotes
- Copyright (C) 2008-2011 IPython Development Team
- Copyright (C) 2001-2007 Fernando Perez. <[email protected]>
- Copyright (C) 2001 Python Software Foundation, www.python.org
Distributed under the terms of the BSD License.
"""
|
# We check " first, then ', so complex cases with nested quotes will
# get the " to take precedence.
text = text.replace("\\'", "")
text = text.replace('\\"', '')
if text.count('"') % 2:
return '"'
elif text.count("'") % 2:
return "'"
else:
return ''
|
<SYSTEM_TASK:>
Control how to automatically insert quotes in various situations.
<END_TASK>
<USER_TASK:>
Description:
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 = self.editor.textCursor()
last_three = self.editor.get_text('sol', 'cursor')[-3:]
last_two = self.editor.get_text('sol', 'cursor')[-2:]
trailing_text = self.editor.get_text('cursor', 'eol').strip()
if self.editor.has_selected_text():
text = self.editor.get_selected_text()
self.editor.insert_text("{0}{1}{0}".format(char, text))
# keep text selected, for inserting multiple quotes
cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, 1)
cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor,
len(text))
self.editor.setTextCursor(cursor)
elif self.editor.in_comment():
self.editor.insert_text(char)
elif (len(trailing_text) > 0 and
not unmatched_quotes_in_line(line_to_cursor) == char and
not trailing_text[0] in (',', ':', ';', ')', ']', '}')):
self.editor.insert_text(char)
elif (unmatched_quotes_in_line(line_text) and
(not last_three == 3*char)):
self.editor.insert_text(char)
# Move to the right if we are before a quote
elif self.editor.next_char() == char:
cursor.movePosition(QTextCursor.NextCharacter,
QTextCursor.KeepAnchor, 1)
cursor.clearSelection()
self.editor.setTextCursor(cursor)
# Automatic insertion of triple double quotes (for docstrings)
elif last_three == 3*char:
self.editor.insert_text(3*char)
cursor = self.editor.textCursor()
cursor.movePosition(QTextCursor.PreviousCharacter,
QTextCursor.KeepAnchor, 3)
cursor.clearSelection()
self.editor.setTextCursor(cursor)
# If last two chars are quotes, just insert one more because most
# probably the user wants to write a docstring
elif last_two == 2*char:
self.editor.insert_text(char)
self.editor.delayed_popup_docstring()
# Automatic insertion of quotes
else:
self.editor.insert_text(2*char)
cursor = self.editor.textCursor()
cursor.movePosition(QTextCursor.PreviousCharacter)
self.editor.setTextCursor(cursor)
|
<SYSTEM_TASK:>
Populate the given ``combobox`` with the class or function names.
<END_TASK>
<USER_TASK:>
Description:
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 list element per
class or function defintion in the file.
Returns
-------
None
"""
|
combobox.clear()
combobox.addItem("<None>", 0)
# First create a list of fully-qualified names.
cb_data = []
for item in data:
fqn = item.name
for parent in reversed(item.parents):
fqn = parent.name + "." + fqn
cb_data.append((fqn, item))
for fqn, item in sorted(cb_data, key=operator.itemgetter(0)):
# Set the icon. Just threw this in here, streight from editortools.py
icon = None
if item.def_type == OED.FUNCTION_TOKEN:
if item.name.startswith('__'):
icon = ima.icon('private2')
elif item.name.startswith('_'):
icon = ima.icon('private1')
else:
icon = ima.icon('method')
else:
icon = ima.icon('class')
# Add the combobox item
if icon is not None:
combobox.addItem(icon, fqn, item)
else:
combobox.addItem(fqn, item)
|
<SYSTEM_TASK:>
Adjust the parent stack in-place as the trigger level changes.
<END_TASK>
<USER_TASK:>
Description:
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:`FoldScopeHelper` object.
parents : list of :class:`FoldScopeHelper`
The current list of parent objects.
Returns
-------
None
"""
|
if prev is None:
return
if fsh.fold_scope.trigger_level < prev.fold_scope.trigger_level:
diff = prev.fold_scope.trigger_level - fsh.fold_scope.trigger_level
del parents[-diff:]
elif fsh.fold_scope.trigger_level > prev.fold_scope.trigger_level:
parents.append(prev)
elif fsh.fold_scope.trigger_level == prev.fold_scope.trigger_level:
pass
|
<SYSTEM_TASK:>
Split out classes and methods into two separate lists.
<END_TASK>
<USER_TASK:>
Description:
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`
Two separate lists of :class:`FoldScopeHelper` objects. The former
contains only class definitions while the latter contains only
function/method definitions.
"""
|
classes = []
functions = []
for fold in folds:
if fold.def_type == OED.FUNCTION_TOKEN:
functions.append(fold)
elif fold.def_type == OED.CLASS_TOKEN:
classes.append(fold)
return classes, functions
|
<SYSTEM_TASK:>
Get the parents at a given linenum.
<END_TASK>
<USER_TASK:>
Description:
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
cursor position.
Returns
-------
parents : list of :class:`FoldScopeHelper`
A list of :class:`FoldScopeHelper` objects that describe the defintion
heirarcy for the given ``linenum``. The 1st index will be the
top-level parent defined at the module level while the last index
will be the class or funtion that contains ``linenum``.
"""
|
# Note: this might be able to be sped up by finding some kind of
# abort-early condition.
parents = []
for fold in folds:
start, end = fold.range
if linenum >= start and linenum <= end:
parents.append(fold)
else:
continue
return parents
|
<SYSTEM_TASK:>
Update the combobox with the selected item based on the parents.
<END_TASK>
<USER_TASK:>
Description:
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
"""
|
if parents is not None and len(parents) == 0:
combobox.setCurrentIndex(0)
else:
item = parents[-1]
for i in range(combobox.count()):
if combobox.itemData(i) == item:
combobox.setCurrentIndex(i)
break
|
<SYSTEM_TASK:>
Move the cursor to the selected definition.
<END_TASK>
<USER_TASK:>
Description:
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)
|
<SYSTEM_TASK:>
Updates the dropdowns to reflect the current class and function.
<END_TASK>
<USER_TASK:>
Description:
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.parents, self.class_cb)
|
<SYSTEM_TASK:>
Select cell under cursor
<END_TASK>
<USER_TASK:>
Description:
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)
cur_pos = prev_pos = cursor.position()
# Moving to the next line that is not a separator, if we are
# exactly at one of them
while self.is_cell_separator(cursor):
cursor.movePosition(QTextCursor.NextBlock)
prev_pos = cur_pos
cur_pos = cursor.position()
if cur_pos == prev_pos:
return cursor, False
prev_pos = cur_pos
# If not, move backwards to find the previous separator
while not self.is_cell_separator(cursor):
cursor.movePosition(QTextCursor.PreviousBlock)
prev_pos = cur_pos
cur_pos = cursor.position()
if cur_pos == prev_pos:
if self.is_cell_separator(cursor):
return cursor, False
else:
break
cursor.setPosition(prev_pos)
cell_at_file_start = cursor.atStart()
# Once we find it (or reach the beginning of the file)
# move to the next separator (or the end of the file)
# so we can grab the cell contents
while not self.is_cell_separator(cursor):
cursor.movePosition(QTextCursor.NextBlock,
QTextCursor.KeepAnchor)
cur_pos = cursor.position()
if cur_pos == prev_pos:
cursor.movePosition(QTextCursor.EndOfBlock,
QTextCursor.KeepAnchor)
break
prev_pos = cur_pos
cell_at_file_end = cursor.atEnd()
return cursor, cell_at_file_start and cell_at_file_end
|
<SYSTEM_TASK:>
Select cell under cursor in the visible portion of the file
<END_TASK>
<USER_TASK:>
Description:
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 if the entire visible portion of the file is selected"""
|
cursor = self.textCursor()
cursor.movePosition(QTextCursor.StartOfBlock)
cur_pos = prev_pos = cursor.position()
beg_pos = self.cursorForPosition(QPoint(0, 0)).position()
bottom_right = QPoint(self.viewport().width() - 1,
self.viewport().height() - 1)
end_pos = self.cursorForPosition(bottom_right).position()
# Moving to the next line that is not a separator, if we are
# exactly at one of them
while self.is_cell_separator(cursor):
cursor.movePosition(QTextCursor.NextBlock)
prev_pos = cur_pos
cur_pos = cursor.position()
if cur_pos == prev_pos:
return cursor, False, False
prev_pos = cur_pos
# If not, move backwards to find the previous separator
while not self.is_cell_separator(cursor)\
and cursor.position() >= beg_pos:
cursor.movePosition(QTextCursor.PreviousBlock)
prev_pos = cur_pos
cur_pos = cursor.position()
if cur_pos == prev_pos:
if self.is_cell_separator(cursor):
return cursor, False, False
else:
break
cell_at_screen_start = cursor.position() <= beg_pos
cursor.setPosition(prev_pos)
cell_at_file_start = cursor.atStart()
# Selecting cell header
if not cell_at_file_start:
cursor.movePosition(QTextCursor.PreviousBlock)
cursor.movePosition(QTextCursor.NextBlock,
QTextCursor.KeepAnchor)
# Once we find it (or reach the beginning of the file)
# move to the next separator (or the end of the file)
# so we can grab the cell contents
while not self.is_cell_separator(cursor)\
and cursor.position() <= end_pos:
cursor.movePosition(QTextCursor.NextBlock,
QTextCursor.KeepAnchor)
cur_pos = cursor.position()
if cur_pos == prev_pos:
cursor.movePosition(QTextCursor.EndOfBlock,
QTextCursor.KeepAnchor)
break
prev_pos = cur_pos
cell_at_file_end = cursor.atEnd()
cell_at_screen_end = cursor.position() >= end_pos
return cursor,\
cell_at_file_start and cell_at_file_end,\
cell_at_screen_start and cell_at_screen_end
|
<SYSTEM_TASK:>
Go to the next cell of lines
<END_TASK>
<USER_TASK:>
Description:
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
cursor.movePosition(QTextCursor.NextBlock)
prev_pos = cur_pos
cur_pos = cursor.position()
if cur_pos == prev_pos:
return
self.setTextCursor(cursor)
|
<SYSTEM_TASK:>
Go to the previous cell of lines
<END_TASK>
<USER_TASK:>
Description:
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)
cur_pos = prev_pos = cursor.position()
while not self.is_cell_separator(cursor):
# Move to the previous cell or the beginning of the current cell
cursor.movePosition(QTextCursor.PreviousBlock)
prev_pos = cur_pos
cur_pos = cursor.position()
if cur_pos == prev_pos:
return
self.setTextCursor(cursor)
|
<SYSTEM_TASK:>
Restore cursor selection from position bounds
<END_TASK>
<USER_TASK:>
Description:
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)
|
<SYSTEM_TASK:>
Duplicate current line or selected text
<END_TASK>
<USER_TASK:>
Description:
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.setPosition(end_pos)
# Check if end_pos is at the start of a block: if so, starting
# changes from the previous block
cursor.movePosition(QTextCursor.StartOfBlock,
QTextCursor.KeepAnchor)
if not to_text_string(cursor.selectedText()):
cursor.movePosition(QTextCursor.PreviousBlock)
end_pos = cursor.position()
cursor.setPosition(start_pos)
cursor.movePosition(QTextCursor.StartOfBlock)
while cursor.position() <= end_pos:
cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
if cursor.atEnd():
cursor_temp = QTextCursor(cursor)
cursor_temp.clearSelection()
cursor_temp.insertText(self.get_line_separator())
break
cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor)
text = cursor.selectedText()
cursor.clearSelection()
if not after_current_line:
# Moving cursor before current line/selected text
cursor.setPosition(start_pos)
cursor.movePosition(QTextCursor.StartOfBlock)
start_pos += len(text)
end_pos += len(text)
cursor.insertText(text)
cursor.endEditBlock()
self.setTextCursor(cursor)
self.__restore_selection(start_pos, end_pos)
|
<SYSTEM_TASK:>
Move current line or selected text
<END_TASK>
<USER_TASK:>
Description:
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 start location
cursor.setPosition(start_pos)
cursor.movePosition(QTextCursor.StartOfBlock)
start_pos = cursor.position()
# Get selection end location
cursor.setPosition(end_pos)
if not cursor.atBlockStart() or end_pos == start_pos:
cursor.movePosition(QTextCursor.EndOfBlock)
cursor.movePosition(QTextCursor.NextBlock)
end_pos = cursor.position()
# Check if selection ends on the last line of the document
if cursor.atEnd():
if not cursor.atBlockStart() or end_pos == start_pos:
last_line = True
# ------ Stop if at document boundary
cursor.setPosition(start_pos)
if cursor.atStart() and not after_current_line:
# Stop if selection is already at top of the file while moving up
cursor.endEditBlock()
self.setTextCursor(cursor)
self.__restore_selection(start_pos, end_pos)
return
cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
if last_line and after_current_line:
# Stop if selection is already at end of the file while moving down
cursor.endEditBlock()
self.setTextCursor(cursor)
self.__restore_selection(start_pos, end_pos)
return
# ------ Move text
sel_text = to_text_string(cursor.selectedText())
cursor.removeSelectedText()
if after_current_line:
# Shift selection down
text = to_text_string(cursor.block().text())
sel_text = os.linesep + sel_text[0:-1] # Move linesep at the start
cursor.movePosition(QTextCursor.EndOfBlock)
start_pos += len(text)+1
end_pos += len(text)
if not cursor.atEnd():
end_pos += 1
else:
# Shift selection up
if last_line:
# Remove the last linesep and add it to the selected text
cursor.deletePreviousChar()
sel_text = sel_text + os.linesep
cursor.movePosition(QTextCursor.StartOfBlock)
end_pos += 1
else:
cursor.movePosition(QTextCursor.PreviousBlock)
text = to_text_string(cursor.block().text())
start_pos -= len(text)+1
end_pos -= len(text)+1
cursor.insertText(sel_text)
cursor.endEditBlock()
self.setTextCursor(cursor)
self.__restore_selection(start_pos, end_pos)
|
<SYSTEM_TASK:>
Go to the end of the current line and create a new line
<END_TASK>
<USER_TASK:>
Description:
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())
|
<SYSTEM_TASK:>
Extend current selection to complete lines
<END_TASK>
<USER_TASK:>
Description:
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)
if cursor.atBlockStart():
cursor.movePosition(QTextCursor.PreviousBlock,
QTextCursor.KeepAnchor)
cursor.movePosition(QTextCursor.EndOfBlock,
QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
|
<SYSTEM_TASK:>
Unselect read-only parts in shell, like prompt
<END_TASK>
<USER_TASK:>
Description:
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([position_from, start])
else:
end = max([position_from, end])
self.set_selection(start, end)
|
<SYSTEM_TASK:>
In shell, avoid editing text except between prompt and EOF
<END_TASK>
<USER_TASK:>
Description:
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.position()
if cursor_position < position_from or cursor_position > position_to:
self.set_cursor_position(position_to)
|
<SYSTEM_TASK:>
Hide calltip when necessary
<END_TASK>
<USER_TASK:>
Description:
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 in (Qt.Key_ParenRight, Qt.Key_Period, Qt.Key_Tab)
if calltip_char not in ('?', '(') or before or other:
QToolTip.hideText()
except (IndexError, TypeError):
QToolTip.hideText()
|
<SYSTEM_TASK:>
Convert options into commands
<END_TASK>
<USER_TASK:>
Description:
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 the single "
"instance mode has been turned on (default)")
parser.add_argument('--defaults', dest="reset_to_defaults",
action='store_true', default=False,
help="Reset configuration settings to defaults")
parser.add_argument('--reset', dest="reset_config_files",
action='store_true', default=False,
help="Remove all configuration files!")
parser.add_argument('--optimize', action='store_true', default=False,
help="Optimize Spyder bytecode (this may require "
"administrative privileges)")
parser.add_argument('-w', '--workdir', dest="working_directory", default=None,
help="Default working directory")
parser.add_argument('--hide-console', action='store_true', default=False,
help="Hide parent console window (Windows)")
parser.add_argument('--show-console', action='store_true', default=False,
help="(Deprecated) Does nothing, now the default behavior "
"is to show the console")
parser.add_argument('--multithread', dest="multithreaded",
action='store_true', default=False,
help="Internal console is executed in another thread "
"(separate from main application thread)")
parser.add_argument('--profile', action='store_true', default=False,
help="Profile mode (internal test, "
"not related with Python profiling)")
parser.add_argument('--window-title', type=str, default=None,
help="String to show in the main window title")
parser.add_argument('-p', '--project', default=None, type=str,
dest="project",
help="Path that contains an Spyder project")
parser.add_argument('--opengl', default=None,
dest="opengl_implementation",
choices=['software', 'desktop', 'gles'],
help=("OpenGL implementation to pass to Qt")
)
parser.add_argument('--debug-info', default=None,
dest="debug_info",
choices=['minimal', 'verbose'],
help=("Level of internal debugging info to give. "
"'minimal' only logs a small amount of "
"confirmation messages and 'verbose' logs a "
"lot of detailed information.")
)
parser.add_argument('--debug-output', default='terminal',
dest="debug_output",
choices=['terminal', 'file'],
help=("Print internal debugging info either to the "
"terminal or to a file called spyder-debug.log "
"in your current working directory. Default is "
"'terminal'.")
)
parser.add_argument('files', nargs='*')
options = parser.parse_args(argv)
args = options.files
return options, args
|
<SYSTEM_TASK:>
Set a list of files opened by the project.
<END_TASK>
<USER_TASK:>
Description:
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',
list(OrderedDict.fromkeys(recent_files)))
except EnvironmentError:
pass
|
<SYSTEM_TASK:>
Return a list of files opened by the project.
<END_TASK>
<USER_TASK:>
Description:
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 recent_file in recent_files[:]:
if not os.path.isfile(recent_file):
recent_files.remove(recent_file)
return list(OrderedDict.fromkeys(recent_files))
|
<SYSTEM_TASK:>
Rename project and rename its root path accordingly.
<END_TASK>
<USER_TASK:>
Description:
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 # ??
self.save()
|
<SYSTEM_TASK:>
Instruct current editorstack to autosave files where necessary.
<END_TASK>
<USER_TASK:>
Description:
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()
|
<SYSTEM_TASK:>
Create unique autosave file name for specified file name.
<END_TASK>
<USER_TASK:>
Description:
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.basename(filename)
autosave_filename = osp.join(autosave_dir, basename)
if autosave_filename in self.name_mapping.values():
counter = 0
root, ext = osp.splitext(basename)
while autosave_filename in self.name_mapping.values():
counter += 1
autosave_basename = '{}-{}{}'.format(root, counter, ext)
autosave_filename = osp.join(autosave_dir, autosave_basename)
return autosave_filename
|
<SYSTEM_TASK:>
Remove autosave file for specified file.
<END_TASK>
<USER_TASK:>
Description:
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:
return
autosave_filename = self.name_mapping[filename]
try:
os.remove(autosave_filename)
except EnvironmentError as error:
action = (_('Error while removing autosave file {}')
.format(autosave_filename))
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled()
del self.name_mapping[filename]
self.stack.sig_option_changed.emit(
'autosave_mapping', self.name_mapping)
logger.debug('Removing autosave file %s', autosave_filename)
|
<SYSTEM_TASK:>
Get name of autosave file for specified file name.
<END_TASK>
<USER_TASK:>
Description:
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 update the mapping.
Args:
filename (str): original file name
"""
|
try:
autosave_filename = self.name_mapping[filename]
except KeyError:
autosave_dir = get_conf_path('autosave')
if not osp.isdir(autosave_dir):
try:
os.mkdir(autosave_dir)
except EnvironmentError as error:
action = _('Error while creating autosave directory')
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled()
autosave_filename = self.create_unique_autosave_filename(
filename, autosave_dir)
self.name_mapping[filename] = autosave_filename
self.stack.sig_option_changed.emit(
'autosave_mapping', self.name_mapping)
logger.debug('New autosave file name')
return autosave_filename
|
<SYSTEM_TASK:>
Autosave a file.
<END_TASK>
<USER_TASK:>
Description:
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 the `changed_since_autosave` flag. Errors raised when saving
are silently ignored.
Args:
index (int): index into self.stack.data
"""
|
finfo = self.stack.data[index]
document = finfo.editor.document()
if not document.changed_since_autosave or finfo.newly_created:
return
autosave_filename = self.get_autosave_filename(finfo.filename)
logger.debug('Autosaving %s to %s', finfo.filename, autosave_filename)
try:
self.stack._write_to_file(finfo, autosave_filename)
document.changed_since_autosave = False
except EnvironmentError as error:
action = (_('Error while autosaving {} to {}')
.format(finfo.filename, autosave_filename))
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled()
|
<SYSTEM_TASK:>
Autosave all opened files.
<END_TASK>
<USER_TASK:>
Description:
def autosave_all(self):
"""Autosave all opened files."""
|
for index in range(self.stack.get_stack_count()):
self.autosave(index)
|
<SYSTEM_TASK:>
Fixtures that returns a temporary CONF element.
<END_TASK>
<USER_TASK:>
Description:
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_mode=True,
)
def fin():
"""
Fixture finalizer to delete the temporary CONF element.
"""
shutil.rmtree(SUBFOLDER)
request.addfinalizer(fin)
return CONF
|
<SYSTEM_TASK:>
This property holds the vertical offset of the scroll flag area
<END_TASK>
<USER_TASK:>
Description:
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 the slider handle may move.
groove_rect = style.subControlRect(
QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self)
return groove_rect.y()
|
<SYSTEM_TASK:>
Override Qt method.
<END_TASK>
<USER_TASK:>
Description:
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 warnings and todos
block = self.editor.document().firstBlock()
for line_number in range(self.editor.document().blockCount()+1):
data = block.userData()
if data:
if data.code_analysis:
# Paint the warnings
color = self.editor.warning_color
for source, code, severity, message in data.code_analysis:
error = severity == DiagnosticSeverity.ERROR
if error:
color = self.editor.error_color
break
self.set_painter(painter, color)
painter.drawRect(make_flag(line_number))
if data.todo:
# Paint the todos
self.set_painter(painter, self.editor.todo_color)
painter.drawRect(make_flag(line_number))
if data.breakpoint:
# Paint the breakpoints
self.set_painter(painter, self.editor.breakpoint_color)
painter.drawRect(make_flag(line_number))
block = block.next()
# Paint the occurrences
if self.editor.occurrences:
self.set_painter(painter, self.editor.occurrence_color)
for line_number in self.editor.occurrences:
painter.drawRect(make_flag(line_number))
# Paint the found results
if self.editor.found_results:
self.set_painter(painter, self.editor.found_results_color)
for line_number in self.editor.found_results:
painter.drawRect(make_flag(line_number))
# Paint the slider range
if not self._unit_testing:
alt = QApplication.queryKeyboardModifiers() & Qt.AltModifier
else:
alt = self._alt_key_is_down
cursor_pos = self.mapFromGlobal(QCursor().pos())
is_over_self = self.rect().contains(cursor_pos)
is_over_editor = self.editor.rect().contains(
self.editor.mapFromGlobal(QCursor().pos()))
# We use QRect.contains instead of QWidget.underMouse method to
# determined if the cursor is over the editor or the flag scrollbar
# because the later gives a wrong result when a mouse button
# is pressed.
if ((is_over_self or (alt and is_over_editor)) and self.slider):
pen_color = QColor(Qt.gray)
pen_color.setAlphaF(.85)
painter.setPen(pen_color)
brush_color = QColor(Qt.gray)
brush_color.setAlphaF(.5)
painter.setBrush(QBrush(brush_color))
painter.drawRect(self.make_slider_range(cursor_pos))
self._range_indicator_is_visible = True
else:
self._range_indicator_is_visible = False
|
<SYSTEM_TASK:>
Return the pixel span height of the scrollbar area in which
<END_TASK>
<USER_TASK:>
Description:
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 which the slider handle may move.
groove_rect = style.subControlRect(
QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self)
return float(groove_rect.height())
|
<SYSTEM_TASK:>
Return the value span height of the scrollbar
<END_TASK>
<USER_TASK:>
Description:
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()
|
<SYSTEM_TASK:>
Set scroll flag area painter pen and brush colors
<END_TASK>
<USER_TASK:>
Description:
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)))
|
<SYSTEM_TASK:>
Action to be performed on first plugin registration
<END_TASK>
<USER_TASK:>
Description:
def on_first_registration(self):
"""Action to be performed on first plugin registration"""
|
self.main.tabify_plugins(self.main.help, self)
self.dockwidget.hide()
|
<SYSTEM_TASK:>
Return color that is lighter or darker than the base color.
<END_TASK>
<USER_TASK:>
Description:
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 (%)
:return A lighter or darker color.
"""
|
base_color = QColor(base_color)
if base_color.lightness() > 128:
return base_color.darker(factor)
else:
if base_color == QColor('#000000'):
return drift_color(QColor('#101010'), factor + 20)
else:
return base_color.lighter(factor + 10)
|
<SYSTEM_TASK:>
Gets the list of ParenthesisInfo for specific text block.
<END_TASK>
<USER_TASK:>
Description:
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
:param editor: code editor instance
:param block: block to parse
:param character: character to look for.
"""
text = block.text()
symbols = []
cursor = QTextCursor(block)
cursor.movePosition(cursor.StartOfBlock)
pos = text.find(character, 0)
cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)
while pos != -1:
if not TextHelper(editor).is_comment_or_string(cursor):
# skips symbols in string literal or comment
info = ParenthesisInfo(pos, character)
symbols.append(info)
pos = text.find(character, pos + 1)
cursor.movePosition(cursor.StartOfBlock)
cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)
return symbols
parentheses = sorted(
list_symbols(editor, block, '(') + list_symbols(editor, block, ')'),
key=lambda x: x.position)
square_brackets = sorted(
list_symbols(editor, block, '[') + list_symbols(editor, block, ']'),
key=lambda x: x.position)
braces = sorted(
list_symbols(editor, block, '{') + list_symbols(editor, block, '}'),
key=lambda x: x.position)
return parentheses, square_brackets, braces
|
<SYSTEM_TASK:>
Cache text cursor position and restore it when the wrapped
<END_TASK>
<USER_TASK:>
Description:
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 = editor.verticalScrollBar()
spos = sb.sliderPosition()
pos = editor.textCursor().position()
retval = func(editor, *args, **kwds)
text_cursor = editor.textCursor()
text_cursor.setPosition(pos)
editor.setTextCursor(text_cursor)
sb.setSliderPosition(spos)
return retval
return wrapper
|
<SYSTEM_TASK:>
Show a wait cursor while the wrapped function is running. The cursor is
<END_TASK>
<USER_TASK:>
Description:
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(Qt.WaitCursor))
try:
ret_val = func(*args, **kwargs)
finally:
QApplication.restoreOverrideCursor()
return ret_val
return wrapper
|
<SYSTEM_TASK:>
Return whether the block of user data is empty.
<END_TASK>
<USER_TASK:>
Description:
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)
|
<SYSTEM_TASK:>
Request a job execution.
<END_TASK>
<USER_TASK:>
Description:
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 args: job's position arguments
:param kwargs: job's keyworded arguments
"""
|
self.cancel_requests()
self._job = job
self._args = args
self._kwargs = kwargs
self._timer.start(self.delay)
|
<SYSTEM_TASK:>
Execute the requested job after the timer has timeout.
<END_TASK>
<USER_TASK:>
Description:
def _exec_requested_job(self):
"""Execute the requested job after the timer has timeout."""
|
self._timer.stop()
self._job(*self._args, **self._kwargs)
|
<SYSTEM_TASK:>
Moves the text cursor to the specified position.
<END_TASK>
<USER_TASK:>
Description:
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 cursor. False will return the cursor
without setting it on the editor.
:param word: Highlight the word, when moving to the line.
:return: The new text cursor
:rtype: QtGui.QTextCursor
"""
|
line = min(line, self.line_count())
text_cursor = self._move_cursor_to(line)
if column:
text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor,
column)
if end_column:
text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor,
end_column)
if move:
block = text_cursor.block()
self.unfold_if_colapsed(block)
self._editor.setTextCursor(text_cursor)
if self._editor.isVisible():
self._editor.centerCursor()
else:
self._editor.focus_in.connect(
self._editor.center_cursor_on_next_focus)
if word and to_text_string(word) in to_text_string(block.text()):
self._editor.find(word, QTextDocument.FindCaseSensitively)
return text_cursor
|
<SYSTEM_TASK:>
Unfold parent fold trigger if the block is collapsed.
<END_TASK>
<USER_TASK:>
Description:
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.plugins.editor.utils.folding import FoldScope
if not block.isVisible():
block = FoldScope.find_parent_scope(block)
if TextBlockHelper.is_collapsed(block):
folding_panel.toggle_fold_trigger(block)
|
<SYSTEM_TASK:>
Gets the text of the specified line.
<END_TASK>
<USER_TASK:>
Description:
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 block.text()
|
<SYSTEM_TASK:>
Replace an entire line with ``new_text``.
<END_TASK>
<USER_TASK:>
Description:
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)
text_cursor.select(text_cursor.LineUnderCursor)
text_cursor.insertText(new_text)
editor.setTextCursor(text_cursor)
|
<SYSTEM_TASK:>
Removes the last line of the document.
<END_TASK>
<USER_TASK:>
Description:
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.removeSelectedText()
text_cursor.deletePreviousChar()
editor.setTextCursor(text_cursor)
|
<SYSTEM_TASK:>
Removes trailing whitespaces and ensure one single blank line at the
<END_TASK>
<USER_TASK:>
Description:
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()
pos = self.cursor_position()
editor.textCursor().beginEditBlock()
# cleanup whitespaces
editor._cleaning = True
eaten = 0
removed = set()
for line in editor._modified_lines:
# parse line before and line after modified line (for cases where
# key_delete or key_return has been pressed)
for j in range(-1, 2):
# skip current line
if line + j != pos[0]:
if line + j >= 0:
txt = self.line_text(line + j)
stxt = txt.rstrip()
if txt != stxt:
self.set_line_text(line + j, stxt)
removed.add(line + j)
editor._modified_lines -= removed
# ensure there is only one blank line left at the end of the file
i = self.line_count()
while i:
line = self.line_text(i - 1)
if line.strip():
break
self.remove_last_line()
i -= 1
if self.line_text(self.line_count() - 1):
editor.appendPlainText('')
# restore cursor and scrollbars
text_cursor = editor.textCursor()
doc = editor.document()
assert isinstance(doc, QTextDocument)
text_cursor = self._move_cursor_to(pos[0])
text_cursor.movePosition(text_cursor.StartOfLine,
text_cursor.MoveAnchor)
cpos = text_cursor.position()
text_cursor.select(text_cursor.LineUnderCursor)
if text_cursor.selectedText():
text_cursor.setPosition(cpos)
offset = pos[1] - eaten
text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor,
offset)
else:
text_cursor.setPosition(cpos)
editor.setTextCursor(text_cursor)
editor.verticalScrollBar().setValue(value)
text_cursor.endEditBlock()
editor._cleaning = False
|
<SYSTEM_TASK:>
Selects an entire line.
<END_TASK>
<USER_TASK:>
Description:
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 without setting it
on the editor.
:return: QTextCursor
"""
|
if line is None:
line = self.current_line_nbr()
return self.select_lines(line, line, apply_selection=apply_selection)
|
<SYSTEM_TASK:>
Returns the line number from the y_pos.
<END_TASK>
<USER_TASK:>
Description:
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 in editor.visible_blocks:
if top <= y_pos <= top + height:
return line
return -1
|
<SYSTEM_TASK:>
Gets the character that is on the right of the text cursor.
<END_TASK>
<USER_TASK:>
Description:
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):
next_char = next_char[0]
else:
next_char = None
return next_char
|
<SYSTEM_TASK:>
Inserts text at the cursor position.
<END_TASK>
<USER_TASK:>
Description:
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 the inserted text).
"""
|
text_cursor = self._editor.textCursor()
if keep_position:
s = text_cursor.selectionStart()
e = text_cursor.selectionEnd()
text_cursor.insertText(text)
if keep_position:
text_cursor.setPosition(s)
text_cursor.setPosition(e, text_cursor.KeepAnchor)
self._editor.setTextCursor(text_cursor)
|
<SYSTEM_TASK:>
Moves the cursor on the right.
<END_TASK>
<USER_TASK:>
Description:
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._editor.textCursor()
text_cursor.movePosition(
text_cursor.Right, text_cursor.KeepAnchor if keep_anchor else
text_cursor.MoveAnchor, nb_chars)
self._editor.setTextCursor(text_cursor)
|
<SYSTEM_TASK:>
Performs extended word selection. Extended selection consists in
<END_TASK>
<USER_TASK:>
Description:
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 may extend a
word.
"""
|
cursor = self._editor.textCursor()
original_pos = cursor.position()
start_pos = None
end_pos = None
# go left
stop = False
seps = self._editor.word_separators + [' ']
while not stop:
cursor.clearSelection()
cursor.movePosition(cursor.Left, cursor.KeepAnchor)
char = cursor.selectedText()
if cursor.atBlockStart():
stop = True
start_pos = cursor.position()
elif char in seps and char not in continuation_chars:
stop = True
start_pos = cursor.position() + 1
# go right
cursor.setPosition(original_pos)
stop = False
while not stop:
cursor.clearSelection()
cursor.movePosition(cursor.Right, cursor.KeepAnchor)
char = cursor.selectedText()
if cursor.atBlockEnd():
stop = True
end_pos = cursor.position()
if char in seps:
end_pos -= 1
elif char in seps and char not in continuation_chars:
stop = True
end_pos = cursor.position() - 1
if start_pos and end_pos:
cursor.setPosition(start_pos)
cursor.movePosition(cursor.Right, cursor.KeepAnchor,
end_pos - start_pos)
self._editor.setTextCursor(cursor)
|
<SYSTEM_TASK:>
Sets the user state, generally used for syntax highlighting.
<END_TASK>
<USER_TASK:>
Description:
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_state == -1:
user_state = 0
higher_part = user_state & 0x7FFF0000
state &= 0x0000FFFF
state |= higher_part
block.setUserState(state)
|
<SYSTEM_TASK:>
Sets the block fold level.
<END_TASK>
<USER_TASK:>
Description:
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 >= 0x3FF:
val = 0x3FF
state &= 0x7C00FFFF
state |= val << 16
block.setUserState(state)
|
<SYSTEM_TASK:>
Checks if the block is a fold trigger.
<END_TASK>
<USER_TASK:>
Description:
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.userState()
if state == -1:
state = 0
return bool(state & 0x04000000)
|
<SYSTEM_TASK:>
Checks if the block is expanded or collased.
<END_TASK>
<USER_TASK:>
Description:
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:
state = 0
return bool(state & 0x08000000)
|
<SYSTEM_TASK:>
Override Qt method to stops timers if widget is not visible.
<END_TASK>
<USER_TASK:>
Description:
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)
|
<SYSTEM_TASK:>
Print a warning message on the rich text view
<END_TASK>
<USER_TASK:>
Description:
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)
|
<SYSTEM_TASK:>
Generate the html_context dictionary for our Sphinx conf file.
<END_TASK>
<USER_TASK:>
Description:
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 how the webpage is rendered in connection with
Sphinx
Parameters
----------
name : str
Object's name.
note : str
A note describing what type has the function or method being
introspected
argspec : str
Argspec of the the function or method being introspected
math : bool
Turn on/off Latex rendering on the OI. If False, Latex will be shown in
plain text.
collapse : bool
Collapse sections
img_path : str
Path for images relative to the file containing the docstring
Returns
-------
A dict of strings to be used by Jinja to generate the webpage
"""
|
if img_path and os.name == 'nt':
img_path = img_path.replace('\\', '/')
context = \
{
# Arg dependent variables
'math_on': 'true' if math else '',
'name': name,
'argspec': argspec,
'note': note,
'collapse': collapse,
'img_path': img_path,
# Static variables
'css_path': css_path,
'js_path': JS_PATH,
'jquery_path': JQUERY_PATH,
'mathjax_path': MATHJAX_PATH,
'right_sphinx_version': '' if sphinx.__version__ < "1.1" else 'true',
'platform': sys.platform
}
return context
|
<SYSTEM_TASK:>
Runs Sphinx on a docstring and outputs the processed documentation.
<END_TASK>
<USER_TASK:>
Description:
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
rendered (through the Sphinx variable *html_context*).
buildername: str
It can be either `html` or `text`.
Returns
-------
An Sphinx-processed string, in either HTML or plain text format, depending
on the value of `buildername`
"""
|
srcdir = mkdtemp()
srcdir = encoding.to_unicode_from_fs(srcdir)
destdir = osp.join(srcdir, '_build')
rst_name = osp.join(srcdir, 'docstring.rst')
if buildername == 'html':
suffix = '.html'
else:
suffix = '.txt'
output_name = osp.join(destdir, 'docstring' + suffix)
# This is needed so users can type \\ on latex eqnarray envs inside raw
# docstrings
if context['right_sphinx_version'] and context['math_on']:
docstring = docstring.replace('\\\\', '\\\\\\\\')
# Add a class to several characters on the argspec. This way we can
# highlight them using css, in a similar way to what IPython does.
# NOTE: Before doing this, we escape common html chars so that they
# don't interfere with the rest of html present in the page
argspec = escape(context['argspec'])
for char in ['=', ',', '(', ')', '*', '**']:
argspec = argspec.replace(char,
'<span class="argspec-highlight">' + char + '</span>')
context['argspec'] = argspec
doc_file = codecs.open(rst_name, 'w', encoding='utf-8')
doc_file.write(docstring)
doc_file.close()
temp_confdir = False
if temp_confdir:
# TODO: This may be inefficient. Find a faster way to do it.
confdir = mkdtemp()
confdir = encoding.to_unicode_from_fs(confdir)
generate_configuration(confdir)
else:
confdir = osp.join(get_module_source_path('spyder.plugins.help.utils'))
confoverrides = {'html_context': context}
doctreedir = osp.join(srcdir, 'doctrees')
sphinx_app = Sphinx(srcdir, confdir, destdir, doctreedir, buildername,
confoverrides, status=None, warning=None,
freshenv=True, warningiserror=False, tags=None)
try:
sphinx_app.build(None, [rst_name])
except SystemMessage:
output = _("It was not possible to generate rich text help for this "
"object.</br>"
"Please see it in plain text.")
return warning(output)
# TODO: Investigate if this is necessary/important for us
if osp.exists(output_name):
output = codecs.open(output_name, 'r', encoding='utf-8').read()
output = output.replace('<pre>', '<pre class="literal-block">')
else:
output = _("It was not possible to generate rich text help for this "
"object.</br>"
"Please see it in plain text.")
return warning(output)
if temp_confdir:
shutil.rmtree(confdir, ignore_errors=True)
shutil.rmtree(srcdir, ignore_errors=True)
return output
|
<SYSTEM_TASK:>
Generates a Sphinx configuration in `directory`.
<END_TASK>
<USER_TASK:>
Description:
def generate_configuration(directory):
"""
Generates a Sphinx configuration in `directory`.
Parameters
----------
directory : str
Base directory to use
"""
|
# conf.py file for Sphinx
conf = osp.join(get_module_source_path('spyder.plugins.help.utils'),
'conf.py')
# Docstring layout page (in Jinja):
layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html')
os.makedirs(osp.join(directory, 'templates'))
os.makedirs(osp.join(directory, 'static'))
shutil.copy(conf, directory)
shutil.copy(layout, osp.join(directory, 'templates'))
open(osp.join(directory, '__init__.py'), 'w').write('')
open(osp.join(directory, 'static', 'empty'), 'w').write('')
|
<SYSTEM_TASK:>
Update encoding of current file.
<END_TASK>
<USER_TASK:>
Description:
def update_encoding(self, encoding):
"""Update encoding of current file."""
|
value = str(encoding).upper()
self.set_value(value)
|
<SYSTEM_TASK:>
Register shell with variable explorer.
<END_TASK>
<USER_TASK:>
Description:
def add_shellwidget(self, shellwidget):
"""
Register shell with variable explorer.
This function opens a new NamespaceBrowser for browsing the variables
in the shell.
"""
|
shellwidget_id = id(shellwidget)
if shellwidget_id not in self.shellwidgets:
self.options_button.setVisible(True)
nsb = NamespaceBrowser(self, options_button=self.options_button)
nsb.set_shellwidget(shellwidget)
nsb.setup(**self.get_settings())
nsb.sig_option_changed.connect(self.change_option)
nsb.sig_free_memory.connect(self.free_memory)
self.add_widget(nsb)
self.shellwidgets[shellwidget_id] = nsb
self.set_shellwidget_from_id(shellwidget_id)
return nsb
|
<SYSTEM_TASK:>
Import data in current namespace
<END_TASK>
<USER_TASK:>
Description:
def import_data(self, fname):
"""Import data in current namespace"""
|
if self.count():
nsb = self.current_widget()
nsb.refresh_table()
nsb.import_data(filenames=fname)
if self.dockwidget and not self.ismaximized:
self.dockwidget.setVisible(True)
self.dockwidget.raise_()
|
<SYSTEM_TASK:>
Reimplemented to avoid formatting actions
<END_TASK>
<USER_TASK:>
Description:
def validate(self, qstr, editing=True):
"""Reimplemented to avoid formatting actions"""
|
valid = self.is_valid(qstr)
if self.hasFocus() and valid is not None:
if editing and not valid:
# Combo box text is being modified: invalidate the entry
self.show_tip(self.tips[valid])
self.valid.emit(False, False)
else:
# A new item has just been selected
if valid:
self.selected()
else:
self.valid.emit(False, False)
|
<SYSTEM_TASK:>
Check source code with pyflakes
<END_TASK>
<USER_TASK:>
Description:
def check_with_pyflakes(source_code, filename=None):
"""Check source code with pyflakes
Returns an empty list if pyflakes is not installed"""
|
try:
if filename is None:
filename = '<string>'
try:
source_code += '\n'
except TypeError:
# Python 3
source_code += to_binary_string('\n')
import _ast
from pyflakes.checker import Checker
# First, compile into an AST and handle syntax errors.
try:
tree = compile(source_code, filename, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError as value:
# If there's an encoding problem with the file, the text is None.
if value.text is None:
results = []
else:
results = [(value.args[0], value.lineno)]
except (ValueError, TypeError):
# Example of ValueError: file contains invalid \x escape character
# (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674797)
# Example of TypeError: file contains null character
# (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674796)
results = []
else:
# Okay, it's syntactically valid. Now check it.
w = Checker(tree, filename)
w.messages.sort(key=lambda x: x.lineno)
results = []
coding = encoding.get_coding(source_code)
lines = source_code.splitlines()
for warning in w.messages:
if 'analysis:ignore' not in \
to_text_string(lines[warning.lineno-1], coding):
results.append((warning.message % warning.message_args,
warning.lineno))
except Exception:
# Never return None to avoid lock in spyder/widgets/editor.py
# See Issue 1547
results = []
if DEBUG_EDITOR:
traceback.print_exc() # Print exception in internal console
return results
|
<SYSTEM_TASK:>
Return checker executable in the form of a list of arguments
<END_TASK>
<USER_TASK:>
Description:
def get_checker_executable(name):
"""Return checker executable in the form of a list of arguments
for subprocess.Popen"""
|
if programs.is_program_installed(name):
# Checker is properly installed
return [name]
else:
path1 = programs.python_script_exists(package=None,
module=name+'_script')
path2 = programs.python_script_exists(package=None, module=name)
if path1 is not None: # checker_script.py is available
# Checker script is available but has not been installed
# (this may work with pyflakes)
return [sys.executable, path1]
elif path2 is not None: # checker.py is available
# Checker package is available but its script has not been
# installed (this works with pycodestyle but not with pyflakes)
return [sys.executable, path2]
|
<SYSTEM_TASK:>
Select the right file uri scheme according to the operating system
<END_TASK>
<USER_TASK:>
Description:
def file_uri(fname):
"""Select the right file uri scheme according to the operating system"""
|
if os.name == 'nt':
# Local file
if re.search(r'^[a-zA-Z]:', fname):
return 'file:///' + fname
# UNC based path
else:
return 'file://' + fname
else:
return 'file://' + fname
|
<SYSTEM_TASK:>
Install Qt translator to the QApplication instance
<END_TASK>
<USER_TASK:>
Description:
def install_translator(qapp):
"""Install Qt translator to the QApplication instance"""
|
global QT_TRANSLATOR
if QT_TRANSLATOR is None:
qt_translator = QTranslator()
if qt_translator.load("qt_"+QLocale.system().name(),
QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
QT_TRANSLATOR = qt_translator # Keep reference alive
if QT_TRANSLATOR is not None:
qapp.installTranslator(QT_TRANSLATOR)
|
<SYSTEM_TASK:>
Create a QToolButton directly from a QAction object
<END_TASK>
<USER_TASK:>
Description:
def action2button(action, autoraise=True, text_beside_icon=False, parent=None):
"""Create a QToolButton directly from a QAction object"""
|
if parent is None:
parent = action.parent()
button = QToolButton(parent)
button.setDefaultAction(action)
button.setAutoRaise(autoraise)
if text_beside_icon:
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
return button
|
<SYSTEM_TASK:>
Add the shortcut associated with a given action to its tooltip
<END_TASK>
<USER_TASK:>
Description:
def add_shortcut_to_tooltip(action, context, name):
"""Add the shortcut associated with a given action to its tooltip"""
|
action.setToolTip(action.toolTip() + ' (%s)' %
get_shortcut(context=context, name=name))
|
<SYSTEM_TASK:>
Add actions to a QMenu or a QToolBar.
<END_TASK>
<USER_TASK:>
Description:
def add_actions(target, actions, insert_before=None):
"""Add actions to a QMenu or a QToolBar."""
|
previous_action = None
target_actions = list(target.actions())
if target_actions:
previous_action = target_actions[-1]
if previous_action.isSeparator():
previous_action = None
for action in actions:
if (action is None) and (previous_action is not None):
if insert_before is None:
target.addSeparator()
else:
target.insertSeparator(insert_before)
elif isinstance(action, QMenu):
if insert_before is None:
target.addMenu(action)
else:
target.insertMenu(insert_before, action)
elif isinstance(action, QAction):
if isinstance(action, SpyderAction):
if isinstance(target, QMenu) or not isinstance(target, QToolBar):
try:
action = action.no_icon_action
except RuntimeError:
continue
if insert_before is None:
# This is needed in order to ignore adding an action whose
# wrapped C/C++ object has been deleted. See issue 5074
try:
target.addAction(action)
except RuntimeError:
continue
else:
target.insertAction(insert_before, action)
previous_action = action
|
<SYSTEM_TASK:>
Create action to run a program
<END_TASK>
<USER_TASK:>
Description:
def create_program_action(parent, text, name, icon=None, nt_name=None):
"""Create action to run a program"""
|
if is_text_string(icon):
icon = get_icon(icon)
if os.name == 'nt' and nt_name is not None:
name = nt_name
path = programs.find_program(name)
if path is not None:
return create_action(parent, text, icon=icon,
triggered=lambda: programs.run_program(name))
|
<SYSTEM_TASK:>
Create action to run a GUI based Python script
<END_TASK>
<USER_TASK:>
Description:
def create_python_script_action(parent, text, icon, package, module, args=[]):
"""Create action to run a GUI based Python script"""
|
if is_text_string(icon):
icon = get_icon(icon)
if programs.python_script_exists(package, module):
return create_action(parent, text, icon=icon,
triggered=lambda:
programs.run_python_script(package, module, args))
|
<SYSTEM_TASK:>
Generic method to show a non-modal dialog and keep reference
<END_TASK>
<USER_TASK:>
Description:
def show(self, dialog):
"""Generic method to show a non-modal dialog and keep reference
to the Qt C++ object"""
|
for dlg in list(self.dialogs.values()):
if to_text_string(dlg.windowTitle()) \
== to_text_string(dialog.windowTitle()):
dlg.show()
dlg.raise_()
break
else:
dialog.show()
self.dialogs[id(dialog)] = dialog
dialog.accepted.connect(
lambda eid=id(dialog): self.dialog_finished(eid))
dialog.rejected.connect(
lambda eid=id(dialog): self.dialog_finished(eid))
|
<SYSTEM_TASK:>
Add Spyder dependency
<END_TASK>
<USER_TASK:>
Description:
def add(modname, features, required_version, installed_version=None,
optional=False):
"""Add Spyder dependency"""
|
global DEPENDENCIES
for dependency in DEPENDENCIES:
if dependency.modname == modname:
raise ValueError("Dependency has already been registered: %s"\
% modname)
DEPENDENCIES += [Dependency(modname, features, required_version,
installed_version, optional)]
|
<SYSTEM_TASK:>
Check if required dependency is installed
<END_TASK>
<USER_TASK:>
Description:
def check(modname):
"""Check if required dependency is installed"""
|
for dependency in DEPENDENCIES:
if dependency.modname == modname:
return dependency.check()
else:
raise RuntimeError("Unkwown dependency %s" % modname)
|
<SYSTEM_TASK:>
Check if dependency is installed
<END_TASK>
<USER_TASK:>
Description:
def check(self):
"""Check if dependency is installed"""
|
return programs.is_module_installed(self.modname,
self.required_version,
self.installed_version)
|
<SYSTEM_TASK:>
Scan the directory `plugin_path` for plugin packages and loads them.
<END_TASK>
<USER_TASK:>
Description:
def _get_spyderplugins(plugin_path, is_io, modnames, modlist):
"""Scan the directory `plugin_path` for plugin packages and loads them."""
|
if not osp.isdir(plugin_path):
return
for name in os.listdir(plugin_path):
# This is needed in order to register the spyder_io_hdf5 plugin.
# See issue 4487
# Is this a Spyder plugin?
if not name.startswith(PLUGIN_PREFIX):
continue
# Ensure right type of plugin
if is_io != name.startswith(IO_PREFIX):
continue
# Skip names that end in certain suffixes
forbidden_suffixes = ['dist-info', 'egg.info', 'egg-info', 'egg-link',
'kernels']
if any([name.endswith(s) for s in forbidden_suffixes]):
continue
# Import the plugin
_import_plugin(name, plugin_path, modnames, modlist)
|
<SYSTEM_TASK:>
Import the plugin `module_name` from `plugin_path`, add it to `modlist`
<END_TASK>
<USER_TASK:>
Description:
def _import_plugin(module_name, plugin_path, modnames, modlist):
"""Import the plugin `module_name` from `plugin_path`, add it to `modlist`
and adds its name to `modnames`.
"""
|
if module_name in modnames:
return
try:
# First add a mock module with the LOCALEPATH attribute so that the
# helper method can find the locale on import
mock = _ModuleMock()
mock.LOCALEPATH = osp.join(plugin_path, module_name, 'locale')
sys.modules[module_name] = mock
if osp.isdir(osp.join(plugin_path, module_name)):
module = _import_module_from_path(module_name, plugin_path)
else:
module = None
# Then restore the actual loaded module instead of the mock
if module and getattr(module, 'PLUGIN_CLASS', False):
sys.modules[module_name] = module
modlist.append(module)
modnames.append(module_name)
except Exception:
sys.stderr.write("ERROR: 3rd party plugin import failed for "
"`{0}`\n".format(module_name))
traceback.print_exc(file=sys.stderr)
|
<SYSTEM_TASK:>
Return image inside a QIcon object.
<END_TASK>
<USER_TASK:>
Description:
def get_icon(name, default=None, resample=False):
"""Return image inside a QIcon object.
default: default image name or icon
resample: if True, manually resample icon pixmaps for usual sizes
(16, 24, 32, 48, 96, 128, 256). This is recommended for QMainWindow icons
created from SVG images on non-Windows platforms due to a Qt bug (see
Issue 1314).
"""
|
icon_path = get_image_path(name, default=None)
if icon_path is not None:
icon = QIcon(icon_path)
elif isinstance(default, QIcon):
icon = default
elif default is None:
try:
icon = get_std_icon(name[:-4])
except AttributeError:
icon = QIcon(get_image_path(name, default))
else:
icon = QIcon(get_image_path(name, default))
if resample:
icon0 = QIcon()
for size in (16, 24, 32, 48, 96, 128, 256, 512):
icon0.addPixmap(icon.pixmap(size, size))
return icon0
else:
return icon
|
<SYSTEM_TASK:>
Item selection has changed
<END_TASK>
<USER_TASK:>
Description:
def item_selection_changed(self):
"""Item selection has changed"""
|
is_selection = len(self.selectedItems()) > 0
self.expand_selection_action.setEnabled(is_selection)
self.collapse_selection_action.setEnabled(is_selection)
|
<SYSTEM_TASK:>
Sorting tree wrt top level items
<END_TASK>
<USER_TASK:>
Description:
def sort_top_level_items(self, key):
"""Sorting tree wrt top level items"""
|
self.save_expanded_state()
items = sorted([self.takeTopLevelItem(0)
for index in range(self.topLevelItemCount())], key=key)
for index, item in enumerate(items):
self.insertTopLevelItem(index, item)
self.restore_expanded_state()
|
<SYSTEM_TASK:>
Prints the editor fold tree to stdout, for debugging purpose.
<END_TASK>
<USER_TASK:>
Description:
def print_tree(editor, file=sys.stdout, print_blocks=False, return_list=False):
"""
Prints the editor fold tree to stdout, for debugging purpose.
:param editor: CodeEditor instance.
:param file: file handle where the tree will be printed. Default is stdout.
:param print_blocks: True to print all blocks, False to only print blocks
that are fold triggers
"""
|
output_list = []
block = editor.document().firstBlock()
while block.isValid():
trigger = TextBlockHelper().is_fold_trigger(block)
trigger_state = TextBlockHelper().is_collapsed(block)
lvl = TextBlockHelper().get_fold_lvl(block)
visible = 'V' if block.isVisible() else 'I'
if trigger:
trigger = '+' if trigger_state else '-'
if return_list:
output_list.append([block.blockNumber() + 1, lvl, visible])
else:
print('l%d:%s%s%s' %
(block.blockNumber() + 1, lvl, trigger, visible),
file=file)
elif print_blocks:
if return_list:
output_list.append([block.blockNumber() + 1, lvl, visible])
else:
print('l%d:%s%s' %
(block.blockNumber() + 1, lvl, visible), file=file)
block = block.next()
if return_list:
return output_list
|
<SYSTEM_TASK:>
Qt override.
<END_TASK>
<USER_TASK:>
Description:
def event(self, event):
"""
Qt override.
This is needed to be able to intercept the Tab key press event.
"""
|
if event.type() == QEvent.KeyPress:
if (event.key() == Qt.Key_Tab or event.key() == Qt.Key_Space):
text = self.text()
cursor = self.cursorPosition()
# fix to include in "undo/redo" history
if cursor != 0 and text[cursor-1] == ' ':
text = text[:cursor-1] + ROW_SEPARATOR + ' ' +\
text[cursor:]
else:
text = text[:cursor] + ' ' + text[cursor:]
self.setCursorPosition(cursor)
self.setText(text)
self.setCursorPosition(cursor + 1)
return False
return QWidget.event(self, event)
|
<SYSTEM_TASK:>
Update the column and row numbering in the headers.
<END_TASK>
<USER_TASK:>
Description:
def reset_headers(self):
"""
Update the column and row numbering in the headers.
"""
|
rows = self.rowCount()
cols = self.columnCount()
for r in range(rows):
self.setVerticalHeaderItem(r, QTableWidgetItem(str(r)))
for c in range(cols):
self.setHorizontalHeaderItem(c, QTableWidgetItem(str(c)))
self.setColumnWidth(c, 40)
|
<SYSTEM_TASK:>
Return the entered array in a parseable form.
<END_TASK>
<USER_TASK:>
Description:
def text(self):
"""
Return the entered array in a parseable form.
"""
|
text = []
rows = self.rowCount()
cols = self.columnCount()
# handle empty table case
if rows == 2 and cols == 2:
item = self.item(0, 0)
if item is None:
return ''
for r in range(rows - 1):
for c in range(cols - 1):
item = self.item(r, c)
if item is not None:
value = item.text()
else:
value = '0'
if not value.strip():
value = '0'
text.append(' ')
text.append(value)
text.append(ROW_SEPARATOR)
return ''.join(text[:-1])
|
<SYSTEM_TASK:>
Qt Override.
<END_TASK>
<USER_TASK:>
Description:
def event(self, event):
"""
Qt Override.
Usefull when in line edit mode.
"""
|
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
return False
return QWidget.event(self, event)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.