def run(self, edit): def_path = join(dirname(sublime.executable_path()), 'Packages') default = set([re.sub(r'\.sublime-package', '', p) for p in listdir(def_path)]) user = get_user_packages() - get_dependencies() pc = set([re.sub(r'\.sublime-package', '', p) for p in listdir(sublime.installed_packages_path())]) disabled = set(sublime.load_settings('Preferences.sublime-settings').get('ignored_packages', [])) ignored = set(["User", "bz2", "0_package_control_loader", ".DS_Store"]) enabled_def = default - disabled disabled_def = default - enabled_def pc_total = (pc | (user - default)) - ignored enabled_pc = pc_total - disabled disabled_pc = pc_total - enabled_pc total = (pc | user | disabled | default) - ignored enabled = total - disabled Row = namedtuple('Row', ['Type', 'Total', 'Disabled', 'Enabled']) row1 = Row("Built-in", len(default), len(disabled_def), len(enabled_def)) row2 = Row("Package Control", len(pc_total), len(disabled_pc), len(enabled_pc)) row3 = Row("Total", len(total), len(disabled), len(enabled)) results = pprinttable([row1, row2, row3]) sep_line = "\n————————————————————————————————————————————\n\t" out = self.view.window().get_output_panel("stats") self.view.window().run_command("show_panel", {"panel": "output.stats"}) out.insert(edit, out.size(), results) out.insert(edit, out.size(), "\n\nPackage Control Packages (Enabled):" + sep_line + '\n\t'.join(sorted(enabled_pc, key=lambda s: s.lower()))) out.insert(edit, out.size(), "\n\nPackage Control Packages (Disabled):" + sep_line + '\n\t'.join(sorted(disabled_pc, key=lambda s: s.lower()))) out.insert(edit, out.size(), "\n\nDefault Packages (Enabled):" + sep_line + '\n\t'.join(sorted(enabled_def, key=lambda s: s.lower()))) out.insert(edit, out.size(), "\n\nDefault Packages (Disabled):" + sep_line + '\n\t'.join(sorted(disabled_def, key=lambda s: s.lower())))
def list_package_files(package, ignore_patterns=[]): """ List files in the specified package. """ package_path = os.path.join(sublime.packages_path(), package, "") path = None file_set = set() file_list = [] if os.path.exists(package_path): for root, directories, filenames in os.walk(package_path): temp = root.replace(package_path, "") for filename in filenames: file_list.append(os.path.join(temp, filename)) file_set.update(file_list) if VERSION >= 3006: sublime_package = package + ".sublime-package" packages_path = sublime.installed_packages_path() if os.path.exists(os.path.join(packages_path, sublime_package)): file_set.update(_list_files_in_zip(packages_path, sublime_package)) packages_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages" if os.path.exists(os.path.join(packages_path, sublime_package)): file_set.update(_list_files_in_zip(packages_path, sublime_package)) file_list = [] for filename in file_set: if not _ignore_file(filename, ignore_patterns): file_list.append(_normalize_to_sublime_path(filename)) return sorted(file_list)
def subl(args=[]): # learnt from SideBarEnhancements executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" subprocess.Popen([executable_path] + args)
def open_folder(dir_path): """dir_pathにあるディレクトリをSublime Text 3で開く. 現状の実装ではsubprocess.Popenを用いて, 新しいウィンドウを起動する. (これはSideBarEnhancementsパッケージを参考にしたものである) """ subprocess.Popen([sublime.executable_path(), dir_path], cwd=dir_path)
def load_and_save_scopes(self): scopes = set() for x in os.walk(sublime.packages_path() + '/..'): for f in glob.glob(os.path.join(x[0], '*.tmLanguage')): for s in self.get_scopes_from(plistlib.readPlist(f)): scopes.add(s.strip()) for x in os.walk(os.path.dirname(sublime.executable_path())): for f in glob.glob(os.path.join(x[0], '*.sublime-package')): input_zip = ZipFile(f) for name in input_zip.namelist(): if name.endswith('.tmLanguage'): for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))): scopes.add(s.strip()) for x in os.walk(sublime.packages_path() + '/..'): for f in glob.glob(os.path.join(x[0], '*.sublime-package')): input_zip = ZipFile(f) for name in input_zip.namelist(): if name.endswith('.tmLanguage'): for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))): scopes.add(s.strip()) names = list(scopes) scopes = dict() for name in names: value = name if value.startswith('source.'): value = value[7:] elif value.startswith('text.'): value = value[5:] scopes[name] = value self.settings.set('scopes', scopes) sublime.save_settings('smart-pieces.sublime-settings')
def run(self, args = []): # 替换参数中的环境变量 env = self.window.extract_variables() args = [sublime.expand_variables(x, env) for x in args] # 获取【sublime】执行路径 executable_path = sublime.executable_path() # 获取【OSX】下的【subl】目录 if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" # 运行【subl】命令 subprocess.Popen([executable_path] + args) # 修复在【Windows】下窗口推动焦点 if sublime.platform() == "windows": def fix_focus(): window = sublime.active_window() view = window.active_view() window.run_command('focus_neighboring_group') window.focus_view(view) sublime.set_timeout(fix_focus, 300)
def get_packages_list(ignore_packages=True, ignore_patterns=[]): """ Return a list of packages. """ package_set = set() package_set.update(_get_packages_from_directory(sublime.packages_path())) if int(sublime.version()) >= 3006: package_set.update(_get_packages_from_directory(sublime.installed_packages_path(), ".sublime-package")) executable_package_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages" package_set.update(_get_packages_from_directory(executable_package_path, ".sublime-package")) if ignore_packages: ignored_list = sublime.load_settings( "Preferences.sublime-settings").get("ignored_packages", []) else: ignored_list = [] for package in package_set: for pattern in ignore_patterns: if re.match(pattern, package): ignored_list.append(package) break for ignored in ignored_list: package_set.discard(ignored) return sorted(list(package_set))
def _get_resource(package_name, resource, return_binary=False, encoding="utf-8"): packages_path = sublime.packages_path() content = None if VERSION > 3013: try: if return_binary: content = sublime.load_binary_resource("Packages/" + package_name + "/" + resource) else: content = sublime.load_resource("Packages/" + package_name + "/" + resource) except IOError: pass else: path = None if os.path.exists(os.path.join(packages_path, package_name, resource)): path = os.path.join(packages_path, package_name, resource) content = _get_directory_item_content(path, return_binary, encoding) if VERSION >= 3006: sublime_package = package_name + ".sublime-package" packages_path = sublime.installed_packages_path() if content is None: if os.path.exists(os.path.join(packages_path, sublime_package)): content = _get_zip_item_content(os.path.join(packages_path, sublime_package), resource, return_binary, encoding) packages_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages" if content is None: if os.path.exists(os.path.join(packages_path, sublime_package)): content = _get_zip_item_content(os.path.join(packages_path, sublime_package), resource, return_binary, encoding) return content.replace("\r\n", "\n").replace("\r", "\n")
def get_package_and_resource_name(path): """ This method will return the package name and resource name from a path. Arguments: path Path to parse for package and resource name. """ package = None resource = None path = _normalize_to_sublime_path(path) if os.path.isabs(path): packages_path = _normalize_to_sublime_path(sublime.packages_path()) if path.startswith(packages_path): package, resource = _search_for_package_and_resource(path, packages_path) if int(sublime.version()) >= 3006: packages_path = _normalize_to_sublime_path(sublime.installed_packages_path()) if path.startswith(packages_path): package, resource = _search_for_package_and_resource(path, packages_path) packages_path = _normalize_to_sublime_path(os.path.dirname(sublime.executable_path()) + os.sep + "Packages") if path.startswith(packages_path): package, resource = _search_for_package_and_resource(path, packages_path) else: path = re.sub(r"^Packages/", "", path) split = re.split(r"/", path, 1) package = split[0] package = package.replace(".sublime-package", "") resource = split[1] return (package, resource)
def launch_ST3(self, files): executable_path = sublime.executable_path() if OSX: app_path = executable_path[:executable_path.rfind(".app/")+5] executable_path = app_path+"Contents/SharedSupport/bin/subl" items = [executable_path, "-n"] + files subprocess.Popen(items, cwd=None if NT else self.path)
def init(): absDir = os.path.dirname(os.path.abspath(__file__)) if v == '3' and os.path.isfile(absDir): pkgDir = os.path.join(sublime.packages_path(), pName); if not os.path.isdir(pkgDir): unpackSelf(absDir, pkgDir) return locale = '' firstRun = False fFile = os.path.join(pDir, '.firstRun') if not os.path.isfile(fFile): firstRun = True backupMenu() open(fFile, 'wt').write('') locale = getSetting('locale', '') eDir = os.path.join(mDir, version, 'en'); if v == '3' and not os.path.isdir(eDir): eFile = sublime.executable_path(); dFile = os.path.join(os.path.dirname(eFile), 'Packages', 'Default.sublime-package'); unpackMenu(dFile, eDir); makeMenu(locale, firstRun) makeCommand(locale, firstRun) setLocale(locale, firstRun) s = sublime.load_settings(sFile) s.add_on_change('locale', updateLocale)
def run(self, edit, **args): current_project = sublime.active_window().project_file_name() if current_project is None: current_project = "" executable_path = sublime.executable_path() subprocess.Popen([executable_path, "-n", current_project])
def sublime_package_paths(): """Get all the locations where plugins live.""" return [ sublime.installed_packages_path(), join(dirname(sublime.executable_path()), "Packages"), sublime.packages_path() ]
def run(self, paths = []): import subprocess items = [] items.append(sublime.executable_path()) for item in SideBarSelection(paths).getSelectedItems(): items.append(item.forCwdSystemPath()) items.append(item.path()) subprocess.Popen(items, cwd=items[1])
def open_in_new_window(path): " Open a path in a new ST3 window by invoking the subl cli utility " # https://github.com/titoBouzout/SideBarEnhancements/blob/st3/SideBar.py#L1643 executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" subprocess.Popen([executable_path, path], env=env())
def get_subl_executable_path(): executable_path = sublime.executable_path() if sublime.platform() == 'osx': suffix = '.app/' app_path = executable_path[:executable_path.rfind(suffix) + len(suffix)] executable_path = app_path + 'Contents/SharedSupport/bin/subl' return executable_path
def defaultMenuOverrides( self ): ## Let's remove 'Copy File Path' from default menus; we'll add our own # Create a 'Default' directory in /Packages/ so we can override the default ST menu; 'Default' will be automagically created if it doesn't already exist packages_default_dir = os.path.join( os.path.dirname( sublime.packages_path() ), 'Packages', 'Default' ) # TODO: implement or remove this #if not os.path.exists( packages_default_dir ): # os.mkdir( packages_default_dir ) # Get ST's Default.sublime-package default_sublime_package = os.path.join( os.path.dirname( sublime.executable_path() ), 'Packages', 'Default.sublime-package' ) # Read archive contents but don't truncate archive = open( default_sublime_package, 'rb') # Unzip archive unzippedArchive = zipfile.ZipFile( archive ) # Iterate over archive files for name in unzippedArchive.namelist(): # Extract file we need unzippedArchive.extract( 'Context.sublime-menu', packages_default_dir ) # Close archive unzippedArchive.close() ## Edit /Packages/Default/Context.sublime-menu created by File Metadata plugin # Retrieve file context_sublime_menu = os.path.join( os.path.dirname( sublime.packages_path() ), 'Packages', 'Default', 'Context.sublime-menu' ) # Open file in 'read' mode f = open( context_sublime_menu, 'r' ) # Get all lines from the file lines = f.readlines() # Close the file f.close() # Re-open the file in 'write' mode (why you need to do dis twice, Python??) f = open( context_sublime_menu, 'w' ) # Iterate over lines for line in lines: # If line doesn't match our exclude pattern if not '{ "command": "copy_path", "caption": "Copy File Path" }' in line: # Write the remaining lines f.write(line) # Close the file f.close()
def get_subl_executable_path( self ): """Return the path to the subl command line binary.""" executable_path = sublime.executable_path() if sublime.platform() == 'osx': suffix = '.app/' app_path = executable_path[:executable_path.rfind(suffix) + len(suffix)] executable_path = app_path + 'Contents/SharedSupport/bin/subl' return executable_path
def get_subl_executable_path(): """Return the path to the subl command line binary.""" executable_path = sublime.executable_path() if sublime.platform() == "osx": suffix = ".app/" app_path = executable_path[: executable_path.rfind(suffix) + len(suffix)] executable_path = app_path + "Contents/SharedSupport/bin/subl" return executable_path
def extract_package(package): if VERSION >= 3006: package_location = os.path.join(sublime.installed_packages_path(), package + ".sublime-package") if not os.path.exists(package_location): package_location = os.path.join(os.path.dirname(sublime.executable_path()), "Packages", package + ".sublime-package") if not os.path.exists(package_location): package_location = None if package_location: with zipfile.ZipFile(package_location) as zip_file: extract_location = os.path.join(sublime.packages_path(), package) zip_file.extractall(extract_location)
def get_installed_packages(ignore_packages=True, ignore_patterns=[]): package_set = set() if int(sublime.version()) >= 3006: package_set.update(_get_packages_from_directory(sublime.installed_packages_path(), ".sublime-package")) executable_package_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages" package_set.update(_get_packages_from_directory(executable_package_path, ".sublime-package")) return sorted(list(_remove_ignored_packages(ignore_packages, ignore_patterns, package_set)))
def subl(*args): executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" subprocess.Popen([executable_path] + list(args)) if sublime.platform() == "windows": def fix_focus(): window = sublime.active_window() view = window.active_view() window.run_command('focus_neighboring_group') window.focus_view(view) sublime.set_timeout(fix_focus, 300)
def update(self, cmd, env): fp = self.view.file_name() or "" dp = os.path.dirname(fp) fn = os.path.basename(fp) bn = os.path.splitext(fn)[0] ex = os.path.splitext(fn)[1].strip(".").lower() st = os.path.dirname(sublime.executable_path()) sd = os.path.dirname(st) for var in env: env[var] = os.path.expandvars(env[var]).format(**locals()).split(";") env[var] = ";".join(path for iglob in map(glob.iglob, env[var]) for path in iglob) return cmd.format(**locals()), dp if os.path.exists(dp) else None
def open_in_new_window(self, paths=[], cmd=None): """Open paths in a new sublime window.""" # from wbond https://github.com/titoBouzout/SideBarEnhancements/blob/st3/SideBar.py#L1916 items = [] executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" items.append(executable_path) if cmd: items.extend(['--command', cmd]) items.extend(paths) subprocess.Popen(items)
def list_default_packages(self): """ :return: A list of all default package names""" if int(sublime.version()) > 3000: bundled_packages_path = os.path.join(os.path.dirname(sublime.executable_path()), 'Packages') files = os.listdir(bundled_packages_path) else: files = os.listdir(os.path.join(os.path.dirname( sublime.packages_path()), 'Pristine Packages')) files = list(set(files) - set(os.listdir( sublime.installed_packages_path()))) packages = [file.replace('.sublime-package', '') for file in files] packages = sorted(packages, key=lambda s: s.lower()) return packages
def reboot(): import os, subprocess opened_file = sublime.active_window().active_view().file_name() if opened_file is None: opened_file = os.path.join(sublime.packages_path(), 'User', 'Preferences.sublime-settings') if sublime.platform() == 'linux': subl_path = sublime.executable_path().replace(' ','\ ') command = ' '.join([ subl_path, '--command', 'exit', '&&', 'sleep', '0.5', '&&', subl_path, opened_file.replace(' ','\ '), '&', 'kill', '-9', '$$' ]) elif sublime.platform() == 'osx': subl_path = sublime.executable_path().replace(' ','\ ') subl_path = subl_path[:subl_path.rfind('.app/') + 5] + '/Contents/SharedSupport/bin/subl' command = ' '.join([ subl_path, '--command', 'exit', '&&', 'sleep', '0.5', '&&', subl_path, opened_file.replace(' ','\ '), '&', 'kill', '-9', '$$' ]) elif sublime.platform() == 'windows': subl_path = sublime.executable_path() subl_path = '"' + subl_path[:subl_path.rfind('\\') + 1] + 'subl' + '"' command = ' '.join([ subl_path, '--command', 'exit', '&&', 'ping', '-n', '1', 'localhost', '&&', subl_path, '"' + opened_file.replace + '"' ]) subprocess.Popen(command, shell=True)
def run(self, edit): items = [] files = self.get_marked() or self.get_selected() if ST3: # sublime.executable_path() is not available in ST2 executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/")+5] executable_path = app_path+"Contents/SharedSupport/bin/subl" items.append(executable_path) items.append("-n") for filename in files: fqn = join(self.path, filename) items.append(fqn) subprocess.Popen(items, cwd=self.path) else: # ST2 items.append("-n") for filename in files: fqn = join(self.path, filename) items.append(fqn) if sublime.platform() == 'osx': try: subprocess.Popen(['subl'] + items, cwd=self.path) except: try: subprocess.Popen(['sublime'] + items, cwd=self.path) except: subprocess.Popen(['/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl'] + items, cwd=self.path) elif sublime.platform() == 'windows': # 9200 means win8 shell = True if sys.getwindowsversion()[2] < 9200 else False items = [i.encode(locale.getpreferredencoding(False)) if sys.getwindowsversion()[2] == 9200 else i for i in items] try: subprocess.Popen(['subl'] + items, cwd=self.path, shell=shell) except: try: subprocess.Popen(['sublime'] + items, cwd=self.path, shell=shell) except: subprocess.Popen(['sublime_text.exe'] + items, cwd=self.path, shell=shell) else: try: subprocess.Popen(['subl'] + items, cwd=self.path) except: subprocess.Popen(['sublime'] + items, cwd=self.path)
def _get_resource(package_name, resource, return_binary=False, encoding="utf-8"): packages_path = sublime.packages_path() content = None if VERSION > 3013: try: if return_binary: content = sublime.load_binary_resource("Packages/" + package_name + "/" + resource) else: content = sublime.load_resource("Packages/" + package_name + "/" + resource) except IOError: pass else: path = None if os.path.exists(os.path.join(packages_path, package_name, resource)): path = os.path.join(packages_path, package_name, resource) content = _get_directory_item_content(path, return_binary, encoding) if VERSION >= 3006: sublime_package = package_name + ".sublime-package" packages_path = sublime.installed_packages_path() if content is None: if os.path.exists(os.path.join(packages_path, sublime_package)): content = _get_zip_item_content( os.path.join(packages_path, sublime_package), resource, return_binary, encoding) packages_path = os.path.dirname( sublime.executable_path()) + os.sep + "Packages" if content is None: if os.path.exists(os.path.join(packages_path, sublime_package)): content = _get_zip_item_content( os.path.join(packages_path, sublime_package), resource, return_binary, encoding) return content
def open(self, path): ''' Open project from file name. ''' import subprocess if not path.endswith('.sublime-project'): path += '.sublime-project' executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + 'Contents/SharedSupport/bin/subl' command = [executable_path, '--project ', path] sublime.set_timeout_async( lambda: subprocess.Popen(command), 10)
def run(self, edit): items = [] files = self.get_marked() or self.get_selected() if ST3: # sublime.executable_path() is not available in ST2 executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/")+5] executable_path = app_path+"Contents/SharedSupport/bin/subl" items.append(executable_path) items.append("-n") for filename in files: fqn = join(self.path, filename) items.append(fqn) subprocess.Popen(items, cwd=self.path) else: # ST2 items.append("-n") for filename in files: fqn = join(self.path, filename) items.append(fqn) if sublime.platform() == 'osx': try: subprocess.Popen(['subl'] + items, cwd=self.path) except: try: subprocess.Popen(['sublime'] + items, cwd=self.path) except: subprocess.Popen(['/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl'] + items, cwd=self.path) elif sublime.platform() == 'windows': try: subprocess.Popen(['subl'] + items, cwd=self.path, shell=True) except: try: subprocess.Popen(['sublime'] + items, cwd=self.path, shell=True) except: subprocess.Popen(['sublime_text.exe'] + items, cwd=self.path, shell=True) else: try: subprocess.Popen(['subl'] + items, cwd=self.path) except: subprocess.Popen(['sublime'] + items, cwd=self.path)
def subl(*args): executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind('.app/') + 5] executable_path = app_path + 'Contents/SharedSupport/bin/subl' subprocess.Popen([executable_path] + list(args)) def on_activated(): if sublime.platform() == 'windows': # refocus sublime text window subprocess.Popen([executable_path, "--command", ""]) window = sublime.active_window() view = window.active_view() sublime_plugin.on_activated(view.id()) sublime_plugin.on_activated_async(view.id()) sublime.set_timeout(on_activated, 300)
def list_default_packages(self): """ :return: A list of all default package names""" if int(sublime.version()) > 3000: bundled_packages_path = os.path.join( os.path.dirname(sublime.executable_path()), 'Packages') files = os.listdir(bundled_packages_path) else: files = os.listdir( os.path.join(os.path.dirname(sublime.packages_path()), 'Pristine Packages')) files = list( set(files) - set(os.listdir(sublime.installed_packages_path()))) packages = [file.replace('.sublime-package', '') for file in files] packages = sorted(packages, key=lambda s: s.lower()) return packages
def run(self, folder, append=False): data = self.window.project_data() if (not data): data = {} data["folders"] = [] if (tools.check_sidebar_folder(folder)): return if (data and append): Popen([sublime.executable_path(), "-a", folder]) else: new_folder = {} new_folder['path'] = folder data['folders'] = [new_folder] self.window.set_project_data(data)
def apply_settings_template(self, settings): # must only be defined after plugin_loaded() template_variables = { "st_cache_path": sublime.cache_path(), "st_executable_path": sublime.executable_path(), "st_installed_packages_path": sublime.installed_packages_path(), "st_packages_path": sublime.packages_path(), "user_home_path": os.path.expanduser("~"), } for key in self.templated_keys: settings.set( key, string.Template(settings.get(key)) .safe_substitute(template_variables) ) return settings
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 action_edit_in_new_window(self): args = [] executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" else: executable_path = os.path.join(os.path.dirname(executable_path), 'subl') args.append(executable_path) path = os.path.abspath(self.path) args.append(path) spec = Specification(args) spec.quote() spec = self.get_spec('detach_run', spec) spec = self.get_spec('shell', spec) spec.popen()
def on_skin_selected(selected_skin_id): """ This is a callback upon user selecting a skin. This can handle user canceling the input. Upon selection a respective path is evaluated and send to a new sublime text instance. """ if selected_skin_id == -1: return skins_path = get_cached_skin_path() skins = os.listdir(skins_path) selected_skin = skins[selected_skin_id] selected_skin_path = os.path.join(skins_path, selected_skin) # to open a folder in new window, just create a new process with the folder as argument st_path = sublime.executable_path() subprocess.Popen([st_path, selected_skin_path])
def run(self, paths=[]): import subprocess items = [] executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" items.append(executable_path) filePath = self.window.active_view().file_name() dirName = os.path.dirname(filePath) items.append(dirName) items.append(filePath) p = subprocess.Popen(items)
def extract_package(package): if VERSION >= 3006: package_location = os.path.join(sublime.installed_packages_path(), package + ".sublime-package") if not os.path.exists(package_location): package_location = os.path.join( os.path.dirname(sublime.executable_path()), "Packages", package + ".sublime-package") if not os.path.exists(package_location): package_location = None if package_location: with zipfile.ZipFile(package_location) as zip_file: extract_location = os.path.join(sublime.packages_path(), package) zip_file.extractall(extract_location) full_path = os.path.join(extract_location, '.extracted-sublime-package') if not os.path.exists(full_path): open(full_path, 'a').close()
def run(self): """ This method is automatically called when sublime_tutor command is executed""" import subprocess executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" plugin_dir = os.path.dirname(os.path.realpath(__file__)) tutorial_dir = os.path.join(plugin_dir, 'tutorial') chapter_1 = os.path.join(plugin_dir, 'tutorial', 'README.md') subprocess.Popen([ executable_path, tutorial_dir, chapter_1, '--project', tutorial_dir + '/sublimetutor.sublime-project' ], cwd=plugin_dir)
def create_sublime_project(self, path): parent, leaf = os.path.split(path) data = { 'folders': [{ 'follow_symlinks': True, 'path': '.' }] } proj_file = os.path.join(path, leaf + '.sublime-project') with open(proj_file, 'wt') as f: f.write(json.dumps(data)) try: Popen([sublime.executable_path(), proj_file], startupinfo=supress_window()) except Exception as e: _logger.debug('could not open new project with subl[.exe]') _logger.debug(e)
def open_project(self, open_path): executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" if sublime.platform() == "windows": subprocess.Popen('"{0}" --project "{1}"'.format( executable_path, open_path), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) else: process = subprocess.Popen( [executable_path, '--project', open_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() self.debug(stdout) self.showlog(stderr)
def get_packages_list(ignore_packages=True): """ Return a list of packages. """ package_set = set() package_set.update(_get_packages_from_directory(sublime.packages_path())) if int(sublime.version()) >= 3006: package_set.update(_get_packages_from_directory(sublime.installed_packages_path(), ".sublime-package")) executable_package_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages" package_set.update(_get_packages_from_directory(executable_package_path, ".sublime-package")) if ignore_packages: ignored_package_list = sublime.load_settings( "Preferences.sublime-settings").get("ignored_packages", []) for ignored in ignored_package_list: package_set.discard(ignored) return sorted(list(package_set))
def run(self): if self.window.project_file_name() is not None: sublime.error_message('This window already has a project.') return if len(self.window.folders()) == 0: sublime.error_message('Add folders before running.') return if len(self.window.folders()) != 1: # TODO: UI to pick one sublime.error_message('Too many folders.') return for view in self.window.views(): if view.is_dirty(): sublime.error_message('Save all views before running.') return project = """ { "folders": [ { "path": ".", "folder_exclude_patterns": ["target"] } ] } """ folder = self.window.folders()[0] name = os.path.basename(folder) project_path = os.path.join(self.window.folders()[0], '%s.sublime-project' % (name, )) if os.path.exists(project_path): sublime.error_message('Path %r already exists.' % (project_path, )) return open(project_path, 'w').write(project) subl = sublime.executable_path() if sublime.platform() == 'osx': subl = subl[:subl.rfind(".app/") + 5] + 'Contents/SharedSupport/bin/subl' self.window.run_command('close_all') self.window.run_command('close_project') subprocess.check_call([subl, project_path])
def set_executable_path(): global ExecutablePath path = sublime.executable_path() if os.path.exists(path): ExecutablePath = path return else: path = None plat = sublime.platform() logger.debug('Platform = %s', plat) if (plat == 'windows'): version = sublime.version()[0] logger.debug('Version = %s', version) arch = sublime.arch() logger.debug('Architecture = %s', arch) folder = 'Sublime Text %s' % version if (arch == 'x32'): path = os.path.join(get_env('ProgramFiles'), folder) elif (arch == 'x64'): path = os.path.join(get_env('ProgramW6432'), folder) if (path is not None) and os.path.isdir(path): exe_path = os.path.join(path, 'subl.exe') if os.path.isfile(exe_path): path = exe_path else: exe_path = os.path.join(path, 'sublime_text.exe') if os.path.isfile(exe_path): path = exe_path if ((path is None) or (not os.path.isfile(path))): path = 'sublime_text.exe' elif (plat == 'osx'): path = 'subl' elif (plat == 'linux'): path = 'subl' ExecutablePath = path
def run(self): log(2, "Entering on run(1)") with lock_context_manager() as is_allowed: if not is_allowed: return package_path = os.path.join( os.path.dirname(sublime.executable_path()), "Packages", packages_upstream_name) upstream_directory = os.path.join( os.path.dirname(sublime.packages_path()), packages_upstream_name) log(2, "run, package_path: " + package_path) log(2, "run, upstream_directory: " + upstream_directory) extract_package(package_path, upstream_directory) create_git_ignore_file(upstream_directory) create_version_setting_file(upstream_directory) free_mutex_lock()
def get_folder_map() -> Dict[str, str]: return { name: str(path.resolve()) for name, path in { # from OS "home": Path.home(), "temp_dir": Path(tempfile.gettempdir()), # from ST itself "bin": Path(sublime.executable_path()).parent, "cache": Path(sublime.cache_path()), "data": Path(sublime.packages_path(), ".."), "index": Path(sublime.cache_path()) / ".." / "Index", "installed_packages": Path(sublime.installed_packages_path()), "lib": Path(sublime.packages_path()) / ".." / "Lib", "local": Path(sublime.packages_path()) / ".." / "Local", "log": Path(sublime.packages_path()) / ".." / "Log", "packages": Path(sublime.packages_path()), # from LSP "package_storage": Path(sublime.cache_path()) / ".." / "Package Storage", }.items() }
def subl(*args): executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind('.app/') + 5] executable_path = app_path + 'Contents/SharedSupport/bin/subl' subprocess.Popen([executable_path] + list(args)) def on_activated(): window = sublime.active_window() view = window.active_view() if sublime.platform() == 'windows': # fix focus on windows window.run_command('focus_neighboring_group') window.focus_view(view) sublime_plugin.on_activated(view.id()) sublime_plugin.on_activated_async(view.id()) sublime.set_timeout(on_activated, 300)
def list_package_files(package, ignore_patterns=[]): """ List files in the specified package. """ package_path = os.path.join(sublime.packages_path(), package, "") path = None file_set = set() file_list = [] if os.path.exists(package_path): for root, directories, filenames in os.walk(package_path): temp = root.replace(package_path, "") for filename in filenames: file_list.append(os.path.join(temp, filename)) file_set.update(file_list) if ST2 is False: sublime_package = package + ".sublime-package" packages_path = sublime.installed_packages_path() if os.path.exists(os.path.join(packages_path, sublime_package)): file_set.update(_list_files_in_zip(packages_path, sublime_package)) packages_path = os.path.dirname( sublime.executable_path()) + os.sep + "Packages" if os.path.exists(os.path.join(packages_path, sublime_package)): file_set.update(_list_files_in_zip(packages_path, sublime_package)) file_list = [] for filename in file_set: if not _ignore_file(filename, ignore_patterns): file_list.append(_normalize_to_sublime_path(filename)) return sorted(file_list)
def get_package_and_resource_name(path): """ This method will return the package name and resource name from a path. Arguments: path Path to parse for package and resource name. """ package = None resource = None path = _normalize_to_sublime_path(path) if os.path.isabs(path): packages_path = _normalize_to_sublime_path(sublime.packages_path()) if path.startswith(packages_path): package, resource = _search_for_package_and_resource( path, packages_path) if int(sublime.version()) >= 3006: packages_path = _normalize_to_sublime_path( sublime.installed_packages_path()) if path.startswith(packages_path): package, resource = _search_for_package_and_resource( path, packages_path) packages_path = _normalize_to_sublime_path( os.path.dirname(sublime.executable_path()) + os.sep + "Packages") if path.startswith(packages_path): package, resource = _search_for_package_and_resource( path, packages_path) else: path = re.sub(r"^Packages/", "", path) split = re.split(r"/", path, 1) package = split[0] package = package.replace(".sublime-package", "") resource = split[1] return (package, resource)
def sublime_executable_path(): """ Return the Sublime Text 2 installation path for each platform """ platform = sublime.platform() error = sublime.set_timeout( functools.partial(get_settings, 'osx_st2_path'), 0) # in Sublime Text 3 we can just use `sublime.executable_path() if SUBLIME_TEXT_3 is True: return sublime.executable_path() if platform == 'osx': if not error: return ('/Applications/Sublime Text 2.app' '/Contents/SharedSupport/bin/subl') else: return error if platform == 'linux': if os.path.exists('/proc/self/cmdline'): return open('/proc/self/cmdline').read().split(chr(0))[0] return sys.executable
def _get_default_packages(): default_path = os.path.join(os.path.dirname(sublime.executable_path()), "Packages") return _archived_packages_in_path(default_path)
def sublime_package_paths(): return [ sublime.installed_packages_path(), join(dirname(sublime.executable_path()), 'Packages') ]
def get_installed_resource_roots(): return ( sublime.installed_packages_path(), Path(sublime.executable_path()).parent / 'Packages', )
def get_builtin_pkg_path(): base_path = os.path.dirname(sublime.executable_path()) ret = os.path.join(base_path, 'Packages') return ret
def init(cls): exe_path = os.path.dirname(sublime.executable_path()) cls.shipped_packages_path = os.path.join(exe_path, "Packages")
def get_sublime_path(): if sublime.platform() == 'osx': base_dir = os.path.dirname(sublime.executable_path()) return os.path.relpath(SUBL_PATH, base_dir) else: # I hope this works on Windows and Linux return sublime.executable_path()
def get_sublime_exe(): ''' Utility function to get the full path to the currently executing Sublime instance. ''' processes = ['subl', 'sublime_text'] def check_processes(st2_dir=None): if st2_dir is None or os.path.exists(st2_dir): for process in processes: try: if st2_dir is not None: process = os.path.join(st2_dir, process) m = SUBLIME_VERSION.search( check_output([process, '-v'], use_texpath=False)) if m and m.group(1) == version: return process except: pass return None platform = sublime.platform() plat_settings = get_setting(platform, {}) sublime_executable = plat_settings.get('sublime_executable', None) if sublime_executable: return sublime_executable # we cache the results of the other checks, if possible if hasattr(get_sublime_exe, 'result'): return get_sublime_exe.result # are we on ST3 if hasattr(sublime, 'executable_path'): get_sublime_exe.result = sublime.executable_path() # on osx, the executable does not function the same as subl if platform == 'osx': get_sublime_exe.result = os.path.normpath( os.path.join(os.path.dirname(get_sublime_exe.result), '..', 'SharedSupport', 'bin', 'subl')) # on linux, it is preferable to use subl if it points to the # correct version see issue #710 for a case where this is useful elif (platform == 'linux' and not get_sublime_exe.result.endswith('subl')): subl = which('subl') if subl is not None: try: m = SUBLIME_VERSION.search( check_output([subl, '-v'], use_texpath=False)) if m and m.group(1) == sublime.version(): get_sublime_exe.result = subl except: pass return get_sublime_exe.result # in ST2 on Windows the Python executable is actually "sublime_text" elif platform == 'windows' and sys.executable != 'python' and \ os.path.isabs(sys.executable): get_sublime_exe.result = sys.executable return get_sublime_exe.result # guess-work for ST2 version = sublime.version() # hope its on the path result = check_processes() if result is not None: get_sublime_exe.result = result return result # guess the default location if platform == 'windows': st2_dir = os.path.expandvars('%PROGRAMFILES%\\Sublime Text 2') result = check_processes(st2_dir) if result is not None: get_sublime_exe.result = result return result elif platform == 'linux': for path in [ '$HOME/bin', '$HOME/sublime_text_2', '$HOME/sublime_text', '/opt/sublime_text_2', '/opt/sublime_text', '/usr/local/bin', '/usr/bin' ]: st2_dir = os.path.expandvars(path) result = check_processes(st2_dir) if result is not None: get_sublime_exe.result = result return result else: st2_dir = '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin' result = check_processes(st2_dir) if result is not None: get_sublime_exe.result = result return result try: folder = check_output( ['mdfind', '"kMDItemCFBundleIdentifier == com.sublimetext.2"'], use_texpath=False) st2_dir = os.path.join(folder, 'Contents', 'SharedSupport', 'bin') result = check_processes(st2_dir) if result is not None: get_sublime_exe.result = result return result except: pass print('Cannot determine the path to your Sublime installation. Please ' 'set the "sublime_executable" setting in your settings for your ' 'platform.') return None
winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinMergeU.exe') except: if os.path.isfile( os.path.join(os.environ['ProgramFiles(x86)'], "WinMerge", "WinMergeU.exe")): WINMERGE = os.path.join(os.environ['ProgramFiles(x86)'], "WinMerge", "WinMergeU.exe") elif os.path.isfile( os.path.join(os.environ['ProgramFiles'], "WinMerge", "WinMergeU.exe")): WINMERGE = os.path.join(os.environ['ProgramFiles'], "WinMerge", "WinMergeU.exe") elif os.path.isfile( os.path.join( os.path.dirname(os.path.dirname(sublime.executable_path())), "WinMergePortable", "WinMergePortable.exe")): WINMERGE = os.path.join( os.path.dirname(os.path.dirname(sublime.executable_path())), "WinMergePortable", "WinMergePortable.exe") else: # Hope it's in the path WINMERGE = '"WinMergeU.exe"' fileA = fileB = None def recordActiveFile(f): global fileA global fileB fileB = fileA