def is_scratch(self, view):
"""
Return whether a view is effectively scratch.
There is a bug (or feature) in the current ST3 where the Find panel
is not marked scratch but has no window.
There is also a bug where settings files opened from within .sublime-package
files are not marked scratch during the initial on_modified event, so we have
to check that a view with a filename actually exists on disk if the file
being opened is in the Sublime Text packages directory.
"""
if view.is_scratch() or view.is_read_only() or view.window() is None or view.settings().get("repl") is not None:
return True
elif (
view.file_name() and
view.file_name().startswith(sublime.packages_path() + os.path.sep) and
not os.path.exists(view.file_name())
):
return True
else:
return False
python类packages_path()的实例源码
def change_mark_colors(error_color, warning_color):
"""Change SublimeLinter error/warning colors in user color schemes."""
error_color = error_color.lstrip('#')
warning_color = warning_color.lstrip('#')
base_path = os.path.join(sublime.packages_path(), 'User', '*.tmTheme')
sublime_path = os.path.join(sublime.packages_path(), 'User', 'SublimeLinter', '*.tmTheme')
themes = glob(sublime_path) + glob(base_path)
for theme in themes:
with open(theme, encoding='utf8') as f:
text = f.read()
if re.search(MARK_COLOR_RE.format(r'mark\.error'), text):
text = re.sub(MARK_COLOR_RE.format(r'mark\.error'), r'\1#{}\2'.format(error_color), text)
text = re.sub(MARK_COLOR_RE.format(r'mark\.warning'), r'\1#{}\2'.format(warning_color), text)
with open(theme, encoding='utf8', mode='w') as f:
f.write(text)
def generate_menu(name, menu_text):
"""Generate and return a sublime-menu from a template."""
from . import persist
plugin_dir = os.path.join(sublime.packages_path(), persist.PLUGIN_DIRECTORY)
path = os.path.join(plugin_dir, '{}.sublime-menu.template'.format(name))
with open(path, encoding='utf8') as f:
template = f.read()
# Get the indent for the menus within the template,
# indent the chooser menus except for the first line.
indent = MENU_INDENT_RE.search(template).group(1)
menu_text = indent_lines(menu_text, indent)
text = Template(template).safe_substitute({'menus': menu_text})
path = os.path.join(plugin_dir, '{}.sublime-menu'.format(name))
with open(path, mode='w', encoding='utf8') as f:
f.write(text)
return text
def fix_scheme_in_settings(settings_file,current_scheme, new_scheme, regenerate=False):
"""Change the color scheme in the given Settings to a background-corrected one"""
from os.path import join, normpath, isfile
settings = load_settings(settings_file)
settings_scheme = settings.get("color_scheme")
if current_scheme == settings_scheme:
new_scheme_path = join(packages_path(), normpath(new_scheme[len("Packages/"):]))
if isfile(new_scheme_path) and not regenerate:
settings.set("color_scheme", new_scheme)
else:
generate_scheme_fix(current_scheme, new_scheme_path)
settings.set("color_scheme", new_scheme)
save_settings(settings_file)
return True
return False
def generate_scheme_fix(old_scheme, new_scheme_path):
"""Appends background-correction XML to a color scheme file"""
from os.path import join
from re import sub
UUID_REGEX = '[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}'
with open(join(packages_path(),current_directory(),'background_fix.xml')) as f:
xml = f.read()
scheme_data = load_resource(old_scheme) # only valid for ST3 API!
insertion_point = scheme_data.rfind("</array>")
new_scheme_data = scheme_data[:insertion_point] + xml + scheme_data[insertion_point:]
def uuid_gen(args):
from uuid import uuid4
return str(uuid4())
new_scheme_data = sub(UUID_REGEX, uuid_gen, new_scheme_data)
with open(new_scheme_path, "wb") as f:
f.write(new_scheme_data.encode("utf-8"))
def on_post_save(self, view):
file_name = view.file_name()
if not ReloadPlugin.PACKAGE_NAME in file_name: return
if ReloadPlugin.PLUGIN_PYTHON_FILE in file_name: return
original_file_name = view.file_name()
plugin_python_file = os.path.join(sublime.packages_path(), ReloadPlugin.PLUGIN_PYTHON_FILE)
if not os.path.isfile(plugin_python_file): return
def _open_original_file():
view.window().open_file(original_file_name)
plugin_view = view.window().open_file(plugin_python_file)
print("save", plugin_view.file_name())
plugin_view.run_command("save")
sublime.set_timeout_async(_open_original_file, self.PLUGIN_RELOAD_TIME_MS)
def load_history(rev=True, as_dict=False):
"""Returns list of past requests. Raises exception if history file doesn't
exist.
"""
history_file = sublime.load_settings('Requester.sublime-settings').get('history_file', None)
if not history_file:
raise KeyError
history_path = os.path.join(sublime.packages_path(), 'User', history_file)
with open(history_path, 'r') as f:
rh = json.loads(f.read() or '{}', object_pairs_hook=OrderedDict)
if as_dict:
return rh
requests = list(rh.items())
if rev:
requests.reverse()
return requests
def is_scratch(self, view):
"""
Return whether a view is effectively scratch.
There is a bug (or feature) in the current ST3 where the Find panel
is not marked scratch but has no window.
There is also a bug where settings files opened from within .sublime-package
files are not marked scratch during the initial on_modified event, so we have
to check that a view with a filename actually exists on disk if the file
being opened is in the Sublime Text packages directory.
"""
if view.is_scratch() or view.is_read_only() or view.window() is None or view.settings().get("repl") is not None:
return True
elif (
view.file_name() and
view.file_name().startswith(sublime.packages_path() + os.path.sep) and
not os.path.exists(view.file_name())
):
return True
else:
return False
def is_settings_file(self, view, user_only=False):
"""Return True if view is a SublimeLinter settings file."""
filename = view.file_name()
if not filename:
return False
if not filename.startswith(sublime.packages_path()):
return False
dirname, filename = os.path.split(filename)
dirname = os.path.basename(dirname)
if self.LINTER_SETTINGS_RE.match(filename):
if user_only:
return dirname == 'User'
else:
return dirname in (persist.PLUGIN_DIRECTORY, 'User')
def change_mark_colors(error_color, warning_color):
"""Change SublimeLinter error/warning colors in user color schemes."""
error_color = error_color.lstrip('#')
warning_color = warning_color.lstrip('#')
base_path = os.path.join(sublime.packages_path(), 'User', '*.tmTheme')
sublime_path = os.path.join(sublime.packages_path(), 'User', 'SublimeLinter', '*.tmTheme')
themes = glob(sublime_path) + glob(base_path)
for theme in themes:
with open(theme, encoding='utf8') as f:
text = f.read()
if re.search(MARK_COLOR_RE.format(r'mark\.error'), text):
text = re.sub(MARK_COLOR_RE.format(r'mark\.error'), r'\1#{}\2'.format(error_color), text)
text = re.sub(MARK_COLOR_RE.format(r'mark\.warning'), r'\1#{}\2'.format(warning_color), text)
with open(theme, encoding='utf8', mode='w') as f:
f.write(text)
def generate_menu(name, menu_text):
"""Generate and return a sublime-menu from a template."""
from . import persist
plugin_dir = os.path.join(sublime.packages_path(), persist.PLUGIN_DIRECTORY)
path = os.path.join(plugin_dir, '{}.sublime-menu.template'.format(name))
with open(path, encoding='utf8') as f:
template = f.read()
# Get the indent for the menus within the template,
# indent the chooser menus except for the first line.
indent = MENU_INDENT_RE.search(template).group(1)
menu_text = indent_lines(menu_text, indent)
text = Template(template).safe_substitute({'menus': menu_text})
path = os.path.join(plugin_dir, '{}.sublime-menu'.format(name))
with open(path, mode='w', encoding='utf8') as f:
f.write(text)
return text
def find_resource(resource_pattern, package=None):
file_set = set()
if package == None:
for package in get_packages_list():
file_set.update(find_resource(resource_pattern, package))
ret_list = list(file_set)
else:
file_set.update(_find_directory_resource(os.path.join(sublime.packages_path(), package), resource_pattern))
if VERSION >= 3006:
zip_location = os.path.join(sublime.installed_packages_path(), package + ".sublime-package")
file_set.update(_find_zip_resource(zip_location, resource_pattern))
zip_location = os.path.join(os.path.dirname(sublime.executable_path()), "Packages", package + ".sublime-package")
file_set.update(_find_zip_resource(zip_location, resource_pattern))
ret_list = map(lambda e: package + "/" + e, file_set)
return sorted(ret_list)
def collect_package_data(self):
block = DataBlock('Package data')
_, packages, _ = next(os.walk(sublime.packages_path()))
packages = list(packages)
_, _, files = next(os.walk(sublime.installed_packages_path()))
suffix = '.sublime-package'
files = [f[:-len(suffix)] for f in files if f.endswith(suffix)]
ignored_packages = sublime.load_settings('Preferences.sublime-settings').get('ignored_packages', [])
block.items.append(DataItem('installed packages', json.dumps(files)))
block.items.append(DataItem('packages', json.dumps(packages)))
block.items.append(DataItem('ignored packages', json.dumps(ignored_packages)))
if sublime.find_resources('Package Control.sublime-settings'):
pc_packages = sublime.load_settings('Package Control.sublime-settings').get('installed_packages', [])
block.items.append(DataItem('packages managed by Package Control', json.dumps(pc_packages)))
self.elements.append(block)
def favorites_data_path(per_project):
file = None
if per_project:
project = sublime.active_window().project_file_name()
if project:
file = project + '.favorites'
else:
file = os.path.join(sublime.packages_path(), 'User', 'favorites.txt')
if file and not path.exists(file):
with open(file, "w") as f:
f.write('')
return file
# -------------------------
def get_favorite_files_data():
"""
Integration with Favorit_Files plugin
It goes only as far as reading its data file, flattening it and allowing to
open files on double-click on the item in the Favorites panel
"""
import json
file_name = os.path.join(sublime.packages_path(), 'User', 'favorite_files_list.json')
with open(file_name) as data_file:
data = json.load(data_file)
result = []
for f in data["files"]:
result.append(f)
for name in data["groups"].keys():
for f in data["groups"][name]:
result.append(f)
return result
# -------------------------
def current_package_name(self):
view = self.window.active_view()
spp = os.path.realpath(sublime.packages_path())
if view and view.file_name():
file_path = os.path.realpath(view.file_name())
if file_path.endswith(".py") and file_path.startswith(spp):
# path on Windows may not be properly cased
# https://github.com/randy3k/AutomaticPackageReloader/issues/10
file_path = casedpath(file_path)
return file_path[len(spp):].split(os.sep)[1]
folders = self.window.folders()
if folders and len(folders) > 0:
first_folder = os.path.realpath(folders[0])
if first_folder.startswith(spp):
return os.path.basename(casedpath(first_folder))
return None
def __init__(self, name_list=None):
self._list = dict()
self._disabled = 0
self._dependencies = 0
# Maps lower cased package names to listed packages on case insensitive
# systems.
self._case_list = dict() if _wrap("ABC") == _wrap("abc") else None
if name_list is not None:
if isinstance(name_list, str):
name_list = [name_list]
if _wrap("Abc") == _wrap("abc"):
name_list = [_wrap(name) for name in name_list]
self._shipped = self.__find_pkgs(PackageInfo.shipped_packages_path, name_list, shipped=True)
self._installed = self.__find_pkgs(sublime.installed_packages_path(), name_list)
self._unpacked = self.__find_pkgs(sublime.packages_path(), name_list, packed=False)
def load_session(self):
"""
Returns dict or None if no session exists
"""
local_session_path = os.path.join(os.path.dirname(sublime.packages_path()), 'Local')
local_auto_save_session_file = os.path.join(local_session_path, 'Auto Save Session.sublime_session')
local_session_file = os.path.join(local_session_path, 'Session.sublime_session')
if os.path.isfile(local_auto_save_session_file):
session_file_to_use = local_auto_save_session_file
elif os.path.isfile(local_session_file):
session_file_to_use = local_session_file
else:
return None
with open(session_file_to_use) as f:
local_session_content = f.read()
session = json.loads(local_session_content, strict=False)
return session
def file_name():
return os.path.join(sublime.packages_path(), 'User', '.vintageousrc')
def abbrevs_path():
return os.path.normpath(
os.path.join(
sublime.packages_path(),
'User/_vintageous_abbrev.sublime-completions'
)
)
def cleanup():
PACKAGES_PATH = sublime.packages_path()
DEFAULT_PATH = os.path.join(PACKAGES_PATH, "Default")
ZZZZ_LOCALE = os.path.join(PACKAGES_PATH, "ZZZZZZZZ-Localization")
import shutil
shutil.rmtree(DEFAULT_PATH)
shutil.rmtree(ZZZZ_LOCALE)
def get_dest_path():
return os.path.join(sublime.packages_path(), PKG, DIST, PATCHES)
def get_aliases_path():
return os.path.join(sublime.packages_path(), PKG, DIST, ALIASES)
def copy_linter(self, name):
"""Copy the template linter to a new linter with the given name."""
self.name = name
self.fullname = 'SublimeLinter-contrib-{}'.format(name)
self.dest = os.path.join(sublime.packages_path(), self.fullname)
if os.path.exists(self.dest):
sublime.error_message('The plugin “{}” already exists.'.format(self.fullname))
return
src = os.path.join(sublime.packages_path(), persist.PLUGIN_DIRECTORY, 'linter-plugin-template')
self.temp_dir = None
try:
self.temp_dir = tempfile.mkdtemp()
self.temp_dest = os.path.join(self.temp_dir, self.fullname)
shutil.copytree(src, self.temp_dest)
self.get_linter_language(name, self.configure_linter)
except Exception as ex:
if self.temp_dir and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
sublime.error_message('An error occurred while copying the template plugin: {}'.format(str(ex)))
def run(self):
"""Run the command."""
base_path = os.path.join(sublime.packages_path(), 'User', '*.tmTheme')
sublime_path = os.path.join(sublime.packages_path(), 'User', 'SublimeLinter', '*.tmTheme')
themes = glob(base_path) + glob(sublime_path)
prefs = sublime.load_settings('Preferences.sublime-settings')
scheme = prefs.get('color_scheme')
for theme in themes:
# Ensure it is a (SL) theme and it is not current current scheme
if re.search(r'\(SL\)', theme) and os.path.normpath(scheme) not in theme:
persist.debug('deleting {}'.format(os.path.split(theme)[1]))
os.remove(theme)
def openFeedList(self):
packagePath = sublime.packages_path()
matches = []
#self.window.open_file("/feedlist.txt")
for root, dirnames, filenames in os.walk(packagePath):
for filename in fnmatch.filter(filenames, "sublimerss.py"):
matches.append(root)
self.window.open_file(matches[0] + "/feedlist.txt")
def on_done(self, index):
"""
callback for menu items, gets called with *index of selected items
"""
if index == -1:
return None
elif index == 0:
self.window.show_input_panel("Set remote IP",
self.settings.get("remote_ip", "192.168.0.1"),
self.set_ip,
None,
None)
elif index == 1:
REMOTE.adb_reconnect_async()
self.window.run_command("remote_actions")
elif index == 2:
variables = self.window.active_view().extract_variables()
if "folder" in variables:
REMOTE.push_to_box(variables["folder"])
elif index == 3:
plugin_path = os.path.join(sublime.packages_path(), "KodiDevKit")
REMOTE.get_log(self.open_file, plugin_path)
elif index == 4:
plugin_path = os.path.join(sublime.packages_path(), "KodiDevKit")
REMOTE.get_screenshot(self.open_file, plugin_path)
elif index == 5:
REMOTE.clear_cache()
elif index == 6:
REMOTE.reboot()
def processRecentUpgrade():
if (VERSION in UPGRADE_KILL_FILES):
print("Performing kill for version %1.1f" % (VERSION))
for killed in UPGRADE_KILL_FILES[VERSION]:
killPath = os.path.join(sublime.packages_path(), "PapyrusF4", killed)
if os.path.exists(killPath):
if killed[-1] == "/":
shutil.rmtree(killPath)
else:
os.remove(killPath)
def Init():
global VERSION
try:
with open(os.path.join(sublime.packages_path(), "PapyrusF4", "VERSION"), "r") as version_file:
VERSION = float(version_file.read())
except:
pass # VERSION remains 0.0
autoUpdateCheck()
processRecentUpgrade()
def get_plugin_folder(self):
packages_path = os.path.join(sublime.packages_path(), self.plugin_name())
return packages_path