def update_binary(): pkgpath = os.path.join(sublime.installed_packages_path(), 'InputHelper.sublime-package') srcdir = os.path.join(sublime.packages_path(), 'InputHelper', 'lib') srcpath = os.path.join(srcdir, binname) srcdb = os.path.join(srcdir, dbname) bindir = os.path.join(sublime.packages_path(), usrbin) binpath = os.path.join(bindir, binname) bindb = os.path.join(bindir, dbname) resdir = 'Packages/InputHelper/lib/' resbin = resdir + binname resdb = resdir + dbname bininfo = None bindata = None dbdata = None if os.path.exists(binpath): bininfo = os.stat(binpath) elif not os.path.exists(bindir): os.makedirs(bindir, 0o755) if not os.path.exists(bindb): if os.path.exists(srcdb): with open(srcdb, 'rb') as srcfile: dbdata = srcfile.read() srcfile.close elif st_version == 3 and os.path.exists(pkgpath): dbdata = sublime.load_binary_resource(resdb) if dbdata != None: print("* Creating " + bindb) with open(bindb, 'wb') as dbfile: dbfile.write(dbdata) dbfile.close() if os.path.exists(srcpath): srcinfo = os.stat(srcpath) if bininfo == None or bininfo[ST_MTIME] < srcinfo[ST_MTIME]: with open(srcpath, 'rb') as srcfile: bindata = srcfile.read() srcfile.close() elif st_version == 3 and os.path.exists(pkgpath): pkginfo = os.stat(pkgpath) if bininfo == None or bininfo[ST_MTIME] < pkginfo[ST_MTIME]: bindata = sublime.load_binary_resource(resbin) if bindata != None: print("* Updating " + binpath) with open(binpath, 'wb') as binfile: binfile.write(bindata) binfile.close() if not os.access(binpath, os.X_OK): os.chmod(binpath, 0o755)
def set_view(self, src, lang, plugin_map): """Setup view for conversion.""" if plugin_map is None: plugin_map = {} # Get the output panel self.view = sublime.active_window().create_output_panel('mdpopups', unlisted=True) # Let all plugins no to leave this view alone self.view.settings().set('is_widget', True) # Don't translate anything. self.view.settings().set("translate_tabs_to_spaces", False) # Don't mess with my indenting Sublime! self.view.settings().set("auto_indent", False) # Insert into the view self.view.run_command('insert', {'characters': src}) # Setup the proper syntax lang = lang.lower() user_map = sublime.load_settings('Preferences.sublime-settings').get( 'mdpopups.sublime_user_lang_map', {}) keys = set( user_map.keys()) | (set(plugin_map.keys()) | set(lang_map.keys())) loaded = False for key in keys: v = lang_map.get(key, (tuple(), tuple())) plugin_v = plugin_map.get(key, (tuple(), tuple())) user_v = user_map.get(key, (tuple(), tuple())) if lang in (tuple(user_v[0]) + plugin_v[0] + v[0]): for l in (tuple(user_v[1]) + plugin_v[1] + v[1]): for ext in ST_LANGUAGES: sytnax_file = 'Packages/{}{}'.format(l, ext) try: sublime.load_binary_resource(sytnax_file) except Exception: continue self.view.set_syntax_file(sytnax_file) loaded = True break if loaded: break if loaded: break if not loaded: # Default to plain text for ext in ST_LANGUAGES: # Just in case text one day switches to 'sublime-syntax' sytnax_file = 'Packages/Text/Plain text{}'.format(ext) try: sublime.load_binary_resource(sytnax_file) except Exception: continue self.view.set_syntax_file(sytnax_file)
def _get_icon(): icon = str() if settings.get("comment_icon_enabled", False): icon = settings.get("comment_icon", "dots") try: icon = "%s/%s.png" % (icon_path, icon) sublime.load_binary_resource(icon) except OSError as ex: log.debug("[Colored Comments]: {} - {}".format( _get_icon.__name__, ex)) icon = str() pass return icon
def load_completions(self, view): scope_name = view.scope_name( view.sel()[0].begin()) # sublime.windows()[0].active_view() if self.should_trigger(scope_name): if not self.settings: self.settings = sublime.load_settings( 'Preferences.sublime-settings') encoding = sublime.load_settings( 'DictionaryAutoComplete.sublime-settings').get('encoding') if ST3: words = sublime.load_binary_resource( self.settings.get('dictionary')).decode( encoding).splitlines() for word in words: word = word.split('/')[0].split('\t')[0] self.word_list.append(word) elif not ST3: self.dict_path = os.path.join( sublime.packages_path()[:-9], self.settings.get('dictionary')) with open(self.dict_path, 'r') as dictionary: words = dictionary.read().decode(encoding).splitlines() for word in words: word = word.split('/')[0].split('\t')[0] self.word_list.append(word) self.b_first_edit = False else: self.b_fully_loaded = True
def __init__(self, scheme_file, color_filter=None): """Initialize.""" if color_filter is None: color_filter = self.filter self.legacy = not scheme_file.lower().endswith('.sublime-color-scheme') self.color_scheme = path.normpath(scheme_file) self.scheme_file = path.basename(self.color_scheme) if self.legacy: self.scheme_obj = color_filter( readPlistFromBytes( re.sub( br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'', sublime.load_binary_resource(sublime_format_path(self.color_scheme)) ) ) ) else: sublime.decode_value( sublime.load_resource(sublime_format_path(self.color_scheme)), preserve_lines=True ) self.scheme_file = scheme_file self.matched = {} self.variables = {} self.parse_scheme()
def on_activated_async(self, view): if view.is_scratch() or view.settings().get('is_widget'): return targetpath = os.path.join( sublime.packages_path(), 'User', 'R-Box', 'Main.sublime-menu') targetdir = os.path.dirname(targetpath) if self.should_show_menu(view): if not os.path.exists(targetdir): os.makedirs(targetdir, 0o755) if not os.path.exists(targetpath): data = sublime.load_binary_resource( "Packages/R-Box/support/R-Box.sublime-menu").decode("utf-8") if not self.send_repl_installed() and self.send_text_plus_installed(): # fall back to send_text_plus data = data.replace("send_repl", "send_text_plus") with open(targetpath, 'w') as binfile: binfile.write(data) binfile.close() else: if os.path.exists(targetpath): os.remove(targetpath)
def update_resources(binname): # from https://github.com/weslly/ColorPicker/blob/master/sublimecp.py targetdir = os.path.join(sublime.packages_path(), 'User', 'R-Box', 'bin') targetpath = os.path.join(targetdir, binname) respath = 'Packages/R-Box/bin/' + binname pkgpath = os.path.join(sublime.installed_packages_path(), 'R-Box.sublime-package') unpkgpath = os.path.join(sublime.packages_path(), 'R-Box', 'bin', binname) if os.path.exists(targetpath): targetinfo = os.stat(targetpath) else: if not os.path.exists(targetdir): os.makedirs(targetdir, 0o755) targetinfo = None if os.path.exists(unpkgpath): pkginfo = os.stat(unpkgpath) elif os.path.exists(pkgpath): pkginfo = os.stat(pkgpath) else: return if targetinfo is None or targetinfo.st_mtime < pkginfo.st_mtime: print("* Updating " + targetpath) if sublime.version() < '3000': shutil.copy2(unpkgpath, targetpath) else: data = sublime.load_binary_resource(respath) with open(targetpath, 'wb') as binfile: binfile.write(data) binfile.close() if not os.access(targetpath, os.X_OK): os.chmod(targetpath, 0o755)
def run(self): # Wait for _corona_utils initialization to complete # print("Waiting for InitializedEvent...") _corona_utils.InitializedEvent.wait() self._snippets_dir = os.path.join(_corona_utils.PACKAGE_USER_DIR, "Snippets") if not os.path.exists(self._snippets_dir): os.makedirs(self._snippets_dir) print(_corona_utils.PACKAGE_NAME + ": Extracting snippets ...") try: # In ST3 our ZIP file is not on the filesystem, it's in our package so we have to extract # it and unzip from there (to work on Windows the temp file must be closed before it can # be reopened to be unzipped) zip_bytes = sublime.load_binary_resource(_corona_utils.ST_PACKAGE_PATH + "snippets.zip") with tempfile.NamedTemporaryFile(suffix = ".zip", delete=False) as tempzip: tempzip.write(zip_bytes) tempzip.close() UnZIPToDir(tempzip.name, self._snippets_dir) os.remove(tempzip.name) except: # We're on ST2 and the ZIP file is just a file in our package directory UnZIPToDir(os.path.join(_corona_utils.PACKAGE_DIR, "snippets.zip"), self._snippets_dir) snippetMenuArray = [] snippetJSON = "" if os.path.isdir(self._snippets_dir): snippetMenuArray = self.addDirectory(self._snippets_dir) snippetJSON = json.dumps(snippetMenuArray, indent=4, separators=(',', ': ')) if snippetJSON == "": print(_corona_utils.PACKAGE_NAME + ": Failed to build Snippets menu") return # Put our menu into the Main.sublime-menu.template file menus = "" if _corona_utils.SUBLIME_VERSION < 3000: with open(os.path.join(_corona_utils.PACKAGE_DIR, "Main.sublime-menu.template"), "r") as fd: menus = fd.read() else: menus = sublime.load_resource(_corona_utils.ST_PACKAGE_PATH + "Main.sublime-menu.template") if menus == "": print(_corona_utils.PACKAGE_NAME + ": Failed to create Snippets menu") return menus = menus.replace("$corona_snippets", snippetJSON) if not os.path.exists(_corona_utils.PACKAGE_DIR): os.makedirs(_corona_utils.PACKAGE_DIR) if _corona_utils.SUBLIME_VERSION < 3000: with open(os.path.join(_corona_utils.PACKAGE_DIR, "Main.sublime-menu"), "w") as fd: fd.write("// Generated file - do not edit - modify 'Main.sublime-menu.template' instead\n") fd.write(menus) else: # ST3/P3 with open(os.path.join(_corona_utils.PACKAGE_DIR, "Main.sublime-menu"), "w", encoding='utf-8') as fd: fd.write("// Generated file - do not edit - modify 'Main.sublime-menu.template' instead\n") fd.write(menus)
def load_color_scheme(self, scheme): is_json = bool() try: if scheme in sublime_default_cs: scheme = "{}{}".format("Packages/Color Scheme - Default/", scheme) scheme_content = sublime.load_binary_resource(scheme) except Exception as ex: sublime.error_message(" ".join([ "An error occured while reading color", "scheme file. Please check the console", "for details.", ])) self.log.debug("[Colored Comments]: {} - {}".format( self.load_color_scheme.__name__, ex)) raise if scheme.endswith(".sublime-color-scheme"): is_json = True updates, color_scheme = self._add_colors_to_scheme( sublime.decode_value(scheme_content.decode("utf-8")), is_json) elif scheme.endswith(".tmTheme"): updates, color_scheme = self._add_colors_to_scheme( plistlib.loads(bytes(scheme_content)), is_json) else: sys.exit(1) return updates, color_scheme, is_json
def cached_resource(res, alias=None): #res = 'Packages/Plugin Debugger/start_sublime_winpdb.py' log("cached_resource: %s => %s", res, alias) if alias is None: alias = os.path.basename(res) log("cached_resource: %s => %s", res, alias) cache_dir = os.path.join(sublime.cache_path(), 'Plugin Debugger') if not os.path.exists(cache_dir): os.makedirs(cache_dir) fn = os.path.join(cache_dir, alias) log("cached name: %s", fn) if not os.path.exists(fn): log("create cached file: %s\n" % fn) data = sublime.load_binary_resource(res) with open(fn, 'wb') as fh: fh.write(data) log("cache done: %s", fn) return fn
def update_resources(*target): targetpath = os.path.join(sublime.packages_path(), 'User', PKGNAME, *target) targetdir = os.path.dirname(targetpath) respath = 'Packages/%s/' % PKGNAME + "/".join(target) pkgpath = os.path.join(sublime.installed_packages_path(), '%s.sublime-package' % PKGNAME) unpkgpath = os.path.join(sublime.packages_path(), PKGNAME, *target) if os.path.exists(targetpath): targetinfo = os.stat(targetpath) else: if not os.path.exists(targetdir): os.makedirs(targetdir, 0o755) targetinfo = None if os.path.exists(unpkgpath): pkginfo = os.stat(unpkgpath) elif os.path.exists(pkgpath): pkginfo = os.stat(pkgpath) else: return if targetinfo is None or targetinfo.st_mtime < pkginfo.st_mtime: print("* Updating " + targetpath) if sublime.version() < '3000': shutil.copy2(unpkgpath, targetpath) else: data = sublime.load_binary_resource(respath) with open(targetpath, 'wb') as f: f.write(data) f.close() if not os.access(targetpath, os.X_OK): os.chmod(targetpath, 0o755)
def parse_scheme(self): HaxeColorScheme.styles = None HaxeColorScheme.color_map = None color_scheme = self.settings.get('color_scheme') try: if int(sublime.version()) >= 3000: b = sublime.load_binary_resource(color_scheme) pl = readPlistFromBytes(b) else: pl = readPlist(os.path.join(os.path.abspath( sublime.packages_path() + '/..'), color_scheme)) except: return def safe_update(fr, to): for k in fr.keys(): if k not in to: to[k] = fr[k] dct = {} for d in pl.settings: if 'settings' not in d: continue s = d['settings'] if 'scope' not in d: safe_update(s, dct) else: scope = d['scope'] scopes = [sc.strip() for sc in scope.split(',')] if 'text' in scopes or 'source' in scopes: dct.update(d.settings) HaxeColorScheme.color_map = dct
def __init__(self, scheme_file, color_filter=None): """Initialize.""" if color_filter is None: color_filter = self.filter self.color_scheme = path.normpath(scheme_file) self.scheme_file = path.basename(self.color_scheme) if NEW_SCHEMES and scheme_file.endswith('.sublime-color-scheme'): self.legacy = False self.scheme_obj = { 'variables': {}, GLOBAL_OPTIONS: {}, 'rules': [] } else: content = sublime.load_binary_resource( sublime_format_path(self.color_scheme)) self.legacy = True self.convert_format( readPlistFromBytes(XML_COMMENT_RE.sub(b'', content))) self.overrides = [] if NEW_SCHEMES: self.merge_overrides() self.scheme_obj = color_filter(self.scheme_obj) self.scheme_file = scheme_file self.matched = {} self.variables = {} self.parse_scheme()
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 __init__(self, scheme_file, color_filter=None): """Initialize.""" if color_filter is None: color_filter = self.filter self.color_scheme = path.normpath(scheme_file) self.scheme_file = path.basename(self.color_scheme) content = sublime.load_binary_resource( sublime_format_path(self.color_scheme)) if scheme_file.lower().endswith( ('.tmtheme', '.hidden-tmtheme')) or IS_XML_RE.match(content) is not None: self.legacy = True self.convert_format( readPlistFromBytes(XML_COMMENT_RE.sub(b'', content))) else: self.legacy = False self.scheme_obj = sublime.decode_value(content.decode('utf-8')) if 'variables' not in self.scheme_obj: self.scheme_obj['variables'] = {} if GLOBAL_OPTIONS not in self.scheme_obj: self.scheme_obj[GLOBAL_OPTIONS] = {} if 'rules' not in self.scheme_obj: self.scheme_obj['rules'] = [] self.overrides = [] if NEW_SCHEMES: self.merge_overrides() self.scheme_obj = color_filter(self.scheme_obj) self.scheme_file = scheme_file self.matched = {} self.variables = {} self.parse_scheme()
def update_binary(): bindir = os.path.join(sublime.packages_path(), usrbin) binpath = os.path.join(bindir, binname) pkgpath = os.path.join(sublime.installed_packages_path(), 'ColorPicker.sublime-package') respath = 'Packages/ColorPicker/lib/' + binname libdir = os.path.join(sublime.packages_path(), 'ColorPicker', 'lib') libpath = os.path.join(libdir, binname) bininfo = None bindata = None if os.path.exists(binpath): bininfo = os.stat(binpath) elif not os.path.exists(bindir): os.makedirs(bindir, 0o755) if os.path.exists(libpath): libinfo = os.stat(libpath) if bininfo == None or bininfo[ST_MTIME] < libinfo[ST_MTIME]: with open(libpath, 'rb') as libfile: bindata = libfile.read() libfile.close() elif sublime_version == 3 and os.path.exists(pkgpath): pkginfo = os.stat(pkgpath) if bininfo == None or bininfo[ST_MTIME] < pkginfo[ST_MTIME]: bindata = sublime.load_binary_resource(respath) if bindata != None: print("* Updating " + binpath) with open(binpath, 'wb') as binfile: binfile.write(bindata) binfile.close() if not os.access(binpath, os.X_OK): os.chmod(binpath, 0o755)
def load_binary_resource(name): if ST3: return sublime.load_binary_resource("Packages/Character Table/"+name) else: fn = os.path.join(sublime.packages_path(), 'Character Table', name) with open(fn, "rb") as f: return f.read()
def plugin_loaded(): """Called automatically from ST3 if plugin is loaded. Is required now due to async call and ignoring sublime.* from main routine """ packages = sublime.packages_path() colorpicker_dir = os.path.join(packages, "User", "Rainmeter", "color", "picker") __require_path(colorpicker_dir) colorpicker_exe = os.path.join(colorpicker_dir, "ColorPicker_win.exe") # could be already copied on a previous run need_picker_exe = not os.path.exists(colorpicker_exe) binary_picker = sublime.load_binary_resource( "Packages/Rainmeter/color/picker/ColorPicker_win.exe" ) # could be a newer version of the color picker be there # only check if no newer is required since expensive # generally happens in consecutive calls without updates if not need_picker_exe: need_picker_exe = os.path.getsize(colorpicker_exe) != len(binary_picker) if need_picker_exe: logger.info( "Newer version of color picker found. Copying data over to '" + colorpicker_exe + "'" ) with open(colorpicker_exe, "wb") as file_handler: file_handler.write(binary_picker) else: logger.info( "You are using the most current version of color picker. Continue loading..." )
def startup(self): """ Check and extract helper files @param on_done: callback after loaded """ helpers = sublime.find_resources("JavatarAutocompleteHelper.jar") installed = False for helper in helpers: if helper[:9] == "Packages/": helper = os.path.join(sublime.packages_path(), helper[9:]) if os.path.exists(helper) and self.verify_helper(helper): installed = True break if not installed: Logger().info("Updating helper files...") file_path = os.path.join(sublime.packages_path(), "User", "Javatar", "Helper", "JavatarAutocompleteHelper.jar") if os.path.exists(file_path): os.remove(file_path) if not os.path.isdir(os.path.dirname(file_path)): try: os.makedirs(os.path.dirname(file_path)) except: pass helper_file = open(file_path, "wb") helper_file.write( sublime.load_binary_resource( "Packages/Javatar/binary/JavatarAutocompleteHelper.jar")) helper_file.close()
def toggle_digraph(view, set_state=True): dir = sublime.packages_path() user_digraph_path = os.path.join(dir, 'User', 'Character Table', 'Digraph') extreme_digraph = os.path.join(user_digraph_path, 'Default.sublime-keymap') global ALL_DIGRAPH if os.path.exists(extreme_digraph): os.remove(extreme_digraph) os.rmdir(user_digraph_path) if set_state: ALL_DIGRAPH = False elif ST3: s = sublime.load_binary_resource('Packages/Character Table/Extreme-Keymap.json') if not os.path.exists(user_digraph_path): os.makedirs(user_digraph_path) with open(extreme_digraph, 'wb') as f: f.write(s) if set_state: ALL_DIGRAPH = True else: create_mnemonic_keymap(user_digraph_path, keys=[]) if set_state: ALL_DIGRAPH = True if set_state: digraph_set_status(view)
def edit_plist_color_scheme(original_color_scheme): scheme_data = plistlib.readPlistFromBytes(sublime.load_binary_resource(original_color_scheme)) if os.path.exists(sublime.packages_path() + "/MCC/ModifiedColorSchemes/" + scheme_data["name"] + ".tmTheme"): sublime.load_settings("Preferences.sublime-settings").set("color_scheme", "Packages/MCC/ModifiedColorSchemes/" + scheme_data["name"] + ".tmTheme") sublime.save_settings("Preferences.sublime-settings") return elif scheme_data["name"].find("(MCC)") > -1: return try: new_background_rgb = "#000000" if "background" in scheme_data["settings"][0]["settings"]: new_background_rgb = ColorSchemeEditor.change_color_by_one(scheme_data["settings"][0]["settings"]["background"]) scheme_data = ColorSchemeEditor.add_mcc_scopes(scheme_data, False, new_background_rgb) if not os.path.exists(sublime.packages_path() + "/MCC/ModifiedColorSchemes/"): os.makedirs(sublime.packages_path() + "/MCC/ModifiedColorSchemes/") new_file_name = "/MCC/ModifiedColorSchemes/" + scheme_data["name"] + ".tmTheme" scheme_data["name"] = scheme_data["name"] + " (MCC)" plistlib.writePlist(scheme_data, sublime.packages_path() + new_file_name) sublime.load_settings("Preferences.sublime-settings").set("color_scheme", "Packages" + new_file_name) sublime.save_settings("Preferences.sublime-settings") except Exception as e: # sublime.error_message("MCC couldn't convert your current color scheme") print("Error on tmTheme conversion") print(e) sublime.active_window().run_command("show_panel", {"panel": "console", "toggle": True})
def patch(): smp = os.path.join(sublime.installed_packages_path(), PLUGIN_NAME) path = smp + '.sublime-package' if not os.path.isfile(path): print('File does not exist: %s' % path) return None linsp = SM3.core.linsp verifyu = linsp.VERIFYU if URL_NEW == linsp.b64d(verifyu): print('File already patched.') return None verifyn = linsp.b64e(linsp.b64d(verifyu).replace(URL_OLD, URL_NEW)) bytes_a = verifyu.encode('utf-8') bytes_b = verifyn.encode('utf-8') if bytes_a != bytes_b and len(bytes_a) == len(bytes_b): src = 'Packages/' + PLUGIN_NAME + '/core/linsp.pyc' bytes_old = sublime.load_binary_resource(src) bytes_new = bytes_old.replace(bytes_a, bytes_b) if bytes_old != bytes_new: unpack(smp, smp) with open(os.path.join(smp, 'core', 'linsp.pyc'), 'wb') as fhr: fhr.write(bytes_new) pack(smp, smp) shutil.rmtree(smp, ignore_errors=True) return True print('File already patched.') print('File has been raped by chuck borys.') return None
def redo(self): """Redo last reverted change.""" self._setup(noedit=True) if self.theme_valid: plist = re.sub( br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'', sublime.load_binary_resource(self.scheme_map["original"])) redo = self.scheme_map["redo"].split(";") if len(redo) == 0 or (len(redo) == 1 and redo[0] == ""): log("Nothing to redo!", status=True) return undo = self.scheme_map["undo"].split(";") undo.append(redo.pop()) self.scheme_map["redo"] = ";".join(redo) self.scheme_map["undo"] = ";".join(undo) self.plist_file = ColorSchemeTweaker().tweak( readPlistFromBytes(plist), self.scheme_map["undo"]) with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: log("Theme has not been tweaked!", status=True)
def __init__(self, scheme_file, strip_trans=False, ignore_gutter=False, track_dark_background=False, filter=None): if filter is None: filter = self.filter self.color_scheme = path.normpath(scheme_file) self.scheme_file = path.basename(self.color_scheme) if ST3: self.plist_file = filter( readPlistFromBytes( sublime.load_binary_resource( sublime_format_path(self.color_scheme)))) else: self.plist_file = filter( readPlist(sublime.packages_path() + self.color_scheme.replace('Packages', ''))) self.scheme_file = scheme_file self.strip_trans = strip_trans self.ignore_gutter = ignore_gutter self.track_dark_background = track_dark_background self.dark_lumens = None self.matched = {} self.parse_scheme()
def plugin_loaded(): global full_data_path, full_icons_path, full_themes_path full_data_path = os.path.join(sublime.packages_path()[:-len("Packages")], os.path.normpath(data_path)) full_icons_path = os.path.join(full_data_path, "icons") full_themes_path = os.path.join(full_data_path, "themes") # Create folders if not os.path.exists(full_data_path): os.mkdir(full_data_path) if not os.path.exists(full_icons_path): os.mkdir(full_icons_path) if not os.path.exists(full_themes_path): os.mkdir(full_themes_path) # Copy binary binary = "ColorPicker_" + get_ext() chflags = stat.S_IXUSR|stat.S_IXGRP|stat.S_IRUSR|stat.S_IRUSR|stat.S_IWUSR|stat.S_IWGRP fpath = os.path.join(full_data_path, binary) if get_version() >= 3000: if not os.path.exists(fpath): data = sublime.load_binary_resource('/'.join(["Packages", "Color Highlighter", "ColorPicker", binary])) if len(data) != 0: write_bin_file(fpath, data) os.chmod(fpath, chflags) else: if not os.path.exists(fpath): shutil.copy(os.path.join(sublime.packages_path(), "Color Highlighter", "ColorPicker", binary), fpath) os.chmod(fpath, chflags) # restore themes restore_broken_schemes()
def startup(self): """ Check and extract helper files @param on_done: callback after loaded """ helpers = sublime.find_resources("JavatarAutocompleteHelper.jar") installed = False for helper in helpers: if helper[:9] == "Packages/": helper = os.path.join(sublime.packages_path(), helper[9:]) if os.path.exists(helper) and self.verify_helper(helper): installed = True break if not installed: Logger().info("Updating helper files...") file_path = os.path.join( sublime.packages_path(), "User", "Javatar", "Helper", "JavatarAutocompleteHelper.jar" ) if os.path.exists(file_path): os.remove(file_path) if not os.path.isdir(os.path.dirname(file_path)): try: os.makedirs(os.path.dirname(file_path)) except: pass helper_file = open(file_path, "wb") helper_file.write(sublime.load_binary_resource( "Packages/Javatar/binary/JavatarAutocompleteHelper.jar" )) helper_file.close()
def update_resource(binname): # from https://github.com/weslly/ColorPicker/blob/master/sublimecp.py= targetdir = os.path.join(sublime.packages_path(), 'User', 'R-Box', 'bin') targetpath = os.path.join(targetdir, binname) respath = 'Packages/R-Box/bin/' + binname pkgpath = os.path.join(sublime.installed_packages_path(), 'R-Box.sublime-package') unpkgpath = os.path.join(sublime.packages_path(), 'R-Box', 'bin', binname) if os.path.exists(targetpath): targetinfo = os.stat(targetpath) else: if not os.path.exists(targetdir): os.makedirs(targetdir, 0o755) targetinfo = None if os.path.exists(unpkgpath): pkginfo = os.stat(unpkgpath) elif os.path.exists(pkgpath): pkginfo = os.stat(pkgpath) else: return if targetinfo == None or targetinfo.st_mtime < pkginfo.st_mtime: data = sublime.load_binary_resource(respath) print("* Updating " + targetpath) with open(targetpath, 'wb') as binfile: binfile.write(data) binfile.close() if not os.access(targetpath, os.X_OK): os.chmod(targetpath, 0o755)
def __init__(self, source): if type(source) is str: #self.by = pkgutil.get_data(__package__, "_dictionaries/" + source) path = sublime.find_resources(source)[0] self.by = sublime.load_binary_resource(path) if not self.by: raise OSError("# Error. File not found or not loadable: " + source) if source.endswith(".bdic"): self._initBinary() elif source.endswith(".json"): self._initJSON( json.loads(self.by.decode("utf-8")) ) #json.loads(self.by) # In Python 3.6, can read directly binary strings else: raise OSError("# Error. Unknown file type: " + source) else: self._initJSON(source) self.sFileName = source if type(source) is str else "[None]" self._arcMask = (2**((self.nBytesArc * 8) - 3)) - 1 self._finalNodeMask = 1 << ((self.nBytesArc * 8) - 1) self._lastArcMask = 1 << ((self.nBytesArc * 8) - 2) self._addrBitMask = 1 << ((self.nBytesArc * 8) - 3) # version 2 # function to decode the affix/suffix code if self.cStemming == "S": self.funcStemming = st.changeWordWithSuffixCode elif self.cStemming == "A": self.funcStemming = st.changeWordWithAffixCode else: self.funcStemming = st.noStemming # Configuring DAWG functions according to nCompressionMethod if self.nCompressionMethod == 1: self.morph = self._morph1 self.stem = self._stem1 self._lookupArcNode = self._lookupArcNode1 self._getArcs = self._getArcs1 self._writeNodes = self._writeNodes1 elif self.nCompressionMethod == 2: self.morph = self._morph2 self.stem = self._stem2 self._lookupArcNode = self._lookupArcNode2 self._getArcs = self._getArcs2 self._writeNodes = self._writeNodes2 elif self.nCompressionMethod == 3: self.morph = self._morph3 self.stem = self._stem3 self._lookupArcNode = self._lookupArcNode3 self._getArcs = self._getArcs3 self._writeNodes = self._writeNodes3 else: raise ValueError(" # Error: unknown code: {}".format( self.nCompressionMethod)) self.bOptNumSigle = False self.bOptNumAtLast = False
def set_language(lang): if not lang: return PACKAGES_PATH = sublime.packages_path() DEFAULT_PATH = os.path.join(PACKAGES_PATH, "Default") SYN_PATH = os.path.join(DEFAULT_PATH, "Syntax.sublime-menu") if os.path.isfile(SYN_PATH): with open(SYN_PATH, "rb") as f: syntax = f.read() m = md5() m.update(syntax) if m.hexdigest() == LANGS[lang]['syntax_md5sum']: sublime.status_message("%s has loaded." % lang) return # mkdir if Default not exist if not os.path.isdir(DEFAULT_PATH): os.mkdir(DEFAULT_PATH) # Load binary resource PACKAGE_NAME = os.path.basename(os.path.dirname(__file__)).split('.')[0] LOCALZIP_RES = "Packages/{}/{}".format(PACKAGE_NAME, LANGS[lang]['zipfile']) lang_bytes = sublime.load_binary_resource(LOCALZIP_RES) # write to tempfile and unzip it. import zipfile from tempfile import NamedTemporaryFile tmp_file = NamedTemporaryFile(delete=False) tmp_file.write(lang_bytes) tmp_file.close() with zipfile.ZipFile(tmp_file.name, "r") as f: f.extractall(DEFAULT_PATH) tmp_file.close() os.unlink(tmp_file.name)
def load_resource(res_name): """ Attempt to load and decode the UTF-8 encoded string with normalized line endings, returning the string on success or None on error. If no resource can be found with the resource specification provided, the call tries to load a file by this name from the packages folder instead. """ try: text = sublime.load_binary_resource(res_name).decode("utf-8") return text.replace('\r\n', '\n').replace('\r', '\n') except OSError: pass except UnicodeError: return log("Unable to decode '%s'; resource is not UTF-8" % res_name) try: spp = os.path.split(sublime.packages_path())[0] file_name = os.path.join(spp, res_name) with codecs.open(file_name, 'r', 'utf-8') as file: return file.read().replace('\r\n', '\n').replace('\r', '\n') except OSError: return log("Unable to load '%s'; resource not found" % res_name) except UnicodeError: return log("Unable to decode '%s'; resource is not UTF-8" % res_name)
def get_image_info(img_name: str) -> ImageDict: """ @brief Get image informations of an image from plugin settings. @param img_name The image name @return The image information. """ img_path = get_image_path(img_name) img_ext = os.path.splitext(img_path)[1] img_mime = "image/png" assert img_ext.lower() == ".png" try: img_bytes = sublime.load_binary_resource(img_path) except IOError: img_bytes = b"" log("error", f"Resource not found: {img_path}") img_base64 = base64.b64encode(img_bytes).decode() img_w, img_h = imagesize.get_from_bytes(img_bytes) return { "base64": img_base64, "bytes": img_bytes, "ext": img_ext, "mime": img_mime, "path": img_path, "ratio_wh": img_w / img_h, "size": (img_w, img_h), }
def on_activated_async(self, view): if view.is_scratch() or view.settings().get('is_widget'): return targetpath = os.path.join(sublime.packages_path(), 'User', 'R-Box', 'Main.sublime-menu') targetdir = os.path.dirname(targetpath) if self.should_show_menu(view): if not os.path.exists(targetdir): os.makedirs(targetdir, 0o755) if not os.path.exists(targetpath): data = sublime.load_binary_resource( "Packages/R-Box/support/R-Box.sublime-menu").decode( "utf-8") if not self.send_repl_installed( ) and self.send_text_plus_installed(): # fall back to send_text_plus data = data.replace("send_repl", "send_text_plus") with open(targetpath, 'w') as binfile: binfile.write(data) binfile.close() else: if os.path.exists(targetpath): os.remove(targetpath)
def __init__(self, scheme_file, color_filter=None): """Initialize.""" if color_filter is None: color_filter = self.filter self.legacy = not scheme_file.lower().endswith( '.sublime-color-scheme') if NEW_SCHEMES else True self.color_scheme = path.normpath(scheme_file) self.scheme_file = path.basename(self.color_scheme) if self.legacy: scheme_obj = readPlistFromBytes( re.sub( br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'', sublime.load_binary_resource( sublime_format_path(self.color_scheme)))) self.convert_format(scheme_obj) else: self.scheme_obj = sublime.decode_value( sublime.load_resource(sublime_format_path(self.color_scheme))) if 'variables' not in self.scheme_obj: self.scheme_obj['variables'] = {} if GLOBAL_OPTIONS not in self.scheme_obj: self.scheme_obj[GLOBAL_OPTIONS] = {} if 'rules' not in self.scheme_obj: self.scheme_obj['rules'] = [] self.overrides = [] if NEW_SCHEMES: self.merge_overrides() self.scheme_obj = color_filter(self.scheme_obj) self.scheme_file = scheme_file self.matched = {} self.variables = {} self.parse_scheme()
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 __init__(self, scheme_file, color_filter=None): """Initialize.""" if color_filter is None: color_filter = self.filter self.color_scheme = scheme_file.replace('\\', '/') self.scheme_file = path.basename(self.color_scheme) if NEW_SCHEMES and scheme_file.endswith(('.sublime-color-scheme', '.hidden-color-scheme')): self.legacy = False self.scheme_obj = { 'variables': {}, GLOBAL_OPTIONS: {}, 'rules': [] } else: try: content = sublime.load_binary_resource(sublime_format_path(self.color_scheme)) except IOError: # Fallback if file was created manually and not yet found in resources with open(packages_path(self.color_scheme), 'rb') as f: content = f.read() self.legacy = True self.convert_format(readPlistFromBytes(XML_COMMENT_RE.sub(b'', content))) self.overrides = [] if NEW_SCHEMES: self.merge_overrides() self.scheme_file = scheme_file self.matched = {} self.variables = {} self.parse_scheme() self.scheme_obj = color_filter(self.scheme_obj) self.setup_matcher()
def toggle(): current_color_scheme = sublime.load_settings( "Preferences.sublime-settings").get("color_scheme").replace("\\", "/") packages_path = sublime.packages_path().replace("\\", "/") cache_path = sublime.cache_path().replace("\\", "/") package_name, theme_file, relative_path_to_theme_file = get_current_color_scheme_parts( current_color_scheme) current_theme = plistlib.readPlistFromBytes( sublime.load_binary_resource(current_color_scheme)) non_cfml_settings = [ row for row in current_theme["settings"] if "scope" not in row or not row["scope"].endswith("cfml") ] # if there are no cfml styles, then add them, else remove them (i.e. toggle) adding_styles = len(non_cfml_settings) == len(current_theme["settings"]) if adding_styles: current_theme["settings"].extend(get_style_settings()) else: current_theme["settings"] = non_cfml_settings if adding_styles or not is_installed_package(package_name): directory_exists = create_directory_if_not_exists( packages_path + "/" + relative_path_to_theme_file) if not directory_exists: return plistlib.writePlist( current_theme, packages_path + "/" + relative_path_to_theme_file + "/" + theme_file) else: remove_directory_if_exists(packages_path + "/" + package_name) remove_file_if_exists(cache_path + "/" + relative_path_to_theme_file + "/" + theme_file + ".cache")
def update_templates(): global templates log.debug("Templates update") # Init templates. templates = {} types = { "phantom": ["error", "warning", "fixit", "note"], "popup": ["error", "info"] } for key in types.keys(): templates[key] = {} for name in types[key]: filepath = path.join( PACKAGE_PATH, tools.PKG_NAME, THEMES_PATH, THEME_NAME, "{}_{}.html".format(name, key)) log.debug("load_binary_resource of {}".format(filepath)) templates[key][name] = \ sublime.load_binary_resource(filepath).decode('utf-8')
def __copy_on_absence_or_newer(user_path, binary_path): """ . user_path: path of the file in the user directory binary_path: Packages/Rainmeter/xxx path inside the package """ # could be already copied on a previous run need_update = not os.path.exists(user_path) binary = sublime.load_binary_resource(binary_path) # could be a newer version there # only check if no newer is required since expensive # generally happens in consecutive calls without updates if not need_update: need_update = os.path.getsize(user_path) != len(binary) if need_update: logger.info( "Newer version of color picker found. Copying data over to '" + user_path + "'") with open(user_path, "wb") as file_handler: file_handler.write(binary) else: logger.info("You are using the most current version of '" + binary_path + "'. Continue loading...")
def set_view(self, src, lang): """Setup view for conversion.""" # Get the output panel self.view = sublime.active_window().get_output_panel('mdpopups') # Let all plugins no to leave this view alone self.view.settings().set('is_widget', True) # Don't translate anything. self.view.settings().set("translate_tabs_to_spaces", False) # Don't mess with my indenting Sublime! self.view.settings().set("auto_indent", False) # Insert into the view self.view.run_command('insert', {'characters': src}) # Setup the proper syntax lang = lang.lower() user_map = sublime.load_settings('Preferences.sublime-settings').get('mdpopups.sublime_user_lang_map', {}) keys = set(list(user_map.keys()) + list(lang_map.keys())) loaded = False for key in keys: v = lang_map.get(key, (tuple(), tuple())) user_v = user_map.get(key, (tuple(), tuple())) if lang in (tuple(user_v[0]) + v[0]): for l in (tuple(user_v[1]) + v[1]): for ext in ST_LANGUAGES: sytnax_file = 'Packages/%s%s' % (l, ext) try: sublime.load_binary_resource(sytnax_file) except Exception: continue self.view.set_syntax_file(sytnax_file) loaded = True break if loaded: break if loaded: break if not loaded: # Default to plain text for ext in ST_LANGUAGES: # Just in case text one day switches to 'sublime-syntax' sytnax_file = 'Packages/Plain text%s' % ext try: sublime.load_binary_resource(sytnax_file) except Exception: continue self.view.set_syntax_file(sytnax_file)
def load_plist(relative_path): try: plist_data = plistlib.readPlistFromBytes(sublime.load_binary_resource(relative_path)) print("CFML: loaded plist file - " + relative_path) return plist_data except: print("CFML: unable to load plist file - " + relative_path) return None
def modify_color_scheme(l,s,read_original = False): prefs = sublime.load_settings("Preferences.sublime-settings") read_original = read_original and prefs.has("original_color_scheme") if read_original and prefs.get('color_scheme').find('/Colorcoder/') == -1: read_original = False if prefs.get('original_color_scheme').find('/\(Colorcoded\)/') != -1: print("original theme already colorcoded, abort") return global modification_running if modification_running: return modification_running = True name = prefs.get("original_color_scheme") if read_original else sublime.active_window().active_view().settings().get('color_scheme') try: cs = plistlib.readPlistFromBytes(sublime.load_binary_resource(name)) tokenclr = "#000000" for rule in cs["settings"]: if "scope" not in rule and "name" not in rule: bgc = rule["settings"]["background"] r = int(bgc[1:3],16) g = int(bgc[3:5],16) b = int(bgc[5:7],16) if b>0: b = b-1 elif g>0: g = g-1 elif r>0: r = r-1 else: rule["settings"]["background"] = "#000001" tokenclr = "#%02x%02x%02x" % (r,g,b) break cs["name"] = cs["name"] + " (Colorcoded)" for x in range(0,256): cs["settings"].append(dict( scope="cc0x%x" % x, settings=dict( foreground="#"+''.join(map(lambda c: "%02x" % int(256*c),colorsys.hls_to_rgb(x/256., l, s))), background=tokenclr ) )) newname = "/%s (Colorcoded).tmTheme" % re.search("/([^/]+).tmTheme$", name).group(1) plistlib.writePlist(cs,"%s%s" % (colorshemeemodifier.get_save_dir(),newname)) prefs.set("original_color_scheme", name) prefs.set("color_scheme","Packages%s%s" % (colorshemeemodifier.get_relative_save_dir(), newname)) sublime.save_settings("Preferences.sublime-settings") except Exception as e: sublime.error_message("Colorcoder was not able to parse the colorscheme\nCheck the console for the actual error message.") sublime.active_window().run_command("show_panel", {"panel": "console", "toggle": True}) print(e) finally: modification_running = False
def load_resource(resource, binary=False): """Load the given resource.""" bfr = None if not binary: bfr = sublime.load_resource(resource) else: bfr = sublime.load_binary_resource(resource) return bfr
def load_completions(self): """ Create the `word_dict_list` containing all the words of the dictionary. The format of `word_dict_list` is {"pref" : ["prefix", "Prefab", ...], ...} where the length of "pref" is determined by `minimal_len` global setting variable. This method is called on the first activation of the view and when the dictionary (language) is changed. If this method is called without a language change it simply returns. """ global last_language, word_dict_list, minimal_len, force_reload, print_debug view = sublime.active_window().active_view() dictionary = view.settings().get('dictionary') if not dictionary: return language = os.path.splitext(os.path.basename(dictionary))[0] if "status" in print_debug: if plugin_is_active: view.set_status('DictionaryAutoComplete', '' + language + ' dictionary complete+' + str(minimal_len)) else: view.set_status('DictionaryAutoComplete', 'dictionary complete is disabled') if last_language != language or force_reload: force_reload = False last_language = language get_setting(language) if local_dictionary: dictionary = local_dictionary debug("Load dictionary from ", dictionary, "[", dict_encoding, "]") else: debug("Load standard dictionary: ", language, "[", dict_encoding, "]") try: if ST3: words = sublime.load_binary_resource(dictionary).decode(dict_encoding).splitlines() else: #ST2 dict_path = os.path.join(sublime.packages_path()[:-9], dictionary) words = open(dict_path, encoding=dict_encoding, mode='r').read().splitlines() words = [word.split('/')[0].split('\t')[0] for word in words] except Exception as e: debug("Error reading from dictionary:", e) # optimize the list # the first line of .dic file is the number of words if not local_dictionary: del words[0:1] # keep only words longer than the minimal prefix length words = [word for word in words if len(word) >= minimal_len] # create dictionary of prefix -> list of words word_dict_list = {} for word in words: pref = smash(word[:minimal_len]) if not pref in word_dict_list: word_dict_list[pref] = [] word_dict_list[pref].append(word) debug("Number of words: ", len(words)) debug("First ones: ", words[:10]) debug("Number of prefixes of length ", minimal_len, " : ", len(word_dict_list))
def tint_raw(img, color, opacity=255): """Tint the image.""" if isinstance(img, str): try: img = sublime.load_binary_resource(img) except Exception: _log('Could not open binary file!') _debug(traceback.format_exc(), ERROR) return '' return imagetint.tint_raw(img, color, opacity)
def scheme_lums(scheme_file): color_scheme = os.path.normpath(scheme_file) scheme_file = os.path.basename(color_scheme) plist_file = readPlistFromBytes( sublime.load_binary_resource( sublime_format_path(color_scheme) ) ) color_settings = plist_file["settings"][0]["settings"] rgba = RGBA(color_settings.get("background", '#FFFFFF')) return rgba.luminance()
def clear(self): self._setup(noedit=True) if self.theme_valid: with open(self.scheme_clone, "wb") as f: f.write(sublime.load_binary_resource(self.scheme_map["original"])) self.scheme_map["redo"] = "" self.scheme_map["undo"] = "" self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: log("Theme has not been tweaked!", status=True)
def parse_scheme(self): if sublime is None or \ sublime.active_window() is None or \ sublime.active_window().active_view() is None: return if self.settings is None: self.settings = sublime.load_settings( 'Preferences.sublime-settings') self.settings.add_on_change( 'color_scheme', lambda: self.parse_scheme()) color_scheme = self.settings.get( 'color_scheme', 'Packages/Color Scheme - Default/Monokai.tmTheme') if self.color_scheme == color_scheme and self.color_map is not None: return self.color_scheme = color_scheme self.styles = None self.color_map = None try: if int(sublime.version()) >= 3000: b = sublime.load_binary_resource(color_scheme) pl = readPlistFromBytes(b) else: pl = readPlist(os.path.join(os.path.abspath( sublime.packages_path() + '/..'), color_scheme)) except: print(traceback.print_exc()) return def safe_update(fr, to): for k in fr.keys(): if k not in to: to[k] = fr[k] dct = {} for d in pl.settings: if 'settings' not in d: continue s = d['settings'] if 'scope' not in d: safe_update(s, dct) else: scope = d['scope'] scopes = [sc.strip() for sc in scope.split(',')] if 'text' in scopes or 'source' in scopes: dct.update(d.settings) self.color_map = dct
def __init__(self, scheme_file): """Initialize.""" self.plist_file = readPlistFromBytes( re_strip_xml_comments.sub( b'', sublime.load_binary_resource(scheme_file) ) ) self.text = '' self.colors = OrderedDict() self.scheme_file = scheme_file self.gen_css()
def set_language(lang, force=False): if lang not in LANGS: return PACKAGES_PATH = sublime.packages_path() DEFAULT_PATH = os.path.join(PACKAGES_PATH, "Default") SYN_PATH = os.path.join(DEFAULT_PATH, "Syntax.sublime-menu") # not force update then check current lang if not force and os.path.isfile(SYN_PATH): with open(SYN_PATH, "rb") as f: syntax = f.read() m = md5() m.update(syntax) if m.hexdigest() == LANGS[lang]['syntax_md5sum']: sublime.status_message("%s has loaded." % lang) return # mkdir if Default not exist if not os.path.isdir(DEFAULT_PATH): os.mkdir(DEFAULT_PATH) # Load binary resource PACKAGE_NAME = __name__.split('.')[0] LOCALZIP_RES = "Packages/{}/{}".format(PACKAGE_NAME, LANGS[lang]['zipfile']) lang_bytes = sublime.load_binary_resource(LOCALZIP_RES) # Use BytesIO and zipfile to unzip it. from io import BytesIO import zipfile file_buf = BytesIO(lang_bytes) with zipfile.ZipFile(file_buf, "r") as f: f.extractall(DEFAULT_PATH) # Remove mnemonic for OSX platform = sublime.platform() if platform == "osx": import re pattern = re.compile(r"(?<=[\u3000-\u9FFFa-zA-Z])\([A-Za-z]\)", re.M) pattern_help = re.compile(r"(ヘルプ|帮助|幫助)") MAIN_MENU = os.path.join(DEFAULT_PATH, "Main.sublime-menu") fh = open(MAIN_MENU, "rb") content = fh.read().decode("utf-8") fh.close() content = re.sub(pattern, "", content) content = re.sub(pattern_help, "Help", content) fh = open(MAIN_MENU, "wb") fh.write(content.encode("utf-8")) fh.close()
def load_emoji(): f = sublime.load_binary_resource("/".join(("Packages", __package__, "emoji-data.txt"))) lines = f.decode("utf-8").strip().split("\n") data = [] names = {} for line in lines: if line[0] == "#": continue code, emoji, name = re.findall("^([A-Z0-9 ]+) ;.+\((.+)\) (.+)", line)[0] names[code] = name name = name.title() data.append([code, emoji, name, "{} {} ({})".format(emoji, name, code)]) return sorted(data, key=lambda x: names[x[0]])
def get_color_scheme(): setting = sublime.load_settings("Preferences.sublime-settings").get("color_scheme") color_scheme_bytes = sublime.load_binary_resource(setting) color_scheme = {"scopes": []} for setting in plistlib.readPlistFromBytes(color_scheme_bytes)["settings"]: if "scope" in setting: this_scope = {"scope": setting["scope"], "style": {}} for key in ["foreground","background","fontStyle"]: if key in setting["settings"]: this_scope["style"][key] = setting["settings"][key] color_scheme["scopes"].append(this_scope) else: color_scheme["foreground"] = setting["settings"]["foreground"] color_scheme["background"] = setting["settings"]["background"] return color_scheme
def run(self, *args, **kwargs): view = sublime.active_window().active_view() #settings = sublime.load_settings('KSP.sublime-settings') #scheme_file = settings.get('color_scheme', 'Packages/SublimeKSP/KScript Light.tmTheme') scheme_file = 'Packages/SublimeKSP/KScript Light.tmTheme' plist = readPlistFromBytes(sublime.load_binary_resource(scheme_file)) result = ['[pre]'] start, end = view.sel()[0].a, view.sel()[0].b if start == end: start, end = 0, view.size() for a, b, scopes in get_ranges(view.scope_name(i) for i in range(start, end)): result.append(self.apply_style(scopes, plist, view.substr(sublime.Region(start+a, start+b)))) result.append('[/pre]') sublime.set_clipboard(''.join(result))
def gutter_icon_path(self): try: resource = sublime.load_binary_resource("gutter-icon.png") cache_path = os.path.join(sublime.cache_path(), "Merlin", "gutter-icon.png") if not os.path.isfile(cache_path): if not os.path.isdir(os.path.dirname(cache_path)): os.makedirs(os.path.dirname(cache_path)) with open(cache_path, "wb") as f: f.write(resource) return "Cache/Merlin/gutter-icon.png" except IOError: return "Packages/" + self._plugin_dir() + "/gutter-icon.png"
def install_binaries(): print('FSharp: Installing files to Packages/FSharp_Binaries...') sublime.status_message('FSharp: Installing files to Packages/FSharp_Binaries...') try: os.mkdir(const.path_to_fs_binaries()) except IOError: pass zipped_bytes = sublime.load_binary_resource('Packages/FSharp/bundled/fsautocomplete.zip') target = os.path.join(const.path_to_fs_binaries(), 'fsautocomplete.zip') with open(target, 'wb') as f: f.write(zipped_bytes) with open(target, 'rb') as f: ZipFile(f).extractall(path=const.path_to_fs_binaries()) os.unlink(target)