def get_code(self, type, namespace, filename): code = '' file_name = "%s.tmpl" % type isIOError = False tmpl_dir = 'Packages/' + self.PACKAGE_NAME + '/' + self.TMLP_DIR + '/' user_tmpl_dir = 'Packages/User/' + \ self.PACKAGE_NAME + '/' + self.TMLP_DIR + '/' self.user_tmpl_path = os.path.join(user_tmpl_dir, file_name) self.tmpl_path = os.path.join(tmpl_dir, file_name) try: code = sublime.load_resource(self.user_tmpl_path) except IOError: try: code = sublime.load_resource(self.tmpl_path) except IOError: isIOError = True if isIOError: sublime.message_dialog('[Warning] No such file: ' + self.tmpl_path + ' or ' + self.user_tmpl_path) code = code.replace('${namespace}', namespace) code = code.replace('${classname}', filename) return code
def decodeEntity(xml, category='iso'): global entities if not isinstance(xml, str): return xml if entities[category]: forward, reverse = entities[category] else: if category == 'iso': forward = sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/IsoEntities.json')) elif category == 'html': forward = sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/HtmlEntities.json')) reverse = dict((v, k) for k, v in forward.items()) entities[category] = (forward, reverse) def parseEntity(match): entity = match.group(1) try: if entity.isdigit(): return reverse[int(entity)] else: return chr(forward[entity]) except: return match.group(0) xml = re.sub('&([a-zA-Z0-9]+);', parseEntity, xml) return xml
def apply_syntax(self, syntax, view): # print("Applying", syntax) try: sublime.load_resource(syntax) except Exception: print("Syntax file not found", syntax) view.set_syntax_file(syntax)
def parseJSON(self, package, name, ext): if ST2: path = os.path.join(sublime.packages_path(), package, name + '.' + ext) if not os.path.isfile(path): path = os.path.join(sublime.packages_path(), package, 'Default.' + ext) if not os.path.isfile(path): return None return None with codecs.open(path) as f: content = self.removeComments(f.read()) if f is not None: f.close() try: parsedJSON = json.loads(content, cls=ConcatJSONDecoder) except (ValueError): return None return parsedJSON[0] else: try: resource = sublime.load_resource('Packages/' + package + '/' + name + '.' + ext) except (IOError): try: resource = sublime.load_resource('Packages/' + package + '/Default.' + ext) except (IOError): return None return None return sublime.decode_value(resource)
def plugin_loaded(): global settings global KWDB global SETTINGS_FILE global INDENT_STYLE global INDENT_STYLE_ALLMAN global INDENT_STYLE_K_AND_R SETTINGS_FILE = 'LSL.sublime-settings' INDENT_STYLE = os.path.join(sublime.packages_path(), 'User', 'LSL_indent_style.tmPreferences') INDENT_STYLE_ALLMAN = sublime.load_resource('Packages/LSL/metadata/LSL_indent_style.tmPreferences.allman') INDENT_STYLE_K_AND_R = sublime.load_resource('Packages/LSL/metadata/LSL_indent_style.tmPreferences.k_and_r') try: settings = sublime.load_settings(SETTINGS_FILE) except Exception as e: print(e) if not os.path.exists(INDENT_STYLE): with open(INDENT_STYLE, mode='w', newline='\n') as file: file.write(INDENT_STYLE_ALLMAN) kwdbAsString = sublime.load_resource('Packages/LSL/other/kwdb/kwdb.xml') KWDB = etree.fromstring(kwdbAsString)
def fixup_docs_action(self): docs_path = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'NeoVintageous/res/doc') def set_utf8_encoding_save_and_close(view): view.run_command('set_encoding', {'encoding': 'utf-8'}) view.run_command('save') view.close() for f in os.listdir(docs_path): if f.endswith('.txt'): resource = 'Packages/NeoVintageous/res/doc/%s' % f try: load_resource(resource) except Exception as e: print(' Error: ' + resource + ' ' + str(e)) file = packages_path() + '/NeoVintageous/res/doc/%s' % f print(' Fixing resource encoding for \'{}\''.format(file)) view = self.window.open_file(file) set_timeout_async(functools.partial(set_utf8_encoding_save_and_close, view), 200)
def set_syntax(self, name): # the default settings file uses / to separate the syntax name parts, but if the user # is on windows, that might not work right. And if the user happens to be on Mac/Linux but # is using rules that were written on windows, the same thing will happen. So let's # be intelligent about this and replace / and \ with os.path.sep to get to # a reasonable starting point path = os.path.dirname(name) name = os.path.basename(name) if not path: path = name file_name = name + ".tmLanguage" new_syntax = sublime_format_path("/".join(["Packages", path, file_name])) current_syntax = self.view.settings().get("syntax") # only set the syntax if it's different if new_syntax != current_syntax: # let's make sure it exists first! try: sublime.load_resource(new_syntax) self.view.set_syntax_file(new_syntax) log("Syntax set to " + name + " using " + new_syntax) except: log("Syntax file for " + name + " does not exist at " + new_syntax)
def reload_settings(self): self.settings_default = sublime.decode_value(sublime.load_resource(from_package('Mediawiker.sublime-settings'))) self.settings = sublime.load_settings('Mediawiker.sublime-settings') try: self.settings_user = sublime.decode_value(sublime.load_resource(from_package('Mediawiker.sublime-settings', name='User'))) except IOError: self.settings_user = {}
def __init__(self): self.client_id = "141" self.client_secret = "4*ic:5WfF;LxE534" self.settings = tools.load_settings("LaTeXing", mendeley_oauth_token="", mendeley_internal_cite_key=False, mendeley_cite_key_pattern="{Author}{year}") # Load map self.map = sublime.decode_value(sublime.load_resource("Packages/LaTeXing/latexing/api/mendeley.map")) # bibtex: zotero type self.type_map = self.map["types"] # bibtex: zotero field self.field_map = self.map["fields"] # Check for user maps try: self.user_map = sublime.decode_value(sublime.load_resource("Packages/User/LaTeXing/mendeley.map")) self.type_map.update(self.user_map["types"] if "types" in self.user_map else {}) self.field_map.update(self.user_map["fields"] if "fields" in self.user_map else {}) except: pass self.status = "Ok" self.items = [] self.items_no_key = {}
def __init__(self): self.client_key = "40af22476e380eadfef5" self.client_secret = "ec5cfba3fb9fb063d0d4" self.settings = tools.load_settings("LaTeXing", zotero_user_key="", zotero_user_id="", zotero_cite_key_pattern="{Author}{year}" ) # Load map self.map = sublime.decode_value(sublime.load_resource("Packages/LaTeXing/latexing/api/zotero.map")) # bibtex: zotero type self.type_map = self.map["types"] # bibtex: zotero field self.field_map = self.map["fields"] # Check for user maps try: self.user_map = sublime.decode_value(sublime.load_resource("Packages/User/LaTeXing/zotero.map")) self.type_map.update(self.user_map["types"] if "types" in self.user_map else {}) self.field_map.update(self.user_map["fields"] if "fields" in self.user_map else {}) except: pass self.status = "Ok" self.items = [] self.items_no_key = {}
def run(self, edit, view_name): popup_max_width = 600 popup_max_height = 600 css = sublime.load_resource("Packages/GitSavvy/popups/style.css") html = sublime.load_resource("Packages/GitSavvy/popups/" + view_name + ".html").format( css=css, super_key=util.super_key ) self.view.show_popup(html, 0, -1, popup_max_width, popup_max_height)
def copy_filename_root_changed(self,root): self.root_folder = root self.saveRoot(root, sublime.load_resource('Packages/FileActions/Side Bar.sublime-menu'), os.path.join(sublime.packages_path(), 'User', 'FileActions', 'Side Bar.sublime-menu')) self.saveRoot(root, sublime.load_resource('Packages/FileActions/Context.sublime-menu'), os.path.join(sublime.packages_path(), 'User', 'FileActions', 'Context.sublime-menu'))
def _plugin_loaded(): global PREVIEW_TEMPLATE, PAGINATION_TEMPLATE root_path = "Packages/" + utils.get_plugin_name() + "/templates" PREVIEW_TEMPLATE = sublime.load_resource( root_path + "/method_preview.html" ).replace("\r", "") PAGINATION_TEMPLATE = sublime.load_resource(root_path + "/pagination.html").replace( "\r", "" )
def exists_resource(resource_file_path): if sublime.version() >= "3000": try: sublime.load_resource(resource_file_path) return True except: return False else: filename = os.path.join(os.path.dirname(sublime.packages_path()), resource_file_path) return os.path.isfile(filename)
def _get_user_css(): """Get user css.""" css = None user_css = _get_setting('mdpopups.user_css', DEFAULT_USER_CSS) try: css = clean_css(sublime.load_resource(user_css)) except Exception: css = clean_css(sublime.load_resource(DEFAULT_CSS)) return css if css else ''
def open_gist(gist_url): gist = api_request(gist_url) # print('Gist:', gist) files = sorted(gist['files'].keys()) for gist_filename in files: # if gist['files'][gist_filename]['type'].split('/')[0] != 'text': # continue view = sublime.active_window().new_file() gistify_view(view, gist, gist_filename) if PY3: view.run_command('append', { 'characters': gist['files'][gist_filename]['content'], }) else: edit = view.begin_edit() view.insert(edit, 0, gist['files'][gist_filename]['content']) view.end_edit(edit) if settings.get('supress_save_dialog'): view.set_scratch(True) if not "language" in gist['files'][gist_filename]: continue language = gist['files'][gist_filename]['language'] if language is None: continue if language == 'C': new_syntax = os.path.join('C++', "{0}.tmLanguage".format(language)) else: new_syntax = os.path.join(language, "{0}.tmLanguage".format(language)) if PY3: new_syntax_path = os.path.join('Packages', new_syntax) if sublime.platform() == 'windows': new_syntax_path = new_syntax_path.replace('\\', '/') try: sublime.load_resource(new_syntax_path) view.set_syntax_file(new_syntax_path) except: pass else: new_syntax_path = os.path.join(sublime.packages_path(), new_syntax) if os.path.exists(new_syntax_path): view.set_syntax_file(new_syntax_path)
def set_syntax(self, path, file_name=False): if not file_name: file_name = path file_name = file_name + '.tmLanguage' new_syntax = sublime_format_path('/'.join(['Packages', path, file_name])) current_syntax = self.view.settings().get('syntax') if new_syntax != current_syntax: sublime.load_resource(new_syntax) self.view.set_syntax_file(new_syntax)
def locate_and_load_resource(hint): """Try to load the first match of hint""" try: return sublime.load_resource(hint) except OSError: pass resources = sublime.find_resources(hint) if not resources: sublime.error_message('Unable to locate %r' % hint) raise OSError('resource not found') first = resources[0] if len(resources) > 1: suricate.log('WARNING: more than one %r found, using %r', hint, first) return sublime.load_resource(first)
def get_code(self, type): settings = self.get_settings() custom_path = settings.get('custom_path', '') code = '' user_file_name = "%s.user.tmpl" % type file_name = "%s.tmpl" % type isIOError = False if custom_path: tmpl_dir = custom_path; else: if IS_GTE_ST3: tmpl_dir = 'Packages/' + PACKAGE_NAME + '/' + TMLP_DIR + '/' # tmpl_dir = os.path.join('Packages', PACKAGE_NAME , TMLP_DIR) else: tmpl_dir = os.path.join(PACKAGES_PATH, PACKAGE_NAME, TMLP_DIR) self.user_tmpl_path = os.path.join(tmpl_dir, user_file_name) self.tmpl_path = os.path.join(tmpl_dir, file_name) if IS_GTE_ST3: if custom_path: if os.path.isfile(self.user_tmpl_path): code = self.open_file(self.user_tmpl_path); elif os.path.isfile(self.tmpl_path): code = self.open_file(self.tmpl_path); else: isIOError = True else: try: code = sublime.load_resource(self.user_tmpl_path) except IOError: try: code = sublime.load_resource(self.tmpl_path) except IOError: isIOError = True else: if os.path.isfile(self.user_tmpl_path): code = self.open_file(self.user_tmpl_path); elif os.path.isfile(self.tmpl_path): code = self.open_file(self.tmpl_path); else: isIOError = True # print(self.tmpl_path) if isIOError: sublime.message_dialog('[Warning] No such file: ' + self.tmpl_path) return self.format_tag(code)
def run(self, edit): # html = sublime.load_resource("Packages/sandbox/html/phantom.html") css = sublime.load_resource("Packages/sandbox/html/ui.css") html = sublime.load_resource("Packages/sandbox/html/ui.html").format(css=css) v = self.view.window().new_file() v.settings().set('gutter', False) v.settings().set('margin', 0) v.set_read_only(True) v.set_scratch(True) sel = v.sel() sel.clear() # LAYOUT_INLINE # LAYOUT_BELOW # LAYOUT_BLOCK v.add_phantom("test", self.view.sel()[0], html, sublime.LAYOUT_INLINE)
def get_track_data(self): track_script = sublime.load_resource("Packages/iTunes/scripts/track.scpt") artist_script = sublime.load_resource("Packages/iTunes/scripts/artist.scpt") track_p = subprocess.Popen("osascript -l JavaScript -e " + shlex.quote(track_script), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) track_name, err = track_p.communicate() if err: return artist_p = subprocess.Popen("osascript -l JavaScript -e " + shlex.quote(artist_script), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) artist_name, err = artist_p.communicate() if err: return return { "name": track_name.decode().strip(), "artist": artist_name.decode().strip() }
def _import_module(module_name, loaded=None): """ Import the module. Import the module and track which modules have been loaded so we don't load already loaded modules. """ # Pull in built-in and custom plugin directory if module_name.startswith("bh_modules."): path_name = join("Packages", "BracketHighlighter", normpath(module_name.replace('.', '/'))) else: path_name = join("Packages", normpath(module_name.replace('.', '/'))) path_name += ".py" if loaded is not None and module_name in loaded: module = sys.modules[module_name] else: module = imp.new_module(module_name) sys.modules[module_name] = module exec( compile( sublime.load_resource(sublime_format_path(path_name)), module_name, 'exec' ), sys.modules[module_name].__dict__ ) return module
def check_status(self): if not self.settings_loaded: self.settings = sublime.load_settings(SETTINGS_FILE) INFOS.get_settings(self.settings) INFOS.update_builtin_labels() css_file = 'Packages/SublimeKodi/' + self.settings.get('tooltip_css_file') self.css = sublime.load_resource(css_file) self.settings_loaded = True view = sublime.active_window().active_view() filename = view.file_name() if INFOS.addon_xml_file and filename and filename.endswith(".xml"): view.assign_syntax('Packages/SublimeKodi/KodiSkinXML.sublime-syntax') if filename and filename.endswith(".po"): view.assign_syntax('Packages/SublimeKodi/Gettext.tmLanguage') if filename and filename.endswith(".log"): view.assign_syntax('Packages/SublimeKodi/KodiLog.sublime-syntax') if view and view.window() is not None: variables = view.window().extract_variables() if "folder" in variables: project_folder = variables["folder"] if project_folder and project_folder != self.actual_project: self.actual_project = project_folder log("project change detected: " + project_folder) INFOS.init_addon(project_folder) else: log("Could not find folder path in project file")
def load_scheme(self, scheme_path): if scheme_path not in self.schemes: scheme_res = sublime.load_resource(scheme_path) if scheme_res: try: # Go through all styles and collect scope/foreground/fontStyle etc. scheme_tree = ElementTree.fromstring(scheme_res) scheme = {} for d in scheme_tree.findall(".//dict[key='scope']"): cur_style = {} cur_tag = None for elem in d.iter(): if elem.tag == 'key': cur_tag = elem.text # We are going to fill it next time elif elem.tag == 'string' and cur_tag is not None: cur_style[cur_tag] = elem.text cur_tag = None if 'scope' in cur_style: scheme[cur_style['scope']] = cur_style self.schemes[scheme_path] = scheme except: pass return self.schemes.get(scheme_path, {})
def run(self): """Show the changelog in a new view.""" try: import mdpopups has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3118) except Exception: has_phantom_support = False text = sublime.load_resource('Packages/ApplySyntax/CHANGES.md') view = self.window.new_file() view.set_name('ApplySyntax - Changelog') view.settings().set('gutter', False) if has_phantom_support: mdpopups.add_phantom( view, 'changelog', sublime.Region(0), text, sublime.LAYOUT_INLINE, wrapper_class="apply-syntax", css=CSS ) else: view.run_command('insert', {"characters": text}) view.set_read_only(True) view.set_scratch(True)
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 load_resource(name): """ return file contents for files within the package root folder """ v = sublime.version() if v >= "3000": filename = "/".join(["Packages", INSTALLED_DIRECTORY, name]) try: return sublime.load_resource(filename) except: print("Error while load_resource('%s')" % filename) traceback.print_exc() return "" else: # 2.x filename = os.path.join(sublime.packages_path(), INSTALLED_DIRECTORY, name) if not os.path.isfile(filename): print("Error while lookup resources file: %s", name) return "" try: return open(filename, "r").read().decode("utf-8") except: print("Error while load_resource('%s')" % filename) traceback.print_exc() return ""
def read_js(file_path, use_unicode=True): file_path = os.path.normpath(file_path) if hasattr(sublime, 'load_resource'): rel_path = None for prefix in [sublime.packages_path(), sublime.installed_packages_path()]: if file_path.startswith(prefix): rel_path = os.path.join('Packages', file_path[len(prefix) + 1:]) break if rel_path: rel_path = rel_path.replace('.sublime-package', '') # for Windows we have to replace slashes # print('Loading %s' % rel_path) rel_path = rel_path.replace('\\', '/') return sublime.load_resource(rel_path) if use_unicode: f = codecs.open(file_path, 'r', 'utf-8') else: f = open(file_path, 'r') content = f.read() f.close() return content
def run(self, edit, page, anchor, add_to_history=True): settings = self.view.settings() previous_page = settings.get("git_savvy.help.page") if not page == previous_page: settings.set("git_savvy.help.page", page) content = sublime.load_resource("Packages/GitSavvy/docs/" + page) is_read_only = self.view.is_read_only() self.view.set_read_only(False) self.view.replace(edit, sublime.Region(0, self.view.size()), content) self.view.set_read_only(is_read_only) self.collapse_links() else: content = self.view.substr(sublime.Region(0, self.view.size())) if add_to_history: history = settings.get("git_savvy.help.history") or [] history.append((page, anchor)) settings.set("git_savvy.help.history", history) pt = self.find_anchor(content, anchor) sel = self.view.sel() sel.clear() sel.add(sublime.Region(pt, pt)) self.view.show(pt)
def run(self): f = tempfile.NamedTemporaryFile(mode="w+", suffix=".html", delete=False) outFile = f.name f.close() g = tempfile.NamedTemporaryFile(mode="w+", suffix=".html", delete=False) empty_template = sublime.load_resource("Packages/Markboard3/template-empty.html") g.write(empty_template) g.close() md = 'markdown+hard_line_breaks+intraword_underscores+strikeout+superscript+\ subscript+inline_code_attributes+all_symbols_escapable+yaml_metadata_block+\ pipe_tables+grid_tables+multiline_tables+table_captions+simple_tables+\ example_lists+definition_lists+startnum+fancy_lists+fenced_code_attributes+\ fenced_code_blocks+backtick_code_blocks+blank_before_blockquote+\ implicit_header_references+auto_identifiers+header_attribuets+\ blank_before_header+escaped_line_breaks' cmd = ['pandoc', self.myFilename, '--output=%s' % outFile, '--from=%s' % md, '--to=html5', '--smart', '--normalize', '--email-obfuscation=none', '--template=%s' % g.name] try: subprocess.call(cmd, env=self.env) except Exception as e: err("Exception: " + str(e)) self.result = False else: f = codecs.open(outFile, "r", "utf-8") self.result = f.read() f.close()
def load_json(*segments, from_sl_dir=False): base_path = "Packages/SublimeLinter/" if from_sl_dir else "" full_path = base_path + "/".join(segments) return sublime.decode_value(sublime.load_resource(full_path))
def load(name): return sublime.load_resource('Packages/SALSyntax/{0}'.format(name))
def sublinter(): sublime_packages_path = sublime.packages_path() try: if not os.path.exists(os.path.join( sublime_packages_path, OVERLAY_ROOT )): log("Updating linter settings") icons = json.loads(sublime.load_resource("Packages/" + PACKAGE_NAME + "/common/icons.json")) aliases = {} sl_settings_file = "SublimeLinter.sublime-settings" sl_default_resource_path = "Packages/SublimeLinter/{}".format( sl_settings_file ) sl_default_settings_path = os.path.join( sublime_packages_path, "SublimeLinter", sl_settings_file ) sl_user_resource_path = "Packages/User/{}".format(sl_settings_file) sl_user_settings_path = os.path.join( sublime_packages_path, "User", sl_settings_file ) sl_input_settings = {} sl_output_settings = {"user": {}} if os.path.exists(sl_user_settings_path): sl_input_settings = json.loads(jsonutils.sanitize_json( sublime.load_resource(sl_user_resource_path)))["user"] elif os.path.exists(sl_default_settings_path): sl_input_settings = json.loads(jsonutils.sanitize_json( sublime.load_resource( sl_default_resource_path )))["default"] if sl_input_settings: for i in icons: if "aliases" in icons[i]: for a in icons[i]["aliases"]: if "linter" in a: aliases[a["name"].lower()] = a["linter"] new_syntax_map = _merge( aliases, sl_input_settings["syntax_map"] ) sl_input_settings["syntax_map"] = new_syntax_map sl_output_settings["user"] = sl_input_settings with open(sl_user_settings_path, "w") as f: json.dump(sl_output_settings, f, sort_keys=True, indent=4) f.close() except Exception as error: log("Error during saving linter settings") dump(error)
def run(self): show_read_only_doc_view( self.window.new_file(), sublime.load_resource('Packages/Requester/docs/tutorial.pyr'), 'Requester Tutorial.pyr', syntax='Packages/Requester/syntax/requester-source.sublime-syntax')
def getCss(self): return (sublime.load_resource('Packages/' + package_name + '/style.css'), 'docphp_popup')
def generate_color_scheme_async(): """ Generate a modified copy of the current color scheme that contains SublimeLinter color entries. The current color scheme is checked for SublimeLinter color entries. If any are missing, the scheme is copied, the entries are added, and the color scheme is rewritten to Packages/User/SublimeLinter. """ # First make sure the user prefs are valid. If not, bail. path = os.path.join(sublime.packages_path(), 'User', 'Preferences.sublime-settings') if (os.path.isfile(path)): try: with open(path, mode='r', encoding='utf-8') as f: json = f.read() sublime.decode_value(json) except: from . import persist persist.printf('generate_color_scheme: Preferences.sublime-settings invalid, aborting') return prefs = sublime.load_settings('Preferences.sublime-settings') scheme = prefs.get('color_scheme') if scheme is None: return scheme_text = sublime.load_resource(scheme) # Ensure that all SublimeLinter colors are in the scheme scopes = { 'mark.warning': False, 'mark.error': False, 'gutter-mark': False } for scope in scopes: if re.search(MARK_COLOR_RE.format(re.escape(scope)), scheme_text): scopes[scope] = True if False not in scopes.values(): return # Append style dicts with our styles to the style array plist = ElementTree.XML(scheme_text) styles = plist.find('./dict/array') from . import persist for style in COLOR_SCHEME_STYLES: color = persist.settings.get('{}_color'.format(style), DEFAULT_MARK_COLORS[style]).lstrip('#') styles.append(ElementTree.XML(COLOR_SCHEME_STYLES[style].format(color))) if not os.path.exists(os.path.join(sublime.packages_path(), 'User', 'SublimeLinter')): os.makedirs(os.path.join(sublime.packages_path(), 'User', 'SublimeLinter')) # Write the amended color scheme to Packages/User/SublimeLinter original_name = os.path.splitext(os.path.basename(scheme))[0] name = original_name + ' (SL)' scheme_path = os.path.join(sublime.packages_path(), 'User', 'SublimeLinter', name + '.tmTheme') with open(scheme_path, 'w', encoding='utf8') as f: f.write(COLOR_SCHEME_PREAMBLE) f.write(ElementTree.tostring(plist, encoding='unicode')) # Set the amended color scheme to the current color scheme path = os.path.join('User', 'SublimeLinter', os.path.basename(scheme_path)) prefs.set('color_scheme', packages_relative_path(path)) sublime.save_settings('Preferences.sublime-settings')
def decode_value(self, file): # Check json syntax try: return sublime.decode_value(sublime.load_resource(file)) except ValueError as e: self.error('Invalid json in %s: %s' % (file, e))
def parse_code(self, selector): """ Parse code against Java grammar @param selector: scope selector (refer to GrammarParser's selector) """ try: scope = GrammarParser( sublime.decode_value( sublime.load_resource( "Packages/Javatar/grammars/Java8.javatar-grammar"))) parse_output = scope.parse_grammar( self.view.substr(sublime.Region(0, self.view.size()))) status_text = "" if parse_output["success"]: if selector == "": nodes = scope.find_all() elif selector == "#": selections = self.view.sel() nodes = scope.find_by_region([0, 0]) if selections: first_sel = selections[0] if first_sel.empty(): nodes = scope.find_by_region( [first_sel.begin(), first_sel.end()]) else: nodes = scope.find_inside_region( [first_sel.begin(), first_sel.end()]) else: nodes = scope.find_by_selectors(selector) if selector != "#": status_text = "Parsing got {} tokens".format(len(nodes)) for node in nodes: if selector == "#": if status_text == "": status_text += node["name"] else: status_text += " " + node["name"] else: Logger().none( "#{begin}:{end} => {name}".format_map(node)) Logger().none(" => {value}".format_map(node)) Logger().none("Total: {} tokens".format(len(nodes))) if selector != "#": if (status_text != "" and str(parse_output["end"]) == str(self.view.size())): status_text += " in {elapse_time:.2f}s".format( elapse_time=scope.get_elapse_time()) else: status_text = "Parsing failed [%s/%s] in {%.2f}s" % ( parse_output["end"], self.view.size(), scope.get_elapse_time()) Logger().none("Ending: %s/%s" % (parse_output["end"], self.view.size())) Logger().none("Parsing Time: {elapse_time:.2f}s".format( elapse_time=scope.get_elapse_time())) StatusManager().show_status(status_text) except Exception as e: ActionHistory().add_action("javatar.commands.utils.parse_code", "Error while parsing", e)
def load_json_data(filename): json_data = sublime.load_resource("Packages/" + utils.get_plugin_name() + "/src/plugins_/fw1/json/" + filename + ".json") return json.loads(json_data)
def getAllLanguages(): return sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/languages.json'))
def run(self, edit, view_name, popup_max_width=800, popup_max_height=600): css = sublime.load_resource("Packages/GitSavvy/popups/style.css") html = sublime.load_resource("Packages/GitSavvy/popups/" + view_name + ".html")\ .format(css=css, super_key=util.super_key) self.view.show_popup(html, 0, -1, popup_max_width, popup_max_height)
def getAllLanguages(): global all_languages if all_languages == None: all_languages = sublime.decode_value( sublime.load_resource(getPackagePath() + '/languages.json')) return all_languages
def load_color_scheme_resource(color_scheme): return plistlib.readPlistFromBytes( bytes(load_resource(color_scheme), 'UTF-8'))
def run_color_scheme_test(test, window, result_printer, code_coverage): skip = False error = False failures = [] assertion_count = 0 test_view = TestView(window, test) test_view.setUp() try: test_content = load_resource(test) color_test_params = _color_test_params_compiled_pattern.match( test_content) if not color_test_params: error = { 'message': 'Invalid COLOR SCHEME TEST header', 'file': test_view.file_name(), 'row': 0, 'col': 0 } raise RuntimeError(error['message']) syntax_package_name = None syntax = color_test_params.group('syntax_name') if not syntax: syntax = os.path.splitext(test)[1].lstrip('.').upper() elif '/' in syntax: syntax_package_name, syntax = syntax.split('/') syntaxes = find_resources(syntax + '.sublime-syntax') if not syntaxes: syntaxes = find_resources(syntax + '.tmLanguage') if not syntaxes: syntaxes = find_resources(syntax + '.hidden-tmLanguage') if syntax_package_name: syntaxes = [s for s in syntaxes if syntax_package_name in s] if len(syntaxes) > 1: error = { 'message': 'More than one syntax found: {}'.format(syntaxes), 'file': test_view.file_name(), 'row': 0, 'col': 0 } # noqa: E501 raise RuntimeError(error['message']) if len(syntaxes) != 1: if color_test_params.group('skip_if_not_syntax'): skip = { 'message': 'Syntax not found: {}'.format(syntax), 'file': test_view.file_name(), 'row': 0, 'col': 0 } # noqa: E501 raise RuntimeError(error['message']) else: error = { 'message': 'Syntax not found: {}'.format(syntax), 'file': test_view.file_name(), 'row': 0, 'col': 0 } # noqa: E501 raise RuntimeError(error['message']) test_view.view.assign_syntax(syntaxes[0]) test_view.view.settings().set( 'color_scheme', 'Packages/' + color_test_params.group('color_scheme')) test_view.set_content(test_content) color_scheme_style = ViewStyle(test_view.view) # This is down here rather than at the start of the function so that the # on_test_start method will have extra information like the color # scheme and syntax to print out if debugging is enabled. result_printer.on_test_start(test, test_view) code_coverage.on_test_start(test, test_view) consecutive_test_lines = 0 has_failed_assertion = False for line_number, line in enumerate(test_content.splitlines()): assertion_params = _color_test_assertion_compiled_pattern.match( line.lower().rstrip(' -->').rstrip(' */')) if not assertion_params: consecutive_test_lines = 0 continue consecutive_test_lines += 1 requires_build = assertion_params.group('build') if requires_build: if int(version()) < int(requires_build): continue assertion_row = line_number - consecutive_test_lines assertion_begin = line.find('^') assertion_repeat = assertion_params.group('repeat') assertion_end = assertion_begin + len(assertion_repeat) assertion_fg = assertion_params.group('fg') assertion_bg = assertion_params.group('bg') assertion_fs = assertion_params.group('fs') expected = {} if assertion_fg is not None: expected['foreground'] = assertion_fg if assertion_bg is not None: expected['background'] = assertion_bg if assertion_fs is not None: expected['fontStyle'] = assertion_fs for col in range(assertion_begin, assertion_end): result_printer.on_assertion() assertion_count += 1 assertion_point = test_view.view.text_point(assertion_row, col) actual_styles = color_scheme_style.at_point(assertion_point) actual = {} for style in expected: if style in actual_styles: if actual_styles[style]: actual[style] = actual_styles[style].lower() else: actual[style] = actual_styles[style] else: actual[style] = '' if actual != expected: has_failed_assertion = True failures.append({ 'assertion': assertion_params.group(0), 'file': test_view.file_name(), 'row': assertion_row + 1, 'col': col + 1, 'actual': actual, 'expected': expected, }) if has_failed_assertion: result_printer.on_test_failure() else: result_printer.on_test_success() except Exception as e: if not error and not skip: result_printer.output.write("\nAn error occurred: %s\n" % str(e)) if error: result_printer.addError(test, test_view) if skip: result_printer.addSkippedTest(test, test_view) finally: test_view.tearDown() result_printer.on_test_end() return { 'skip': skip, 'error': error, 'failures': failures, 'assertions': assertion_count }
def run(self, edit, view_name="help"): css = sublime.load_resource("Packages/PackagesUI/popups/help.css") html = sublime.load_resource("Packages/PackagesUI/popups/" + view_name + ".html").format(css=css) self.view.show_popup(html, 0, -1, max_width=600, max_height=600)
def _get_default_css(): """Get default CSS.""" return clean_css(sublime.load_resource(DEFAULT_CSS))
def load_data(): sourcePath = 'Packages/{}/src/_assets/keyword_data/LSL.yaml'.format( PKG_NAME) # TODO: sourcePath = f'Packages/{PKG_NAME}/src/_assets/keyword_data/LSL.yaml' global LSL_KEYWORD_DATA LSL_KEYWORD_DATA = YAML().load(sublime.load_resource(sourcePath))
def run(self, edit): css = sublime.load_resource("Packages/sandbox/html/ui.css") html = sublime.load_resource("Packages/sandbox/html/ui.html").format( css=css) self.view.show_popup(html, 0, -1, 480, 700, self.on_navigate, self.on_hide)
def __init__(self): """Initialize basic needs.""" self.CSS = sublime.load_resource(POPUP_CSS_FILE)
def get_characters_html(self): resources = sublime.find_resources('unicode-characters.html') content = sublime.load_resource(resources[0]) return content
def on_activated_async(self, view): global cache global settings settings = sublime.load_settings('SyncedSidebarBg.sublime-settings') # making sure we're not changing sidebar color based on focused panels # like PlainNotes's jotter view = view.window() and view.window().active_view() if not view: return # do nothing if it's a widget if view.settings().get('is_widget'): return scheme_file = view.settings().get('color_scheme') # do nothing if the scheme file is not available or the same as before if not scheme_file or scheme_file == cache.get('color_scheme'): return file_content = sublime.load_resource(scheme_file) removed_comments = re.sub(r"<!--.+-->", '', file_content) plist_file = plistlib.readPlistFromBytes( bytes(removed_comments, 'UTF-8')) global_settings = [ i["settings"] for i in plist_file["settings"] if i["settings"].get("lineHighlight") ] color_settings = global_settings and global_settings[0] if not color_settings: return bg = color_settings.get("background", '#FFFFFF') fg = color_settings.get("foreground", '#000000') bgc = bg.lstrip('#') cache = {"bg": bg, "fg": fg, "color_scheme": scheme_file} # -- COLOR ------------------------------ _NUMERALS = '0123456789abcdefABCDEF' _HEXDEC = { v: int(v, 16) for v in (x + y for x in _NUMERALS for y in _NUMERALS) } def rgb(triplet): return _HEXDEC[triplet[0:2]], _HEXDEC[triplet[2:4]], _HEXDEC[ triplet[4:6]] def is_light(triplet): r, g, b = _HEXDEC[triplet[0:2]], _HEXDEC[triplet[2:4]], _HEXDEC[ triplet[4:6]] yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000 return yiq >= 128 def brightness_variant(hex_color, brightness_offset=1): """ takes a color like #87c95f and produces a lighter or darker variant """ if len(hex_color) == 9: print("=> Passed %s into color_variant()" % hex_color) hex_color = hex_color[0:-2] print("=> Reformatted as %s " % hex_color) if len(hex_color) != 7: raise Exception( "Passed %s into color_variant(), needs to be in #87c95f format." % hex_color) rgb_hex = [hex_color[x:x + 2] for x in [1, 3, 5]] new_rgb_int = [ int(hex_value, 16) + brightness_offset for hex_value in rgb_hex ] new_rgb_int = [min([255, max([0, i])]) for i in new_rgb_int ] # make sure new values are between 0 and 255 return "#%02x%02x%02x" % tuple(new_rgb_int) def bg_variat(bg): if settings.get('sidebar_bg_brightness_change') == 0: return rgb(bgc) else: return rgb( brightness_variant( bg, settings.get( 'sidebar_bg_brightness_change')).lstrip('#')) def color_variant(bg, brightness_change=settings.get( 'side_bar_sep_line_brightness_change')): if is_light(bg.lstrip('#')): return rgb( brightness_variant(bg, -1.4 * brightness_change).lstrip('#')) else: return rgb( brightness_variant(bg, brightness_change).lstrip('#')) template = [{ "class": "tree_row", "layer0.tint": color_variant(bg), }, { "class": "sidebar_container", "layer0.tint": color_variant(bg), "layer0.opacity": 1.0, }, { "class": "sidebar_tree", "layer0.tint": bg_variat(bg), "layer0.opacity": 1, "dark_content": not is_light(bgc) }, { "class": "sidebar_label", "color": color_variant(bg, 180), }, { "class": "sidebar_heading", "shadow_offset": [0, 0] }, { "class": "disclosure_button_control", "layer0.tint": color_variant(bg, 90), "layer1.tint": color_variant(bg, 150), }, { "class": "fold_button_control", "layer0.tint": color_variant(bg, 90), "layer1.tint": color_variant(bg, 150) }, { "class": "scroll_tabs_left_button", "layer0.tint": color_variant(bg, 120), "layer1.tint": color_variant(bg, 180) }, { "class": "scroll_tabs_right_button", "layer0.tint": color_variant(bg, 120), "layer1.tint": color_variant(bg, 180) }, { "class": "show_tabs_dropdown_button", "layer0.tint": color_variant(bg, 120), "layer1.tint": color_variant(bg, 180) }, { "class": "icon_file_type", "layer0.tint": color_variant(bg, 120), }, { "class": "icon_folder", "layer0.tint": color_variant(bg, 90), }, { "class": "sidebar_heading", "color": color_variant(bg, 90), }, { "class": "grid_layout_control", "border_color": color_variant(bg, 90) }] json_str = json.dumps(template, sort_keys=True, indent=4, separators=(',', ': ')).encode('raw_unicode_escape') new_theme_file_path = sublime.packages_path( ) + "/User/" + view.settings().get('theme') with codecs.open(new_theme_file_path, 'w', 'utf-8') as f: f.write(json_str.decode())
def load_build_system(self, build_system): build_system = sublime.load_resource(build_system)
def run(self, action="check_syntax", kill=False): if kill: if self.proc: self.killed = True self.proc.terminate() return view = self.window.active_view() vars = self.window.extract_variables() view_settings = view.settings() # Cleanup old files for file in os.listdir(tempfile.gettempdir()): if file.startswith("sublime_abl_"): os.remove(os.path.join(tempfile.gettempdir(), file)) project_dir, project_file = os.path.split(self.window.project_file_name()) if 'file_path' in vars: working_dir = vars['file_path'] else: working_dir = project_dir if action != 'run-gui': with self.panel_lock: # Creating the panel implicitly clears any previous contents self.panel = self.window.create_output_panel('exec') settings = self.panel.settings() settings.set( 'result_file_regex', r'(?:^(.+?):([0-9]+):([0-9]+)\s(.+)$)*' ) settings.set('result_base_dir', working_dir) self.window.run_command('show_panel', {'panel': 'output.exec'}) if self.proc is not None: self.proc.terminate() self.proc = None abl_p = os.path.join(sublime.cache_path(), 'OpenEdge ABL', 'abl.p') if not os.path.exists(abl_p): with open(abl_p, 'w') as outfile: outfile.write(sublime.load_resource('Packages/OpenEdge ABL/abl.p')) abl_settings = view_settings.get('abl'); dlc = '' if 'dlc' in abl_settings: dlc = abl_settings['dlc'] else: if 'DLC' in os.environ: dlc = os.environ['DLC'] else: self.queue_write('\n[Unable to determine DLC path]') return # Resolve relative paths to project if 'propath' in abl_settings: propath = abl_settings['propath'] for i, path in enumerate(propath): if not os.path.isabs(path): abl_settings['propath'][i] = os.path.join(project_dir, path) if not os.path.isabs(abl_settings['pf']): abl_settings['pf'] = os.path.join(project_dir, abl_settings['pf']) abl_settings['action'] = action temp_procedure = False if 'file_path' in vars: abl_settings['filename'] = os.path.join(vars['file_path'], vars['file_name']) else: temp_procedure = True contents = view.substr(sublime.Region(0, view.size())) abl_settings['filename'] = os.path.join(tempfile.gettempdir(), 'sublime_abl_' + str(uuid.uuid4()) + '.p') with open(abl_settings['filename'], 'w') as outfile: outfile.write(contents) abl_settings_file = os.path.join(tempfile.gettempdir(), 'sublime_abl_' + str(uuid.uuid4()) + '.json') with open(abl_settings_file, 'w') as outfile: json.dump(abl_settings, outfile) args = [] if action == 'run-gui': if (os.name != "posix"): if os.path.exists(os.path.join(dlc, 'bin', 'prowin.exe')): _progres = os.path.join(dlc, 'bin', 'prowin.exe') else: _progres = os.path.join(dlc, 'bin', 'prowin32.exe') else: _progres = os.path.join(dlc, 'bin', '_progres') else: _progres = os.path.join(dlc, 'bin', '_progres') if (os.name != "posix"): _progres += ".exe" # Does windows work without this? Who knows args.append(_progres) if not action == 'run-gui': args.append('-1') args.append('-b') # Run the entry point args.append('-p') args.append(abl_p) # Set the PF file if 'pf' in abl_settings: pf_file = abl_settings['pf'] args.append('-pf') if os.path.isabs(pf_file): args.append(pf_file) else: args.append(os.path.join(project_dir, pf_file)) # Set the PARAM args.append('-param') args.append(abl_settings_file) abl_env = os.environ.copy() abl_env["DLC"] = dlc abl_env["PROMSGS"] = os.path.join(abl_settings['dlc'], 'promsgs') if (os.name == "posix"): abl_env["TERM"] = 'xterm' print (' '.join(args)) if action == 'run-gui': if (os.name != "posix"): self.proc = subprocess.Popen( args, env=abl_env, cwd=working_dir ) else: args[3] = '"' + args[3] + '"' command="export TERM=xterm; export DLC=" + dlc + "; export PROMSGS=$DLC/promsgs; " + ' '.join(args) os.system("gnome-terminal -- /bin/bash -c '" + command + "; read'") else: self.proc = subprocess.Popen( args, env=abl_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=working_dir ) self.killed = False thread = threading.Thread( target=self.read_handle, args=(self.proc.stdout,) ) thread.start() thread.join()
def __init__(self, view): self.current_line = (-1, -1) self.view = view self.settings = sublime.load_settings('hyper_click.sublime-settings') self.css = sublime.load_resource("Packages/HyperClick/html/ui.css") self.html = sublime.load_resource("Packages/HyperClick/html/ui.html")
def run(self, edit): html = sublime.load_resource('Packages/GitHunk/help.html') self.view.show_popup(html, 0, -1, 400, 400)
def __init__(self, original_color_scheme): color_scheme_xml = sublime.load_resource(original_color_scheme) self.plist = ElementTree.XML(color_scheme_xml) self.styles = self.plist.find("./dict/array")
def run(self, find_all=False, **kwargs): if not hasattr(self, 'output_view'): # Try not to call get_output_panel until the regexes are assigned self.output_view = self.window.create_output_panel('exec') settings = self.output_view.settings() settings.set('result_file_regex', PACKAGES_FILE_REGEX) settings.set('result_base_dir', sublime.packages_path()) settings.set('word_wrap', True) settings.set('line_numbers', False) settings.set('gutter', False) settings.set('scroll_past_end', False) # Call create_output_panel a second time after assigning the above # settings, so that it'll be picked up as a result buffer self.window.create_output_panel('exec') if not find_all: relative_path = package_relative_path(self.window.active_view()) if not relative_path: return file_name = os.path.basename(relative_path) if is_syntax(relative_path): tests = [] for t in sublime.find_resources('syntax_test*'): lines = sublime.load_resource(t).splitlines() if len(lines) == 0: continue first_line = lines[0] match = re.match('^.*SYNTAX TEST "(.*?)"', first_line) if not match: continue syntax = match.group(1) if syntax == relative_path or syntax == file_name: tests.append(t) elif file_name.startswith('syntax_test'): tests = [relative_path] else: sublime.error_message( 'The current file is not a *.sublime-syntax, *.tmLanguage ' 'or syntax_test* file') return else: tests = sublime.find_resources('syntax_test*') show_panel_on_build(self.window) total_assertions = 0 failed_assertions = 0 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: append(self.output_view, line + '\n') if failed_assertions > 0: message = 'FAILED: {} of {} assertions in {} files failed\n' params = (failed_assertions, total_assertions, len(tests)) else: message = 'Success: {} assertions in {} files passed\n' params = (total_assertions, len(tests)) append(self.output_view, message.format(*params)) append(self.output_view, '[Finished]')
def find_gutter_themes(self): """ Find all SublimeLinter.gutter-theme resources. For each found resource, if it doesn't match one of the patterns from the "gutter_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 = [] gutter_themes = sublime.find_resources('*.gutter-theme') excludes = persist.settings.get('gutter_theme_excludes', []) pngs = sublime.find_resources('*.png') for theme in gutter_themes: # Make sure the theme has error.png and warning.png exclude = False parent = os.path.dirname(theme) for name in ('error', 'warning'): if '{}/{}.png'.format(parent, name) not in pngs: exclude = True if exclude: continue # Now see if the theme name is in gutter_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) try: info = json.loads(sublime.load_resource(theme)) colorize = info.get('colorize', False) except ValueError: colorize = False std_theme = theme.startswith( 'Packages/SublimeLinter/gutter-themes/') settings.append([ name, '{}{}'.format( 'SublimeLinter theme' if std_theme else 'User theme', ' (colorized)' if colorize else '') ]) # 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 getAllLanguages(): return sublime.decode_value( sublime.load_resource( os.path.join('Packages', package_name, 'languages.json')))
def edit_rule(self, value, new=False): """Parse rule and format as Python code and insert into panel.""" if value >= 0 or new: if new: name = None rule = {} else: name = self.keys[value] rule = self.rules[value] text = '"""\nIf you don\'t need a setting, just leave it as None.\n' text += 'When the rule is parsed, the default will be used.\n' text += 'Each variable is evaluated separately, so you cannot substitute variables ' text += 'in other variables.\n"""\n' text += '\n# name (str): Rule name. Required.\n' text += self.format_string('name', name) text += '\n# find (str): Regular expression pattern or literal string.\n' text += '# Use (?i) for case insensitive. Use (?s) for dotall.\n' text += '# See https://docs.python.org/3.4/library/re.html for more info on regex flags.\n' text += '# Required unless "scope" is defined.\n' text += self.format_regex_string('find', rule.get('find')) text += '\n# replace (str - default=r\'\\g<0>\'): Replace pattern.\n' text += self.format_regex_string('replace', rule.get('replace')) text += '\n# literal (bool - default=False): Preform a non-regex, literal search and replace.\n' text += self.format_bool('literal', rule.get('literal')) text += '\n# literal_ignorecase (bool - default=False): Ignore case when "literal" is true.\n' text += self.format_bool('literal_ignorecase', rule.get('literal_ignorecase')) text += '\n# scope (str): Scope to search for and to apply optional regex to.\n' text += '# Required unless "find" is defined.\n' text += self.format_string('scope', rule.get('scope')) text += '\n# scope_filter ([str] - default=[]): An array of scope qualifiers for the match.\n' text += '# Only used when "scope" is not defined.\n' text += '#\n' text += '# - Any instance of scope qualifies match: scope.name\n' text += '# - Entire match of scope qualifies match: !scope.name\n' text += '# - Any instance of scope disqualifies match: -scope.name\n' text += '# - Entire match of scope disqualifies match: -!scope.name\n' text += self.format_array('scope_filter', rule.get('scope_filter')) text += '\n# greedy (bool - default=True): Apply action to all instances (find all).\n' text += '# Used when "find" is defined.\n' text += self.format_bool('greedy', rule.get('greedy')) text += '\n# greedy_scope (bool - default=True): Find all the scopes specified by "scope."\n' text += self.format_bool('greedy_scope', rule.get('greedy_scope')) text += '\n# format_replace (bool - default=False): Use format string style replace templates.\n' text += '# Works only for Regex (with and without Backrefs) and Re (with Backrefs).\n' text += '# See https://facelessuser.github.io/backrefs/usage/#format-replacements for more info.\n' text += self.format_bool('format_replace', rule.get('format_replace')) text += '\n# selection_inputs (bool -default=False): Use selection for inputs into find pattern.\n' text += '# Global setting "selection_only" must be disabled for this to work.\n' text += self.format_bool('selection_inputs', rule.get('selection_inputs')) text += '\n# multi_pass (bool - default=False): Perform multiple sweeps on the scope region to find\n' text += '# and replace all instances of the regex when regex cannot be formatted to find\n' text += '# all instances. Since a replace can change a scope, this can be useful.\n' text += self.format_bool('multi_pass', rule.get('multi_pass')) text += '\n# plugin (str): Define replace plugin for more advanced replace logic.\n' text += self.format_string('plugin', rule.get('plugin')) text += '\n# args (dict): Arguments for \'plugin\'.\n' text += self.format_dict('args', rule.get('args')) text += '\n# ----------------------------------------------------------------------------------------\n' text += '# test: Here you can setup a test command. This is not saved and is just used for this session.\n' text += '# - replacements ([str]): A list of regex rules to sequence together.\n' text += '# - find_only (bool): Highlight current find results and prompt for action.\n' text += '# - action (str): Apply the given action (fold|unfold|mark|unmark|select).\n' text += '# This overrides the default replace action.\n' text += '# - options (dict): optional parameters for actions (see documentation for more info).\n' text += '# - key (str): Unique name for highlighted region.\n' text += '# - scope (str - default="invalid"): Scope name to use as the color.\n' text += '# - style (str - default="outline"): Highlight style (solid|underline|outline).\n' text += '# - multi_pass (bool): Repeatedly sweep with sequence to find all instances.\n' text += '# - no_selection (bool): Overrides the "selection_only" setting and forces no selections.\n' text += '# - regex_full_file_with_selections (bool): Apply regex search to full file then apply\n' text += '# action to results under selections.\n' text += textwrap.dedent( """\ test = { "replacements": [%s], "find_only": True, "action": None, "options": {}, "multi_pass": False, "no_selection": False, "regex_full_file_with_selections": False } """ % (self.simple_format_string(name) if name is not None else '')) replace_view = self.window.create_output_panel('reg_replace') replace_view.run_command('reg_replace_panel_insert', {'text': text}) for ext in ST_LANGUAGES: highlighter = sublime.load_settings( 'reg_replace.sublime-settings').get( 'python_highlighter', 'Python/Python') highlighter = 'Packages/' + highlighter + ext try: sublime.load_resource(highlighter) replace_view.set_syntax_file(highlighter) break except Exception: pass replace_view.settings().set('gutter', True) replace_view.settings().set('line_numbers', True) replace_view.settings().set('reg_replace.edit_view', True) replace_view.settings().set( 'bracket_highlighter.bracket_string_escape_mode', 'regex') replace_view.settings().set('regreplace.name', name) replace_view.sel().clear() replace_view.sel().add(sublime.Region(0, 0)) self.window.run_command("show_panel", {"panel": "output.reg_replace"}) sublime.set_timeout( lambda w=self.window, v=replace_view: w.focus_view(v), 100)