def run(self): print ('ok') sublime.status_message("Indexing Color Schemes..") self.initial = sublime.load_settings("Preferences.sublime-settings").get('color_scheme') self.syntax = list(sorted(sublime.find_resources("*.tmTheme") + sublime.find_resources("*.sublime-syntax"))) sublime.status_message("Found {0} color schemes in total".format(len(self.syntax))) self.display_list(self.syntax)
def set_syntax_by_host(host, view): """ Sets the view's syntax by using the host_to_syntax for an lookup. """ settings = sublime.load_settings('GhostText.sublime-settings') host_to_syntax = settings.get('host_to_syntax') syntax = None syntax_part = None for host_fragment in host_to_syntax: if host_fragment not in host: continue syntax_part = host_to_syntax[host_fragment] resources = sublime.find_resources('*{}'.format(syntax_part)) if len(resources) > 0: syntax = resources[0] if syntax is not None: view.set_syntax_file(syntax) else: if syntax_part is not None: sublime.error_message('Syntax "{}" is not installed!'.format(syntax_part)) default_syntax = settings.get('default_syntax', 'Markdown.tmLanguage') resources = sublime.find_resources('*{}'.format(default_syntax)) if len(resources) > 0: view.set_syntax_file(resources[0]) else: print('Default syntax "{}" is not installed!'.format(default_syntax))
def get_items(): """Return a list of quick panel items for all color schemes. The values are the full path of each *.tmTheme. NOTE: Excludes color schemes manipulated by SublimeLinter as they are automatically created and used if required. """ names = [] values = [] settings = sublime.load_settings("Theme-Switcher.sublime-settings") exclude_list = settings.get("colors_exclude") or [] paths = sorted( sublime.find_resources("*.sublime-color-scheme") + sublime.find_resources("*.tmTheme"), key=lambda x: os.path.basename(x).lower()) for path in paths: if not any(exclude in path for exclude in exclude_list): elems = path.split("/") # elems[1] package name # elems[-1] color scheme file name names.append( [built_res_name(elems[-1]), # title "Package: " + elems[1]]) # description values.append(path) return [names, values]
def findSyntaxFilePaths(self, dropDuplicated=False): """ @brief find the path of all syntax files @param dropDuplicated if True, for a syntax, only the highest priority resource will be returned @return list<string> the path of all syntax files """ if dropDuplicated is False: syntaxFiles = [] for syntaxFileExt in ST_LANGUAGES: syntaxFiles += sublime.find_resources('*'+syntaxFileExt) else: # key = syntax resource path without extension # value = the corresponding extension # example: { 'Packages/Java/Java': '.sublime-syntax' } syntaxGriddle = {} for syntaxFileExt in ST_LANGUAGES: resources = sublime.find_resources('*'+syntaxFileExt) for resource in resources: resourceName, resourceExt = os.path.splitext(resource) if resourceName not in syntaxGriddle: syntaxGriddle[resourceName] = resourceExt # combine a name and an extension back into a full path syntaxFiles = [n+e for n, e in syntaxGriddle.items()] return syntaxFiles
def get_all_syntax_files(): """ Find all sublime-syntax and tmLanguage files. """ syntax_files = [] if USE_ST_SYNTAX: syntax_files += sublime.find_resources("*.sublime-syntax") syntax_files += sublime.find_resources("*.tmLanguage") return syntax_files
def _load_settings(self, on_loaded_once=None): """Load and merge settings and their comments from all base files. The idea is each package which wants to add a valid entry to the `Preferences.sublime-settings` file must provide such a file with all keys it wants to add. These keys and the associated comments above it are loaded into dictionaries and used to provide tooltips, completions and linting. """ ignored_patterns = frozenset(("/User/", "/Preferences Editor/")) # TODO project settings include "Preferences", # but we don't have a syntax def for those yet l.debug("loading defaults and comments for %r", self.filename) start_time = time.time() resources = sublime.find_resources(self.filename) resources += sublime.find_resources(self.filename + "-hints") if self.filename == PREF_FILE: resources += sublime.find_resources(PREF_FILE_ALIAS) l.debug("found %d %r files", len(resources), self.filename) for resource in resources: if any(ignored in resource for ignored in ignored_patterns): l.debug("ignoring %r", resource) continue try: l.debug("parsing %r", resource) lines = sublime.load_resource(resource).splitlines() for key, value in self._parse_settings(lines).items(): # merge settings without overwriting existing ones self.defaults.setdefault(key, value) except Exception as e: l.error("error parsing %r - %s%s", resource, e.__class__.__name__, e.args) duration = time.time() - start_time l.debug("loading took %.3fs", duration) # include general settings if we're in a syntax-specific file is_syntax_specific = self._is_syntax_specific() if is_syntax_specific and not self.fallback_settings: self.fallback_settings = KnownSettings(PREF_FILE) # add fallbacks to the ChainMaps self.defaults.maps.append(self.fallback_settings.defaults) self.comments.maps.append(self.fallback_settings.comments) # these may be loaded later, so delay calling our own callbacks self.fallback_settings.add_on_loaded(self._has_loaded, once=True) else: if self.fallback_settings and not is_syntax_specific: # file was renamed, probably self.fallback_settings = None self.defaults.maps.pop() self.comments.maps.pop() self._has_loaded()
def run(self): self.prefs = sublime.load_settings(self.PREFS_FILE) self.views = None self.current = self.prefs.get('color_scheme', self.DEFAULT_CS) show_legacy = sublime.load_settings( "Preferences.sublime-settings").get("show_legacy_color_schemes", False) initial_highlight = -1 self.schemes = [] names = [] package_set = set() files = sublime.find_resources('*.tmTheme') trimmed_names = set() for f in files: name, ext = os.path.splitext(os.path.basename(f)) trimmed_names.add(name) # Add all the sublime-color-scheme files, but not the overrides for f in sublime.find_resources('*.sublime-color-scheme'): name, ext = os.path.splitext(os.path.basename(f)) if not name in trimmed_names: trimmed_names.add(name) files.append(f) for cs in files: if self.current and cs == self.current: initial_highlight = len(self.schemes) if len(cs.split('/', 2)) != 3: # Not in a package continue pkg = os.path.dirname(cs) if pkg == "Packages/Color Scheme - Legacy" and not show_legacy: continue if pkg.startswith("Packages/"): pkg = pkg[len("Packages/"):] name, ext = os.path.splitext(os.path.basename(cs)) self.schemes.append(cs) names.append([name, pkg]) package_set.add(pkg) # Don't show the package name if all color schemes are in the same # package if len(package_set) == 1: names = [name for name, pkg in names] self.window.show_quick_panel( names, self.on_done, sublime.KEEP_OPEN_ON_FOCUS_LOST, initial_highlight, self.on_highlighted )
def find_tooltip_themes(self): """ Find all SublimeLinter.tooltip-theme resources. For each found resource, if it doesn't match one of the patterns from the "tooltip_theme_excludes" setting, return the base name of resource and info on whether the theme is a standard theme or a user theme, as well as whether it is colorized. The list of paths to the resources is appended to self.themes. """ self.themes = [] settings = [] tooltip_themes = sublime.find_resources('*.tooltip-theme') excludes = persist.settings.get('tooltip_theme_excludes', []) for theme in tooltip_themes: exclude = False parent = os.path.dirname(theme) htmls = sublime.find_resources('*.html') if '{}/tooltip.html'.format(parent) not in htmls: continue # Now see if the theme name is in tooltip_theme_excludes name = os.path.splitext(os.path.basename(theme))[0] for pattern in excludes: if fnmatch(name, pattern): exclude = True break if exclude: continue self.themes.append(theme) std_theme = theme.startswith('Packages/SublimeLinter/tooltip-themes/') settings.append([ name, 'SublimeLinter theme' if std_theme else 'User theme' ]) # Sort self.themes and settings in parallel using the zip trick settings, self.themes = zip(*sorted(zip(settings, self.themes))) # zip returns tuples, convert back to lists settings = list(settings) self.themes = list(self.themes) return settings
def set_syntax(self, syntax): langs = sublime.find_resources('*language') langs += sublime.find_resources('*sublime-syntax') new_syntax = next((s for s in langs if syntax[0] in s), None) print('new syntax is ' + new_syntax) if new_syntax != self.syn: # let's make sure it exists first! # if os.path.exists(new_syntax_path): self.view.set_syntax_file(new_syntax) print('Syntax set to ' + syntax[0] + ' using ' + new_syntax)
def validate_skin(skin_data, fallback_theme=None, fallback_colors=None): """Check skin integrity and return the boolean result. For a skin to be valid at least 'color_scheme' or 'theme' must exist. If one of both values is invalid, it may be replaced with a fallback value. Otherwise SublimeText's behavior when loading the skin is unpredictable. SublimeLinter automatically creates and applies patched color schemes if they doesn't contain linter icon scopes. To ensure not to break this feature this function ensures not to apply such a hacked color scheme directly so SublimeLinter can do his job correctly. Arguments: skin_data (dict): JSON object with all settings to apply for the skin. fallback_theme (string): A valid theme name to inject into skin_data, if skin_data does not contain a valid one. fallback_colors (string): A valid color_scheme path to inject into skin_data, if skin_data does not contain a valid one. """ # check theme file theme_name = skin_data[PREF].get("theme") theme_ok = theme_name and sublime.find_resources(theme_name) # check color scheme color_scheme_ok = False color_scheme_name = skin_data[PREF].get("color_scheme") if color_scheme_name: path, tail = os.path.split(color_scheme_name) name = tail.replace(" (SL)", "") color_schemes = sublime.find_resources(name) if color_schemes: # Try to find the exact path from *.skins file resource_path = "/".join((path, name)) for found in color_schemes: if found == resource_path: color_scheme_ok = True break # Use the first found color scheme which matches 'name' if not color_scheme_ok: skin_data[PREF]["color_scheme"] = color_schemes[0] color_scheme_ok = True valid = theme_ok or color_scheme_ok if valid: if fallback_theme and not theme_ok: skin_data[PREF]["theme"] = fallback_theme if fallback_colors and not color_scheme_ok: skin_data[PREF]["color_scheme"] = fallback_colors return valid
def find_syntax_files(self): # ST3 if hasattr(sublime, 'find_resources'): for f in sublime.find_resources("*.tmLanguage"): yield f for f in sublime.find_resources("*.sublime-syntax"): yield f else: for root, dirs, files in os.walk(sublime.packages_path()): for f in files: if f.endswith(".tmLanguage") or f.endswith("*.sublime-syntax"): langfile = os.path.relpath(os.path.join(root, f), sublime.packages_path()) # ST2 (as of build 2181) requires unix/MSYS style paths for the 'syntax' view setting yield os.path.join('Packages', langfile).replace("\\", "/")
def getMarkWarningPng(): """ Retrieve png for warning mark.""" if ErrorsHandler.mark_warning_png is None: ErrorsHandler.mark_warning_png = sublime.find_resources( "cfserver-mark-warning.png")[0] return ErrorsHandler.mark_warning_png
def plugin_loaded(): print('themr ready') def on_theme_change(): the_theme = Themr.get_theme() if sublime.find_resources(the_theme): Themr.theme = the_theme else: Themr.set_theme(Themr.theme) sublime.status_message('Theme not found. Reverting to ' + Themr.theme) def on_ignored_packages_change(): the_theme = Themr.get_theme() if sublime.find_resources(the_theme): Themr.theme = the_theme else: Themr.set_theme('Default.sublime-theme') sublime.status_message('Theme disabled. Reverting to Default.sublime-theme') preferences = sublime.load_settings('Preferences.sublime-settings') preferences.add_on_change('theme', on_theme_change) preferences.add_on_change('ignored_packages', on_ignored_packages_change) the_theme = Themr.get_theme() if sublime.find_resources(the_theme): Themr.theme = the_theme else: Themr.set_theme('Default.sublime-theme') sublime.status_message('Theme not found. Reverting to Default.sublime-theme')
def get_installed(logging=True): if logging: log("Getting installed themes") theme_resources = sublime.find_resources("*.sublime-theme") all_themes_ordered = OrderedDict([]) installed_themes = {} for res in theme_resources: package = re.sub(PATTERN, "", res) all_themes_ordered[package] = [] for res in theme_resources: package = re.sub(PATTERN, "", res) theme = os.path.basename(res) all_themes_ordered[package].append(theme) for k in all_themes_ordered.keys(): value = all_themes_ordered[k] is_addon = False is_patch = True if k == settings.OVERLAY_ROOT else False for v in installed_themes.values(): if set(value).issubset(set(v)): is_addon = True if not (is_addon or is_patch): installed_themes[k] = value if logging: dump(installed_themes) return installed_themes
def syntax_testing(self, stream, package): total_assertions = 0 failed_assertions = 0 try: tests = sublime.find_resources("syntax_test*") if package != "__all__": tests = [t for t in tests if t.startswith("Packages/%s/" % package)] # remove UnitTesting syntax_tests tests = [t for t in tests if not t.startswith("Packages/UnitTesting/")] if not tests: raise RuntimeError("No syntax_test files are found in %s!" % package) for t in tests: assertions, test_output_lines = sublime_api.run_syntax_test(t) total_assertions += assertions if len(test_output_lines) > 0: failed_assertions += len(test_output_lines) for line in test_output_lines: stream.write(line + "\n") if failed_assertions > 0: stream.write("FAILED: %d of %d assertions in %d files failed\n" % (failed_assertions, total_assertions, len(tests))) else: stream.write("Success: %d assertions in %s files passed\n" % (total_assertions, len(tests))) stream.write("OK\n") except Exception as e: if not stream.closed: stream.write("ERROR: %s\n" % e) stream.write("\n") stream.write(DONE_MESSAGE) stream.close()
def load_schemes(self): scheme_paths = [] favorites = self.get_favorites() try: # use find_resources() first for ST3. scheme_paths = sublime.find_resources('*.tmTheme') except: # fallback to walk() for ST2 # Load the paths for schemes contained in zipped .sublime-package files. for root, dirs, files in os.walk(sublime.installed_packages_path()): for package in (package for package in files if package.endswith('.sublime-package')): zf = zipfile.ZipFile(os.path.join(sublime.installed_packages_path(), package)) for filename in (filename for filename in zf.namelist() if filename.endswith('.tmTheme')): filepath = os.path.join(root, package, filename).replace(sublime.installed_packages_path(), 'Packages').replace('.sublime-package', '').replace('\\', '/') scheme_paths.append(filepath) # Load the paths for schemes contained in folders. for root, dirs, files in os.walk(sublime.packages_path()): for filename in (filename for filename in files if filename.endswith('.tmTheme')): filepath = os.path.join(root, filename).replace(sublime.packages_path(), 'Packages').replace('\\', '/') scheme_paths.append(filepath) scheme_paths = self.filter_scheme_list(scheme_paths) # Given the paths of all the color schemes, add in the information for # the pretty-printed name and whether or not it's been favorited. schemes = [] for scheme_path in scheme_paths: scheme_name = self.filter_scheme_name(scheme_path) is_favorite = '' if scheme_path in favorites: is_favorite = u' \u2605' # Put a pretty star icon next to favorited schemes. :) schemes.append([scheme_name, scheme_path, is_favorite]) schemes.sort(key=lambda s: s[0].lower()) return schemes
def on_ignored_packages_change(): the_theme = Themr.get_theme() if sublime.find_resources(the_theme): Themr.theme = the_theme else: Themr.set_theme('Default.sublime-theme') sublime.status_message('Theme disabled. Reverting to Default.sublime-theme')
def get_theme(obj, default=None): """ Get the theme for the theme object. See if ST2 or ST3 variant is avaliable, if not use the standard theme format. """ special = "@st3" if ST3 else "@st2" theme = obj.get("theme", None) if theme is None: theme = default elif ST3: parts = os.path.splitext(theme) special_theme = parts[0] + special + parts[1] resources = sublime.find_resources(special_theme) for r in resources: if r == "Packages/Theme - Aprosopo/%s" % special_theme: theme = special_theme break else: parts = os.path.splitext(theme) special_theme = parts[0] + special + parts[1] pkgs = sublime.packages_path() resource = os.path.join(pkgs, "Theme - Aprosopo", special_theme) if os.path.exists(resource): theme = special_theme return theme
def apply_setting(self, name): """Directly apply the provided theme or color scheme.""" if any(sublime.find_resources(os.path.basename(name))): sublime.load_settings(self.PREFS_FILE).set(self.KEY, name) sublime.save_settings(self.PREFS_FILE) else: sublime.status_message(name + " does not exist!")
def on_theme_change(): the_theme = Themr.get_theme() if sublime.find_resources(the_theme): Themr.theme = the_theme else: Themr.set_theme(Themr.theme) sublime.status_message('Theme not found. Reverting to ' + Themr.theme)
def load_themes(self): all_themes = set() try: # use find_resources() first for ST3 for theme_resource in sublime.find_resources('*.sublime-theme'): filename = os.path.basename(theme_resource) all_themes.add(filename) except: # fallback to walk() for ST2 for root, dirs, files in os.walk(sublime.packages_path()): for filename in (filename for filename in files if filename.endswith('.sublime-theme')): all_themes.add(filename) for root, dirs, files in os.walk(sublime.installed_packages_path()): for package in (package for package in files if package.endswith('.sublime-package')): zf = zipfile.ZipFile(os.path.join(sublime.installed_packages_path(), package)) for filename in (filename for filename in zf.namelist() if filename.endswith('.sublime-theme')): all_themes.add(filename) favorite_themes = self.get_favorites() themes = [] for theme in all_themes: favorited = theme in favorite_themes pretty_name = 'Theme: ' + theme.replace('.sublime-theme', '') if favorited: pretty_name += u' \N{BLACK STAR}' # Put a pretty star icon next to favorited themes. :) themes.append([pretty_name, theme, favorited]) themes.sort() return themes
def get_items(): """Return a list of quick panel items for all themes. The values are the basename of each *.sublime-theme. NOTE: Excludes themes manipulated by zz File Icons as they are automatically created and used if required. """ names = [] values = [] settings = sublime.load_settings("Theme-Switcher.sublime-settings") exclude_list = settings.get("themes_exclude") or [] paths = sorted( sublime.find_resources("*.sublime-theme"), key=lambda x: os.path.basename(x).lower()) for path in paths: if not any(exclude in path for exclude in exclude_list): parts = path.split("/") theme = parts[-1] # themes are merged by ST so display only first one if theme in values: continue # parts[1] package name # parts[-1] theme file name names.append( [built_res_name(theme), # title "Package: " + parts[1]]) # description values.append(theme) return [names, values]
def get_cwl_package_files(): results = [ r for r in sublime.find_resources('*.cwl') if (r.startswith('Packages/User/cwl/') or r.startswith('Packages/LaTeX-cwl/')) ] return(results, True) if results else ([], False)
def find_scheme(self, scheme_path): scheme_name = self.filter_scheme_name(scheme_path) scheme_path = sublime.find_resources(scheme_name + '.tmTheme') if len(scheme_path) is not 0: return scheme_path[0] else: return False
def get_language_files(ignored_packages, *paths): r''' Get a list of language files respecting ignored packages. ''' paths = list(paths) tml_files = [] tml_files.extend(sublime.find_resources('*.tmLanguage')) for path in paths: for dir, dirs, files in os.walk(path): # TODO: be sure that not tmLanguage from disabled package is taken for fn in files: if fn.endswith('.tmLanguage'): tml_files.append(os.path.join(dir, fn)) R = re.compile("Packages[\\/]([^\\/]+)[\\/]") result = [] for f in tml_files: m = R.search(f) if m: if m.group(1) not in ignored_packages: result.append(f) return result
def set_from_resources( key, patterns, settings_file=None, set_mode='file', window=None): """Set the key in settings_file from a list of resources found based on patterns. Available values for `set_mode`: * "file": `Packages/Default/Preferences.sublime-settings` * "file_name": `Preferences.sublime-settings` * "file_base_name": `Preferences` """ resources = set() if set_mode == 'file': clean = lambda x: x elif set_mode == 'file_name': clean = os.path.basename elif set_mode == 'file_base_name': clean = lambda x: os.path.splitext(os.path.basename(x))[0] else: sublime.error_message('Unknown set_mode "%s".' % set_mode) return for pattern in _make_list(patterns): resources.update(clean(x) for x in sublime.find_resources(pattern)) on_done = lambda picked: set_key_value(key, picked, settings_file) sublime_wrapper.show_quick_panel(sorted(list(resources)), on_done, window)
def create_menu(command, file_patterns, exclude_setting): d = {} settings = sublime.load_settings("Theme-Switcher.sublime-settings") exclude_list = settings.get(exclude_setting, []) resources = [] for pattern in file_patterns: resources.extend(sublime.find_resources(pattern)) for path in resources: if not any(exclude in path for exclude in exclude_list): elems = path.split("/") # elems[1] package name # elems[-1] theme file name d.setdefault(elems[1], []).append(elems[-1]) menu = [{ "caption": package_name, "children": [{ "caption": built_res_name(theme), "command": command, "args": {"name": theme} } for theme in themes] } for package_name, themes in sorted(d.items())] menu.append({"caption": "-", "id": "separator"}) menu.append({"caption": "Refresh Theme Cache", "command": "refresh_theme_cache"}) return menu
def on_load(self, view): if not requirements_file(view): return syntax_file = "Packages/requirementstxt/requirementstxt.tmLanguage" if hasattr(sublime, "find_resources"): syntax_file = sublime.find_resources("requirementstxt.tmLanguage")[0] view.set_syntax_file(syntax_file)
def run(self): """ Search for all packages and load them """ default_packages = [] for filepath in sublime.find_resources("*.javatar-packages"): filename = basename(filepath) ActionHistory().add_action( "javatar.core.packages_loader_thread.analyse_package", "Analyse package [file=" + filepath + "]" ) packages = self.analyse_package(filepath) if packages: ActionHistory().add_action( "javatar.core.packages_loader_thread.load_status", "Javatar package " + filename + " loaded [file=" + filepath + "]" ) default_packages.append(packages) else: ActionHistory().add_action( "javatar.core.packages_loader_thread.load_status", "Javatar package load failed [file=" + filepath + "]" ) data = { "installed_packages": self.installed_packages, "default_packages": default_packages } self.result = True if self.on_complete is not None: sublime.set_timeout(lambda: self.on_complete(data), 10)
def initialize_ProgressBar( self, view ): #▒▒▒ Text ▒▒▒# self.popUp_Label_InProgress = "PROGRESS:" self.popUp_Label_Complete = "COMPLETE!" #▒▒▒ Progress Tracking ▒▒▒# self.maxPercent = 100 self.updateFrequency = 50 # In Milliseconds #▒▒▒ Dimensions ▒▒▒# self.popupWidth = 500 self.popupMaxHeight = 500 self.progressBar_Height = 21 #▒▒▒ Colors ▒▒▒# self.progressBar_Incomplete_Color = "#0B121A" self.progressBar_Complete_Color = "#57BB80" self.progressBar_Progress_Color = "#5A91BC" self.progressBar_BorderColor = "#000000" self.popupCSS = sublime.load_resource( sublime.find_resources( "ProgressBarDemo_ProgressBar.css" )[ 0 ] ) self.progressBar_Width = int( float( self.popupWidth * 0.8 ) ) self.progressPercent = 0 mdpopups.show_popup( view, # view "", # content True, # markdown self.popupCSS, # css 0, # flags -1, # location self.popupWidth, # width self.popupMaxHeight # height )
def find_syntax_files(self): # ST3 if hasattr(sublime, 'find_resources'): for f in sublime.find_resources("*.tmLanguage"): yield f else: for root, dirs, files in os.walk(sublime.packages_path()): for f in files: if f.endswith(".tmLanguage"): langfile = os.path.relpath(os.path.join(root, f), sublime.packages_path()) # ST2 (as of build 2181) requires unix/MSYS style paths for the 'syntax' view setting yield os.path.join('Packages', langfile).replace("\\", "/")
def run(self): snippets = [] from .javatar_utils import get_path for filepath in sublime.find_resources("*.javatar"): filename = get_path("name", filepath) get_action().add_action("javatar.util.collection", "Javatar snippet " + filename + " loaded") print("Javatar snippet " + filename + " loaded") snippets.append(self.analyse_snippet(filepath)) self.result = True if self.on_complete is not None: sublime.set_timeout(lambda: self.on_complete(snippets), 10)
def remove_generated_color_schemes(plugindir): colorSchemes = sublime.find_resources('*.sublime-color-scheme') for colorScheme in colorSchemes: match = re.match( 'Packages/Semantic Highlighter/(.+\.sublime-color-scheme)', colorScheme) if match is not None: f = os.path.join(plugindir, match.group(1)) if os.path.exists(f): print("Remove color scheme", f) os.remove(f)
def determine_syntax_files(): syntax_files = sublime.find_resources("*.tmLanguage") for syntax_file in syntax_files: try: # Use `sublime.load_resource`, in case Package is `*.sublime-package`. resource = sublime.load_resource(syntax_file) plist = readPlistFromBytes(bytearray(resource, encoding="utf-8")) for extension in plist["fileTypes"]: if extension not in syntax_file_map: syntax_file_map[extension] = [] extension_list = syntax_file_map[extension] extension_list.append(syntax_file) except: continue
def get_syntax_file(syntax): # First try to find the resource using the provided string: # resources = sublime.find_resources(syntax) # If there is no match, then try with the newer .sublime-syntax # extension: # if not resources: resources = sublime.find_resources(syntax + '.sublime-syntax') # If there is still no match then try for the older .tmLanguage extension: # if not resources: resources = sublime.find_resources(syntax + '.tmLanguage') # If none of these approaches found a syntax file then throw an error, since # the user obviously wanted something: # if not resources: raise Exception('No resource found matching "%s".' % syntax) else: return resources[0]
def run(self, action): color_schemes = sublime.find_resources("gruvbox*.tmTheme") color_themes = sublime.find_resources("gruvbox*.sublime-theme") temp_schemes = [] self.themes = [] self.schemes = [] for scheme in color_schemes: if 'Packages/gruvbox/' in scheme: temp_schemes.append(scheme[17:-8]) for i in range(len(temp_schemes)): if (i % 2) == 0: self.schemes.insert(i + 1, temp_schemes[i]) else: self.schemes.insert(i - 1, temp_schemes[i]) for theme in color_themes: if 'Packages/gruvbox/' in theme: self.themes.append(theme[17:]) self.show_panel()
def run(self): self.helps = [] for spelling in README_PATTERNS: for path in sublime.find_resources(spelling): components = path.split('/') if len(components) == 3: # exclude files in package subdirs package_name, readme_name = components[-2:] self.helps.append([package_name, readme_name, path]) self.helps.sort() self.window.show_quick_panel( list(map(lambda x: [x[0], x[1]], self.helps)), self.onSelect)
def theme_path(self): """Read 'theme' setting and return path to gutter icons.""" theme = self.get('theme', 'Default.gitgutter-theme') # rebuilt path if setting changed if theme != os.path.basename(self._theme_path): if ST3: themes = sublime.find_resources(theme) self._theme_path = os.path.dirname(themes[-1]) \ if themes else self.default_theme_path else: # ST2 doesn't support find_resource so use built-in themes only theme, _ = os.path.splitext(theme) self._theme_path = '/'.join((self._builtin_theme_path, theme)) return self._theme_path
def build_syntax_menu(): """Create the syntax menu.""" tm_syntax_files = sublime.find_resources("*.tmLanguage") syntax_files = sublime.find_resources("*.sublime-syntax") tm_syntax_files = [ s for s in tm_syntax_files if s.replace(".tmLanguage", ".sublime-syntax") not in syntax_files ] syntax_files.extend(tm_syntax_files) syn_dict = collections.OrderedDict({}) for syntax_file in syntax_files: split = syntax_file.split("/") package = split[1] file = split[-1].split(".")[0] if package in syn_dict: syn_dict[package].append((file, syntax_file)) else: syn_dict[package] = [(file, syntax_file)] syntax_menu = MenuEntry("Syntax") sorted_dict = sorted(syn_dict.items(), key=lambda i: i[0].lower()) od = collections.OrderedDict(sorted_dict) for package, file_infos in od.items(): if len(file_infos) == 1: file, path = file_infos[0] entry = _create_file_entry(file, path) else: entry = MenuEntry(package) for file, path in file_infos: child = _create_file_entry(file, path) entry.children.append(child) syntax_menu.children.append(entry) return syntax_menu
def run(self, package=None, **kwargs): if not package: return window = sublime.active_window() settings = self.load_unittesting_settings(package, kwargs) stream = self.load_stream(package, settings) try: from ColorSchemeUnit.lib.runner import ColorSchemeUnit except ImportError: stream.write('ERROR: ColorSchemeUnit runner could not be imported') stream.write('\n') stream.write(DONE_MESSAGE) stream.close() return tests = sublime.find_resources("color_scheme_test*") tests = [t for t in tests if t.startswith("Packages/%s/" % package)] if not tests: stream.write("ERROR: No syntax_test files are found in %s!" % package) stream.write("\n") stream.write(DONE_MESSAGE) stream.close() return # trigger "Start reading output" stream.write("Running ColorSchemeUnit\n") stream.flush() # a trick to use `async` as an argument kwargs = { "output": stream, "package": package, "async": False } result = ColorSchemeUnit(window).run(**kwargs) if result: stream.write('\n') stream.write("OK.\n") else: stream.write('\n') stream.write("FAILED.\n") stream.write("\n") stream.write(DONE_MESSAGE) stream.close()
def get_missing(theme_package): package_icons = json.loads( sublime.load_resource("Packages/" + settings.PACKAGE_NAME + "/common/icons.json")) theme_icons_path = get_path(theme_package) if not theme_icons_path: return package_icons theme_icons = { os.path.basename(os.path.splitext(i)[0]) for i in sublime.find_resources("*.png") if i.startswith(theme_icons_path) } return [icon for icon in package_icons if icon not in theme_icons]
def _scan_help_packages(help_list=None): """ Scan for packages with a help index and load them. If a help list is provided, only the help for packages not already in the list will be loaded. """ help_list = dict() if help_list is None else help_list for index_file in sublime.find_resources("hyperhelp.json"): pkg_name = path.split(index_file)[0].split("/")[1] if pkg_name not in help_list: result = _load_help_index(index_file) if result is not None: help_list[result.package] = result return help_list
def _is_syntax_specific(self): """Check whether a syntax def with the same base file name exists. Returns: bool """ syntax_file_exts = (".sublime-syntax", ".tmLanguage") name_no_ext = os.path.splitext(self.filename)[0] for ext in syntax_file_exts: syntax_file_name = name_no_ext + ext resources = sublime.find_resources(syntax_file_name) if resources: logger.debug("syntax-specific settings file for %r", resources[0]) return True return False
def load_theme_settings(self): """ Parse the .sublime-theme file for any settings keys """ the_theme = Themr.instance().get_theme() pattern = re.compile(r'"settings":\s*\[(?:[, ]*"!?(\w+)")*\]') theme_settings = set() # Load the actual theme resource files resources = [sublime.load_resource(theme) for theme in sublime.find_resources(the_theme)] for resource in resources: for key in re.findall(pattern, resource): theme_settings.add(key) # Return a list of tuples with setting key and values return [(key, self.preferences.get(key, False)) for key in theme_settings]
def __init__(self, original_color_scheme): self._dirty = False try: self.color_scheme_string = sublime.load_resource(original_color_scheme) except IOError: # then use sublime.find_resources paths = sublime.find_resources(original_color_scheme) if not paths: raise IOError("{} cannot be found".format(original_color_scheme)) for path in paths: if path.startswith("Packages/User/"): # load user specfic theme first self.color_scheme_string = sublime.load_resource(path) break self.color_scheme_string = sublime.load_resource(paths[0])
def determine_syntax_files(): syntax_files = sublime.find_resources("*.sublime-syntax") # Temporary fix to get GitSavvy loading. return for syntax_file in syntax_files: try: # Use `sublime.load_resource`, in case Package is `*.sublime-package`. resource = sublime.load_resource(syntax_file) for extension in yaml.load(resource)["file_extensions"]: if extension not in syntax_file_map: syntax_file_map[extension] = [] extension_list = syntax_file_map[extension] extension_list.append(syntax_file) except: continue
def run(self, theme): # pylint: disable=R0201; sublime text API, no need for class reference """ Search all *.tmTheme files in the Rainmeter space and tries to match it to the theme param. If no matching theme was found an error is reported to the log and tell the user that his intended operation failed. Parameters ---------- self: EditThemeCommand the current instance given to the method. theme: String Given String through the menu. Should match one of the tmTheme in the Rainmeter space """ all_themes = sublime.find_resources("*.hidden-tmTheme") # only list rainmeter themes # could be installed via "add repository" then the file is named after the repository rm_exp = re.compile(r"Packages/Rainmeter/", re.IGNORECASE) theme_exp = re.compile(re.escape(theme)) filtered_themes = list( filter(lambda t: rm_exp.search(t) and theme_exp.search(t), all_themes)) if len(filtered_themes) != 1: stringified_all_themes = '\n'.join(map(str, all_themes)) stringified_filtered_themes = '\n'.join(map(str, filtered_themes)) message = """searched for '{theme}' in {stringified_all_themes} but resulted into more or less than 1 result with {stringified_filtered_themes}""" formatted_message = message.format( theme=theme, stringified_all_themes=stringified_all_themes, stringified_filtered_themes=stringified_filtered_themes) logger.error(formatted_message) sublime.error_message(formatted_message) # we found only one theme = filtered_themes[0] settings = sublime.load_settings("Rainmeter.sublime-settings") settings.set("color_scheme", theme) sublime.save_settings("Rainmeter.sublime-settings")
def load_schemes(self): scheme_paths = [] favorites = self.get_favorites() try: # use find_resources() first for ST3. scheme_paths = sublime.find_resources('*.tmTheme') except: # fallback to walk() for ST2 # Load the paths for schemes contained in zipped .sublime-package files. for root, dirs, files in os.walk( sublime.installed_packages_path()): for package in (package for package in files if package.endswith('.sublime-package')): zf = zipfile.ZipFile( os.path.join(sublime.installed_packages_path(), package)) for filename in (filename for filename in zf.namelist() if filename.endswith('.tmTheme')): filepath = os.path.join( root, package, filename).replace( sublime.installed_packages_path(), 'Packages').replace('.sublime-package', '').replace('\\', '/') scheme_paths.append(filepath) # Load the paths for schemes contained in folders. for root, dirs, files in os.walk(sublime.packages_path()): for filename in (filename for filename in files if filename.endswith('.tmTheme')): filepath = os.path.join(root, filename).replace( sublime.packages_path(), 'Packages').replace('\\', '/') scheme_paths.append(filepath) scheme_paths = self.filter_scheme_list(scheme_paths) # Given the paths of all the color schemes, add in the information for # the pretty-printed name and whether or not it's been favorited. schemes = [] for scheme_path in scheme_paths: scheme_name = self.filter_scheme_name(scheme_path) is_favorite = '' if scheme_path in favorites: is_favorite = u' \u2605' # Put a pretty star icon next to favorited schemes. :) schemes.append([scheme_name, scheme_path, is_favorite]) schemes.sort(key=lambda s: s[0].lower()) return schemes
def theme_path(self): """Read 'theme' setting and return path to gutter icons.""" theme = self.get('theme') if not theme: theme = 'Default.gitgutter-theme' # rebuilt path if setting changed if theme != os.path.basename(self._theme_path): if ST3: themes = sublime.find_resources(theme) self._theme_path = (os.path.dirname(themes[-1]) if themes else self._PACKAGE_THEMES + '/Default') else: # ST2 doesn't support find_resource, use built-in themes only. theme, _ = os.path.splitext(theme) self._theme_path = '/'.join((self._PACKAGE_THEMES, theme)) return self._theme_path
def on_post_save(self, view): file_path = view.file_name() if not file_path.endswith(".py"): return file_base = os.path.basename(file_path) if os.sep == "\\": file_path = file_path.replace("\\", "/") file_res = "Packages" + file_path[file_path. find("/" + settings.PACKAGE_NAME):] if file_res in sublime.find_resources(file_base): reload_plugin()
def cache_add_resources(sql, file_spec): """Load documentation from sublime-package. The tooltip text is shipped with CreateMyConfig. As not everybody may have access to this tool, its files are shipped as copy with this package, too. """ for file_name in sublime.find_resources(file_spec): lang = os.path.basename(os.path.dirname(file_name)).lower() # valid language codes have a length of 2 characters if len(lang) == 2: try: print("reloading docs", file_name) cache_add_xml(sql, xml.parseString( sublime.load_binary_resource(file_name)), lang) except Exception as err: print(" error", err)
def load_default_collections(): execution_units = {} collections = sublime.find_resources("*.terminality-collections") for collection_file in collections: collection = sublime.decode_value( sublime.load_resource(collection_file)) if "execution_units" not in collection: continue for scope in collection["execution_units"]: scope_value = collection["execution_units"][scope] if not isinstance(scope_value, dict): continue execution_units[scope] = UnitCollections.load_language_scopes( scope_value, execution_units[scope] if scope in execution_units else None) return execution_units
def get_installed(): log.message('Getting installed themes') installed_res = sublime.find_resources(THEMES) installed_themes = {} for ires in installed_res: installed_themes.setdefault(os.path.basename(os.path.dirname(ires)), []).append(os.path.basename(ires)) if PATCHES in installed_themes: del installed_themes[PATCHES] log.value(installed_themes) return installed_themes
def get_customizable(installed_themes): log("Getting the list of theme packages with customization support") customizable_themes = [] theme_res = sublime.find_resources(".supports-a-file-icon-customization") for res in theme_res: pkg = re.sub(PATTERN, "", res) if pkg in installed_themes: customizable_themes.append(pkg) dump(customizable_themes) return customizable_themes
def run(self, piano_layout=None): if piano_layout: self.item_chosen(piano_layout) return items = [path.splitext(path.basename(file_path))[0] for file_path in sublime.find_resources('*.piano_layout')] try: pre_select_index = items.index(piano_prefs('layout')) except ValueError: pre_select_index = 0 if len(items) == 0: sublime.message_dialog('no piano layouts found') else: # TODO: should we preview the layout on select? self.window.show_quick_panel(items, lambda index: self.item_chosen(items[index] if index > -1 else None), flags=0, selected_index=pre_select_index)
def read_gutter_theme(): global COLORIZE COLORIZE = True theme_path = persist.settings.get('gutter_theme') theme_file = os.path.basename(theme_path) if not theme_file.endswith(".gutter-theme"): theme_file += ".gutter-theme" theme_files = sublime.find_resources(theme_file) if theme_files: theme_file = theme_files[0] opts = util.load_json(theme_file) if opts: COLORIZE = opts.get("colorize", True)
def syntax_testing(self, stream, package): try: syntaxes = sublime.find_resources("*.sublime-syntax") if package != "__all__": syntaxes = [ s for s in syntaxes if s.startswith("Packages/%s/" % package) ] # remove UnitTesting syntax_tests syntaxes = [ s for s in syntaxes if not s.startswith("Packages/UnitTesting/") ] if not syntaxes: raise RuntimeError("No sublime-syntax files found in %s!" % package) total_errors = 0 total_failed_syntaxes = 0 for syntax in syntaxes: results = sublime_api.incompatible_syntax_patterns(syntax) for location, _, message in results: stream.write("%s:%d:%d: %s\n" % (syntax, location[0] + 1, location[0] + location[1], message)) if results: total_errors += len(results) total_failed_syntaxes += 1 if total_errors: stream.write( "FAILED: %d errors in %d of %d syntaxes\n" % (total_errors, total_failed_syntaxes, len(syntaxes))) else: stream.write("Success: %d syntaxes passed\n" % (len(syntaxes), )) stream.write("OK\n") except Exception as e: if not stream.closed: stream.write("ERROR: %s\n" % e) stream.write("\n") stream.write(DONE_MESSAGE) stream.close()
def get_package_modules(package_names): package_names = set(package_names) package_path_bases = [ p for pkg_name in package_names for p in ( os.path.join(sublime.installed_packages_path(), pkg_name + '.sublime-package'), os.path.join(sublime.packages_path(), pkg_name), ) ] def module_paths(module): try: yield module.__file__ except AttributeError: pass try: yield from module.__path__ except AttributeError: pass @functools.lru_cache(1024) def _package_python_matched(package): return package_python_matched(package) for module in sys.modules.values(): try: base, path = next( (base, path) for path in module_paths(module) for base in package_path_bases if path and (path == base or path.startswith(base + os.sep))) except StopIteration: continue else: pkg_name = module.__name__.split(".")[0] is_plugin = (os.path.dirname(path) == base) and _package_python_matched(pkg_name) yield module.__name__, is_plugin # get all the top level plugins in case they were removed from sys.modules for path in sublime.find_resources("*.py"): for pkg_name in package_names: if not _package_python_matched(pkg_name): continue if posixpath.dirname(path) == 'Packages/' + pkg_name: yield pkg_name + '.' + posixpath.basename( posixpath.splitext(path)[0]), True
def run(self): color_scheme = sublime.ui_info().get('color_scheme', {}).get('resolved_value') if color_scheme is None: color_scheme = DEFAULT_CS if '/' not in color_scheme: possible_paths = sublime.find_resources(color_scheme) default_path = 'Packages/Color Scheme - Default/' + color_scheme if default_path in possible_paths or len(possible_paths) == 0: color_scheme = default_path else: color_scheme = possible_paths[0] # Ensure we always create overrides with the .sublime-color-scheme ext user_package_path = os.path.join(sublime.packages_path(), 'User') color_scheme_file_name = os.path.basename(color_scheme) base_name, ext = os.path.splitext(color_scheme_file_name) if ext in {'.tmTheme', '.hidden-tmTheme', '.hidden-color-scheme'}: color_scheme_file_name = base_name + '.sublime-color-scheme' user_file = os.path.join(user_package_path, color_scheme_file_name) # edit_settings only works with ${packages}-based paths if color_scheme.startswith('Packages/'): color_scheme = '${packages}' + color_scheme[8:] self.window.run_command( 'edit_settings', { "base_file": color_scheme, 'user_file': user_file, "default": "// Documentation at https://www.sublimetext.com/docs/color_schemes.html\n" "{\n" "\t\"variables\":\n" "\t{\n" "\t},\n" "\t\"globals\":\n" "\t{\n" "\t},\n" "\t\"rules\":\n" "\t[\n" "\t\t$0\n" "\t]\n" "}\n" })
def is_topic_file_valid(pkg_info, topic_dict): """ Given a topic dictionary such as returned by lookup_help_topic() that represents a package file, return an indication as to whether that file exists or not as a package resource. None is returned if a topic does not represent a package file. """ if is_topic_file(pkg_info, topic_dict): file = topic_dict["file"] base = os.path.split(file)[1] if file not in sublime.find_resources(base): return False return True return None