text stringlengths 81 112k |
|---|
Return dirname associated with *index*
def get_dirname(self, index):
"""Return dirname associated with *index*"""
fname = self.get_filename(index)
if fname:
if osp.isdir(fname):
return fname
else:
return osp.dirname(fname) |
Setup tree widget
def setup(self, name_filters=['*.py', '*.pyw'], show_all=False,
single_click_to_open=False):
"""Setup tree widget"""
self.setup_view()
self.set_name_filters(name_filters)
self.show_all = show_all
self.single_click_to_open = single_click_to... |
Setup context menu common actions
def setup_common_actions(self):
"""Setup context menu common actions"""
# Filters
filters_action = create_action(self, _("Edit filename filters..."),
None, ima.icon('filter'),
tr... |
Edit name filters
def edit_filter(self):
"""Edit name filters"""
filters, valid = QInputDialog.getText(self, _('Edit filename filters'),
_('Name filters:'),
QLineEdit.Normal,
... |
Toggle all files mode
def toggle_all(self, checked):
"""Toggle all files mode"""
self.parent_widget.sig_option_changed.emit('show_all', checked)
self.show_all = checked
self.set_show_all(checked) |
Return actions for submenu 'New...
def create_file_new_actions(self, fnames):
"""Return actions for submenu 'New...'"""
if not fnames:
return []
new_file_act = create_action(self, _("File..."),
icon=ima.icon('filenew'),
... |
Return file management actions
def create_file_manage_actions(self, fnames):
"""Return file management actions"""
only_files = all([osp.isfile(_fn) for _fn in fnames])
only_modules = all([osp.splitext(_fn)[1] in ('.py', '.pyw', '.ipy')
for _fn in fnames])
... |
Return folder management actions
def create_folder_manage_actions(self, fnames):
"""Return folder management actions"""
actions = []
if os.name == 'nt':
_title = _("Open command prompt here")
else:
_title = _("Open terminal here")
_title = _("Open ... |
Create context menu actions
def create_context_menu_actions(self):
"""Create context menu actions"""
actions = []
fnames = self.get_selected_filenames()
new_actions = self.create_file_new_actions(fnames)
if len(new_actions) > 1:
# Creating a submenu only if the... |
Update context menu
def update_menu(self):
"""Update context menu"""
self.menu.clear()
add_actions(self.menu, self.create_context_menu_actions()) |
Reimplement Qt method
def keyPressEvent(self, event):
"""Reimplement Qt method"""
if event.key() in (Qt.Key_Enter, Qt.Key_Return):
self.clicked()
elif event.key() == Qt.Key_F2:
self.rename()
elif event.key() == Qt.Key_Delete:
self.delete()
... |
Reimplement Qt method.
def mouseReleaseEvent(self, event):
"""Reimplement Qt method."""
QTreeView.mouseReleaseEvent(self, event)
if self.single_click_to_open:
self.clicked() |
Selected item was double-clicked or enter/return was pressed
def clicked(self):
"""Selected item was double-clicked or enter/return was pressed"""
fnames = self.get_selected_filenames()
for fname in fnames:
if osp.isdir(fname):
self.directory_clicked(fname)
... |
Drag and Drop - Move event
def dragMoveEvent(self, event):
"""Drag and Drop - Move event"""
if (event.mimeData().hasFormat("text/plain")):
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.ignore() |
Reimplement Qt Method - handle drag event
def startDrag(self, dropActions):
"""Reimplement Qt Method - handle drag event"""
data = QMimeData()
data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
drag = QDrag(self)
drag.setMimeData(data)
drag.exec... |
Open files with the appropriate application
def open(self, fnames=None):
"""Open files with the appropriate application"""
if fnames is None:
fnames = self.get_selected_filenames()
for fname in fnames:
if osp.isfile(fname) and encoding.is_text_file(fname):
... |
Open files with default application
def open_external(self, fnames=None):
"""Open files with default application"""
if fnames is None:
fnames = self.get_selected_filenames()
for fname in fnames:
self.open_outside_spyder([fname]) |
Open file outside Spyder with the appropriate application
If this does not work, opening unknown file in Spyder, as text file
def open_outside_spyder(self, fnames):
"""Open file outside Spyder with the appropriate application
If this does not work, opening unknown file in Spyder, as text fil... |
Open interpreter
def open_interpreter(self, fnames):
"""Open interpreter"""
for path in sorted(fnames):
self.sig_open_interpreter.emit(path) |
Run Python scripts
def run(self, fnames=None):
"""Run Python scripts"""
if fnames is None:
fnames = self.get_selected_filenames()
for fname in fnames:
self.sig_run.emit(fname) |
Remove whole directory tree
Reimplemented in project explorer widget
def remove_tree(self, dirname):
"""Remove whole directory tree
Reimplemented in project explorer widget"""
while osp.exists(dirname):
try:
shutil.rmtree(dirname, onerror=misc.onerror)
... |
Delete file
def delete_file(self, fname, multiple, yes_to_all):
"""Delete file"""
if multiple:
buttons = QMessageBox.Yes|QMessageBox.YesToAll| \
QMessageBox.No|QMessageBox.Cancel
else:
buttons = QMessageBox.Yes|QMessageBox.No
if yes_t... |
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:
spyproject_path = osp.join(fname,'.spyproject')
... |
Convert an IPython notebook to a Python script in editor
def convert_notebook(self, fname):
"""Convert an IPython notebook to a Python script in editor"""
try:
script = nbexporter().from_filename(fname)[0]
except Exception as e:
QMessageBox.critical(self, _('Conver... |
Convert IPython notebooks to Python scripts in editor
def convert_notebooks(self):
"""Convert IPython notebooks to Python scripts in editor"""
fnames = self.get_selected_filenames()
if not isinstance(fnames, (tuple, list)):
fnames = [fnames]
for fname in fnames:
... |
Rename file
def rename_file(self, fname):
"""Rename file"""
path, valid = QInputDialog.getText(self, _('Rename'),
_('New name:'), QLineEdit.Normal,
osp.basename(fname))
if valid:
path = osp.join(osp.dirname(fname), to... |
Rename files
def rename(self, fnames=None):
"""Rename files"""
if fnames is None:
fnames = self.get_selected_filenames()
if not isinstance(fnames, (tuple, list)):
fnames = [fnames]
for fname in fnames:
self.rename_file(fname) |
Move files/directories
def move(self, fnames=None, directory=None):
"""Move files/directories"""
if fnames is None:
fnames = self.get_selected_filenames()
orig = fixpath(osp.dirname(fnames[0]))
while True:
self.redirect_stdio.emit(False)
if dir... |
Create new folder
def create_new_folder(self, current_path, title, subtitle, is_package):
"""Create new folder"""
if current_path is None:
current_path = ''
if osp.isfile(current_path):
current_path = osp.dirname(current_path)
name, valid = QInputDialog.get... |
New folder
def new_folder(self, basedir):
"""New folder"""
title = _('New folder')
subtitle = _('Folder name:')
self.create_new_folder(basedir, title, subtitle, is_package=False) |
New package
def new_package(self, basedir):
"""New package"""
title = _('New package')
subtitle = _('Package name:')
self.create_new_folder(basedir, title, subtitle, is_package=True) |
Create new file
Returns True if successful
def create_new_file(self, current_path, title, filters, create_func):
"""Create new file
Returns True if successful"""
if current_path is None:
current_path = ''
if osp.isfile(current_path):
current_path =... |
New file
def new_file(self, basedir):
"""New file"""
title = _("New file")
filters = _("All files")+" (*)"
def create_func(fname):
"""File creation callback"""
if osp.splitext(fname)[1] in ('.py', '.pyw', '.ipy'):
create_script(fname)
... |
New module
def new_module(self, basedir):
"""New module"""
title = _("New module")
filters = _("Python scripts")+" (*.py *.pyw *.ipy)"
def create_func(fname):
self.sig_create_module.emit(fname)
self.create_new_file(basedir, title, filters, create_func) |
Copy absolute or relative path to given file(s)/folders(s).
def copy_path(self, fnames=None, method="absolute"):
"""Copy absolute or relative path to given file(s)/folders(s)."""
cb = QApplication.clipboard()
explorer_dir = self.fsmodel.rootPath()
if fnames is None:
fna... |
Copy file(s)/folders(s) to clipboard.
def copy_file_clipboard(self, fnames=None):
"""Copy file(s)/folders(s) to clipboard."""
if fnames is None:
fnames = self.get_selected_filenames()
if not isinstance(fnames, (tuple, list)):
fnames = [fnames]
try:
... |
Paste file from clipboard into file/project explorer directory.
def save_file_clipboard(self, fnames=None):
"""Paste file from clipboard into file/project explorer directory."""
if fnames is None:
fnames = self.get_selected_filenames()
if not isinstance(fnames, (tuple, list)):
... |
Create shortcuts for this file explorer.
def create_shortcuts(self):
"""Create shortcuts for this file explorer."""
# Configurable
copy_clipboard_file = config_shortcut(self.copy_file_clipboard,
context='explorer',
... |
VCS action (commit, browse)
def vcs_command(self, fnames, action):
"""VCS action (commit, browse)"""
try:
for path in sorted(fnames):
vcs.run_vcs_tool(path, action)
except vcs.ActionToolNotFound as error:
msg = _("For %s support, please install one ... |
Set scrollbar positions
def set_scrollbar_position(self, position):
"""Set scrollbar positions"""
# Scrollbars will be restored after the expanded state
self._scrollbar_positions = position
if self._to_be_loaded is not None and len(self._to_be_loaded) == 0:
self.restore... |
Restore scrollbar positions once tree is loaded
def restore_scrollbar_positions(self):
"""Restore scrollbar positions once tree is loaded"""
hor, ver = self._scrollbar_positions
self.horizontalScrollBar().setValue(hor)
self.verticalScrollBar().setValue(ver) |
Save all items expanded state
def save_expanded_state(self):
"""Save all items expanded state"""
model = self.model()
# If model is not installed, 'model' will be None: this happens when
# using the Project Explorer without having selected a workspace yet
if model is not No... |
Restore directory expanded state
def restore_directory_state(self, fname):
"""Restore directory expanded state"""
root = osp.normpath(to_text_string(fname))
if not osp.exists(root):
# Directory has been (re)moved outside Spyder
return
for basename in os.lis... |
Follow directories loaded during startup
def follow_directories_loaded(self, fname):
"""Follow directories loaded during startup"""
if self._to_be_loaded is None:
return
path = osp.normpath(to_text_string(fname))
if path in self._to_be_loaded:
self._to_be_l... |
Restore all items expanded state
def restore_expanded_state(self):
"""Restore all items expanded state"""
if self.__expanded_state is not None:
# In the old project explorer, the expanded state was a dictionnary:
if isinstance(self.__expanded_state, list):
s... |
Filter the directories to show
def filter_directories(self):
"""Filter the directories to show"""
index = self.get_index('.spyproject')
if index is not None:
self.setRowHidden(index.row(), index.parent(), True) |
Setup proxy model filter parameters
def setup_filter(self, root_path, path_list):
"""Setup proxy model filter parameters"""
self.root_path = osp.normpath(to_text_string(root_path))
self.path_list = [osp.normpath(to_text_string(p)) for p in path_list]
self.invalidateFilter() |
Reimplement Qt method
def sort(self, column, order=Qt.AscendingOrder):
"""Reimplement Qt method"""
self.sourceModel().sort(column, order) |
Reimplement Qt method
def filterAcceptsRow(self, row, parent_index):
"""Reimplement Qt method"""
if self.root_path is None:
return True
index = self.sourceModel().index(row, 0, parent_index)
path = osp.normcase(osp.normpath(
to_text_string(self.sourceModel(... |
Show tooltip with full path only for the root directory
def data(self, index, role):
"""Show tooltip with full path only for the root directory"""
if role == Qt.ToolTipRole:
root_dir = self.path_list[0].split(osp.sep)[-1]
if index.data() == root_dir:
return ... |
Setup proxy model
def setup_proxy_model(self):
"""Setup proxy model"""
self.proxymodel = ProxyModel(self)
self.proxymodel.setSourceModel(self.fsmodel) |
Set root path
def set_root_path(self, root_path):
"""Set root path"""
self.root_path = root_path
self.install_model()
index = self.fsmodel.setRootPath(root_path)
self.proxymodel.setup_filter(self.root_path, [])
self.setRootIndex(self.proxymodel.mapFromSource(index)... |
Return index associated with filename
def get_index(self, filename):
"""Return index associated with filename"""
index = self.fsmodel.index(filename)
if index.isValid() and index.model() is self.fsmodel:
return self.proxymodel.mapFromSource(index) |
Set folder names
def set_folder_names(self, folder_names):
"""Set folder names"""
assert self.root_path is not None
path_list = [osp.join(self.root_path, dirname)
for dirname in folder_names]
self.proxymodel.setup_filter(self.root_path, path_list) |
Return filename from index
def get_filename(self, index):
"""Return filename from index"""
if index:
path = self.fsmodel.filePath(self.proxymodel.mapToSource(index))
return osp.normpath(to_text_string(path)) |
Setup view for projects
def setup_project_view(self):
"""Setup view for projects"""
for i in [1, 2, 3]:
self.hideColumn(i)
self.setHeaderHidden(True)
# Disable the view of .spyproject.
self.filter_directories() |
Setup context menu common actions
def setup_common_actions(self):
"""Setup context menu common actions"""
actions = super(ExplorerTreeWidget, self).setup_common_actions()
if self.show_cd_only is None:
# Enabling the 'show current directory only' option but do not
# ... |
Toggle show current directory only mode
def toggle_show_cd_only(self, checked):
"""Toggle show current directory only mode"""
self.parent_widget.sig_option_changed.emit('show_cd_only', checked)
self.show_cd_only = checked
if checked:
if self.__last_folder is not None:
... |
Set current folder and return associated model index
def set_current_folder(self, folder):
"""Set current folder and return associated model index"""
index = self.fsmodel.setRootPath(folder)
self.__last_folder = folder
if self.show_cd_only:
if self.__original_root_index... |
Refresh widget
force=False: won't refresh widget if path has not changed
def refresh(self, new_path=None, force_current=False):
"""Refresh widget
force=False: won't refresh widget if path has not changed"""
if new_path is None:
new_path = getcwd_or_home()
if fo... |
Go to parent directory
def go_to_parent_directory(self):
"""Go to parent directory"""
self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir))) |
Update browse history
def update_history(self, directory):
"""Update browse history"""
try:
directory = osp.abspath(to_text_string(directory))
if directory in self.history:
self.histindex = self.history.index(directory)
except Exception:
... |
Set directory as working directory
def chdir(self, directory=None, browsing_history=False):
"""Set directory as working directory"""
if directory is not None:
directory = osp.abspath(to_text_string(directory))
if browsing_history:
directory = self.history[self.histi... |
Toggle icon text
def toggle_icontext(self, state):
"""Toggle icon text"""
self.sig_option_changed.emit('show_icontext', state)
for widget in self.action_widgets:
if widget is not self.button_menu:
if state:
widget.setToolButtonStyle(Qt.ToolB... |
Set model data
def set_data(self, data):
"""Set model data"""
self._data = data
keys = list(data.keys())
self.breakpoints = []
for key in keys:
bp_list = data[key]
if bp_list:
for item in data[key]:
self.breakp... |
Overriding sort method
def sort(self, column, order=Qt.DescendingOrder):
"""Overriding sort method"""
if column == 0:
self.breakpoints.sort(
key=lambda breakpoint: breakpoint[1])
self.breakpoints.sort(
key=lambda breakpoint: osp.basename(bre... |
Return data at table index
def data(self, index, role=Qt.DisplayRole):
"""Return data at table index"""
if not index.isValid():
return to_qvariant()
if role == Qt.DisplayRole:
if index.column() == 0:
value = osp.basename(self.get_value(index))
... |
Setup table
def setup_table(self):
"""Setup table"""
self.horizontalHeader().setStretchLastSection(True)
self.adjust_columns()
self.columnAt(0)
# Sorting columns
self.setSortingEnabled(False)
self.sortByColumn(0, Qt.DescendingOrder) |
Reimplement Qt method
def mouseDoubleClickEvent(self, event):
"""Reimplement Qt method"""
index_clicked = self.indexAt(event.pos())
if self.model.breakpoints:
filename = self.model.breakpoints[index_clicked.row()][0]
line_number_str = self.model.breakpoints[index_cl... |
Get the list of languages we need to start servers and create
clients for.
def get_languages(self):
"""
Get the list of languages we need to start servers and create
clients for.
"""
languages = ['python']
all_options = CONF.options(self.CONF_SECTION)
for... |
Get root path to pass to the LSP servers.
This can be the current project path or the output of
getcwd_or_home (except for Python, see below).
def get_root_path(self, language):
"""
Get root path to pass to the LSP servers.
This can be the current project path or the output of... |
Send a new initialize message to each LSP server when the project
path has changed so they can update the respective server root paths.
def reinitialize_all_clients(self):
"""
Send a new initialize message to each LSP server when the project
path has changed so they can update the respe... |
Start an LSP client for a given language.
def start_client(self, language):
"""Start an LSP client for a given language."""
started = False
if language in self.clients:
language_client = self.clients[language]
queue = self.register_queue[language]
# Don't st... |
Update Python server configuration with the options saved in our
config system.
def generate_python_config(self):
"""
Update Python server configuration with the options saved in our
config system.
"""
python_config = PYTHON_CONFIG.copy()
# Server options
... |
Setup config page widgets and options.
def setup_page(self):
"""Setup config page widgets and options."""
settings_group = QGroupBox(_("Settings"))
hist_spin = self.create_spinbox(
_("History depth: "), _(" entries"),
'max_entries', min_=1... |
Transcode a text string
def transcode(text, input=PREFERRED_ENCODING, output=PREFERRED_ENCODING):
"""Transcode a text string"""
try:
return text.decode("cp437").encode("cp1252")
except UnicodeError:
try:
return text.decode("cp437").encode(output)
except UnicodeErr... |
Return a unicode version of string decoded using the file system encoding.
def to_unicode_from_fs(string):
"""
Return a unicode version of string decoded using the file system encoding.
"""
if not is_string(string): # string is a QString
string = to_text_string(string.toUtf8(), 'utf-8')
... |
Return a byte string version of unic encoded using the file
system encoding.
def to_fs_from_unicode(unic):
"""
Return a byte string version of unic encoded using the file
system encoding.
"""
if is_unicode(unic):
try:
string = unic.encode(FS_ENCODING)
exce... |
Function to get the coding of a text.
@param text text to inspect (string)
@return coding string
def get_coding(text, force_chardet=False):
"""
Function to get the coding of a text.
@param text text to inspect (string)
@return coding string
"""
if not force_chardet:
for... |
Function to decode a text.
@param text text to decode (string)
@return decoded text and encoding
def decode(text):
"""
Function to decode a text.
@param text text to decode (string)
@return decoded text and encoding
"""
try:
if text.startswith(BOM_UTF8):
# ... |
Convert a string to unicode
def to_unicode(string):
"""Convert a string to unicode"""
if not is_unicode(string):
for codec in CODECS:
try:
unic = to_text_string(string, codec)
except UnicodeError:
pass
except TypeError:
... |
Write 'text' to file ('filename') assuming 'encoding' in an atomic way
Return (eventually new) encoding
def write(text, filename, encoding='utf-8', mode='wb'):
"""
Write 'text' to file ('filename') assuming 'encoding' in an atomic way
Return (eventually new) encoding
"""
text, encoding = ... |
Write 'lines' to file ('filename') assuming 'encoding'
Return (eventually new) encoding
def writelines(lines, filename, encoding='utf-8', mode='wb'):
"""
Write 'lines' to file ('filename') assuming 'encoding'
Return (eventually new) encoding
"""
return write(os.linesep.join(lines), filena... |
Read text from file ('filename')
Return text and encoding
def read(filename, encoding='utf-8'):
"""
Read text from file ('filename')
Return text and encoding
"""
text, encoding = decode( open(filename, 'rb').read() )
return text, encoding |
Read lines from file ('filename')
Return lines and encoding
def readlines(filename, encoding='utf-8'):
"""
Read lines from file ('filename')
Return lines and encoding
"""
text, encoding = read(filename, encoding)
return text.split(os.linesep), encoding |
Return all file type extensions supported by Pygments
def _get_pygments_extensions():
"""Return all file type extensions supported by Pygments"""
# NOTE: Leave this import here to keep startup process fast!
import pygments.lexers as lexers
extensions = []
for lx in lexers.get_all_lexers():
... |
Return filter associated to file extension
def get_filter(filetypes, ext):
"""Return filter associated to file extension"""
if not ext:
return ALL_FILTER
for title, ftypes in filetypes:
if ext in ftypes:
return _create_filter(title, ftypes)
else:
return '' |
Get all file types supported by the Editor
def get_edit_filetypes():
"""Get all file types supported by the Editor"""
# The filter details are not hidden on Windows, so we can't use
# all Pygments extensions on that platform
if os.name == 'nt':
supported_exts = []
else:
try:
... |
Detect if we are running in an Ubuntu-based distribution
def is_ubuntu():
"""Detect if we are running in an Ubuntu-based distribution"""
if sys.platform.startswith('linux') and osp.isfile('/etc/lsb-release'):
release_info = open('/etc/lsb-release').read()
if 'Ubuntu' in release_info:
... |
Detect if we are running in a Gtk-based desktop
def is_gtk_desktop():
"""Detect if we are running in a Gtk-based desktop"""
if sys.platform.startswith('linux'):
xdg_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '')
if xdg_desktop:
gtk_desktops = ['Unity', 'GNOME', 'XFCE']
... |
Detect if we are running in a KDE desktop
def is_kde_desktop():
"""Detect if we are running in a KDE desktop"""
if sys.platform.startswith('linux'):
xdg_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '')
if xdg_desktop:
if 'KDE' in xdg_desktop:
return True
... |
Return PYTHONPATH list as relative paths
def _get_relative_pythonpath(self):
"""Return PYTHONPATH list as relative paths"""
# Workaround to replace os.path.relpath (new in Python v2.6):
offset = len(self.root_path)+len(os.pathsep)
return [path[offset:] for path in self.pythonpath] |
Set PYTHONPATH list relative paths
def _set_relative_pythonpath(self, value):
"""Set PYTHONPATH list relative paths"""
self.pythonpath = [osp.abspath(osp.join(self.root_path, path))
for path in value] |
Return True if dirname is in project's PYTHONPATH
def is_in_pythonpath(self, dirname):
"""Return True if dirname is in project's PYTHONPATH"""
return fixpath(dirname) in [fixpath(_p) for _p in self.pythonpath] |
Remove path from project's PYTHONPATH
Return True if path was removed, False if it was not found
def remove_from_pythonpath(self, path):
"""Remove path from project's PYTHONPATH
Return True if path was removed, False if it was not found"""
pathlist = self.get_pythonpath()
i... |
Add path to project's PYTHONPATH
Return True if path was added, False if it was already there
def add_to_pythonpath(self, path):
"""Add path to project's PYTHONPATH
Return True if path was added, False if it was already there"""
pathlist = self.get_pythonpath()
if path in p... |
Return data files for package *name* with extensions in *extlist*
def get_package_data(name, extlist):
"""Return data files for package *name* with extensions in *extlist*"""
flist = []
# Workaround to replace os.path.relpath (not available until Python 2.6):
offset = len(name)+len(os.pathsep)
for ... |
Return subpackages of package *name*
def get_subpackages(name):
"""Return subpackages of package *name*"""
splist = []
for dirpath, _dirnames, _filenames in os.walk(name):
if osp.isfile(osp.join(dirpath, '__init__.py')):
splist.append(".".join(dirpath.split(os.sep)))
return splist |
Return Python documentation path
(Windows: return the PythonXX.chm path if available)
def get_python_doc_path():
"""
Return Python documentation path
(Windows: return the PythonXX.chm path if available)
"""
if os.name == 'nt':
doc_path = osp.join(sys.prefix, "Doc")
if no... |
Set the OpenGL implementation used by Spyder.
See issue 7447 for the details.
def set_opengl_implementation(option):
"""
Set the OpenGL implementation used by Spyder.
See issue 7447 for the details.
"""
if option == 'software':
QCoreApplication.setAttribute(Qt.AA_UseSoftwareO... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.