我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sublime.load_settings()。
def blink(times=4, delay=55): prefs = load_settings('Preferences.sublime-settings') if prefs.get('vintageous_visualbell') is False: return v = active_window().active_view() settings = v.settings() # Ensure we leave the setting as we found it. times = times if (times % 2) == 0 else times + 1 def do_blink(): nonlocal times if times > 0: settings.set('highlight_line', not settings.get('highlight_line')) times -= 1 set_timeout(do_blink, delay) do_blink()
def get_vhdl_setting(cmd_obj, key): ''' Borrowing an idea from OdatNurd from ST forum, creating a method that will return the value of a key and also check to see if it's been overridden in project files. Defaults are handled by the supplied sublime-settings file. This will actually work on the regular Preferences as well I think though might do bad things if the key doesn't exist. ''' # Load the defaults, or user overridden defaults. vhdl_settings = sublime.load_settings('vhdl_mode.sublime-settings') default = vhdl_settings.get(key, None) # Load the view's settings view_settings = cmd_obj.view.settings() return view_settings.get(key, default) #----------------------------------------------------------------------------
def run(self, edit): ''' Standard TextCommand Run Method ''' print('Preference Settings') print('vhdl-mode: {}: {}'.format('tab_size', util.get_vhdl_setting(self, 'tab_size'))) print('vhdl-mode: {}: {}'.format('translate_tabs_to_spaces', util.get_vhdl_setting(self, 'translate_tabs_to_spaces'))) vhdl_settings = sublime.load_settings('vhdl_mode.sublime-settings') keys = ['vhdl-user', 'vhdl-company', 'vhdl-project-name', 'vhdl-platform', 'vhdl-standard', 'vhdl-modified-time-string', 'vhdl-use-copyright-block', 'vhdl-use-revision-block', 'vhdl-copyright-block', 'vhdl-revision-block'] print('Package Settings') for key in keys: print('vhdl-mode: {}: "{}"'.format(key, vhdl_settings.get(key))) print('View Settings') for key in keys: print('vhdl-mode: {}: {}'.format(key, util.get_vhdl_setting(self, key)))
def fix_scheme_in_settings(settings_file,current_scheme, new_scheme, regenerate=False): """Change the color scheme in the given Settings to a background-corrected one""" from os.path import join, normpath, isfile settings = load_settings(settings_file) settings_scheme = settings.get("color_scheme") if current_scheme == settings_scheme: new_scheme_path = join(packages_path(), normpath(new_scheme[len("Packages/"):])) if isfile(new_scheme_path) and not regenerate: settings.set("color_scheme", new_scheme) else: generate_scheme_fix(current_scheme, new_scheme_path) settings.set("color_scheme", new_scheme) save_settings(settings_file) return True return False
def get_font_scale(self): """Get font scale.""" scale = 1.0 try: pref_scale = float(sublime.load_settings('Preferences.sublime-settings').get('mdpopups.font_scale', 0.0)) except Exception: pref_scale = 0.0 if sublime.platform() == 'windows' and pref_scale <= 0.0: try: import ctypes logpixelsy = 90 dc = ctypes.windll.user32.GetDC(0) height = ctypes.windll.gdi32.GetDeviceCaps(dc, logpixelsy) scale = float(height) / 96.0 ctypes.windll.user32.ReleaseDC(0, dc) except Exception: pass elif pref_scale > 0.0: scale = pref_scale return scale
def plugin_loaded(): global import_js_environment import_js_environment = dict(os.environ).copy() import_js_environment.update({ 'LC_ALL': 'en_US.UTF-8', 'LC_CTYPE': 'UTF-8', 'LANG': 'en_US.UTF-8', }) path_env_variable = extract_path() settings = sublime.load_settings('ImportJS.sublime-settings') setting_paths = settings.get('paths') if setting_paths: path_env_variable = ':'.join(setting_paths) + ':' + path_env_variable import_js_environment.update({ 'PATH': path_env_variable, }) print('ImportJS loaded with environment:') print(import_js_environment)
def run(self, edit): import cson, json # read data from view input = self.view.substr(sublime.Region(0, self.view.size())) data = Atom.read_cson(input) if data is False: return output = SublimeText.write_json(data) sort_keys = sublime.load_settings('Atomizr.sublime-settings').get("json_sort_keys") or True indent = sublime.load_settings('Atomizr.sublime-settings').get("json_indentation") or 2 selection = sublime.Region(0, self.view.size()) self.view.replace(edit, selection, json.dumps(output, sort_keys=sort_keys, indent=indent, separators=(',', ': '))) # set syntax to JSON Helpers.set_json(self) Helpers.rename_file(self, "sublime-completions") # Reset selection Helpers.reset_selection(self) # Converts Atom snippets (CSON into JSON)
def run(self, edit): import json # read data from view input = self.view.substr(sublime.Region(0, self.view.size())) data = VsCode.read_json(input) if data is False: return output = SublimeText.write_json(data) sort_keys = sublime.load_settings('Atomizr.sublime-settings').get("json_sort_keys") or True indent = sublime.load_settings('Atomizr.sublime-settings').get("json_indentation") or 2 # write converted data to view selection = sublime.Region(0, self.view.size()) self.view.replace(edit, selection, json.dumps(output, sort_keys=sort_keys, indent=indent)) # set syntax to JSON Helpers.set_json(self) Helpers.rename_file(self, "sublime-completions") Helpers.select_scope(self, "sublime", None)
def rename_file(self, extension): if sublime.load_settings('Atomizr.sublime-settings').get("rename_files") != True: return import os inputFile = self.view.window().active_view().file_name() parentDir = os.path.dirname(inputFile) baseName = os.path.splitext(os.path.basename(inputFile))[0] fileName = baseName + "." + extension outputFile = os.path.join(parentDir, fileName) os.rename(inputFile, outputFile) self.view.set_name(fileName) self.view.retarget(outputFile) self.view.window().run_command("save")
def load_history(rev=True, as_dict=False): """Returns list of past requests. Raises exception if history file doesn't exist. """ history_file = sublime.load_settings('Requester.sublime-settings').get('history_file', None) if not history_file: raise KeyError history_path = os.path.join(sublime.packages_path(), 'User', history_file) with open(history_path, 'r') as f: rh = json.loads(f.read() or '{}', object_pairs_hook=OrderedDict) if as_dict: return rh requests = list(rh.items()) if rev: requests.reverse() return requests
def run_initial_request(self, req, filename): requests_method = getattr(requests, req.method.lower()) try: res = requests_method(*req.args, stream=True, **req.kwargs) except Exception as e: sublime.error_message('Download Error: {}'.format(e)) return response = Response(req, res, None) self.handle_response(response) self.handle_responses([response]) self.persist_requests([response]) # persist initial request before starting download if res.status_code != 200: sublime.error_message( 'Download Error: response status code is not 200\n\n{}'.format(truncate(res.text, 500)) ) if sublime.load_settings('Requester.sublime-settings').get('only_download_for_200', True): return self.download_file(res, filename)
def sf_oauth2(): from .libs import auth settings = setting.load() default_project_value = settings["default_project_value"] is_sandbox = default_project_value["is_sandbox"] if refresh_token(): return server_info = sublime.load_settings("sfdc.server.sublime-settings") client_id = server_info.get("client_id") client_secret = server_info.get("client_secret") redirect_uri = server_info.get("redirect_uri") oauth = auth.SalesforceOAuth2(client_id, client_secret, redirect_uri, is_sandbox) authorize_url = oauth.authorize_url() print('authorize_url-->') print(authorize_url) start_server() open_in_default_browser(authorize_url)
def plugin_loaded(): global currentSettings, language, currentView currentSettings = sublime.load_settings(setting_file) language = currentSettings.get('language') currentView = sublime.active_window().active_view() docphpPath = getDocphpPath() if not os.path.isdir(docphpPath + 'language'): os.makedirs(docphpPath + 'language') if not callable(sublime_symbol.symbol_at_point) or not callable(sublime_symbol.navigate_to_symbol): sublime.error_message('Cannot find symbol_at_point from Default.sublime-package\n\nPlease restore the file which usually replaced by outdated localizations') from package_control import events if events.install(package_name) or not language: currentView.run_command('docphp_checkout_language', {"is_init": True, "set_fallback": True})
def load_settings(self, project_dir): project_setting_file = RemoteGDBSettings.project_setting_file(project_dir) if not os.path.exists(project_setting_file): return False try: with open(project_setting_file) as data_file: json_str = "" for line in data_file.readlines(): line = line.strip() if len(line) == 0: continue if line.startswith("//"): continue json_str += line json_str += "\n" self.data = json.loads(json_str) except Exception as err: print(err) # sublime.error_message("some errors exist in project setting file!") return False return True
def get(self, key, default_value=None): keys = key.split(".") try: res = self.data for item in keys: if item in res.keys(): res = res[item] else: raise if not res: return default_value return res except Exception: return sublime.load_settings("SublimeRemoteGDB.sublime-settings").get(key, default_value) return sublime.load_settings("SublimeRemoteGDB.sublime-settings").get(key, default_value)
def get_setting(key, default=None, view=None): return gdb_settings.get(key, default) try: if view is None: view = sublime.active_window().active_view() s = view.settings() # Try executable specific settings first if exec_settings and key in exec_settings: return exec_settings[key] # Then try user settings if s.has("sublimegdb_%s" % key): return s.get("sublimegdb_%s" % key) except: pass # Default settings return sublime.load_settings("SublimeGDB.sublime-settings").get(key, default)
def set_proper_scheme(view): ''' this is callback, it is not meant to be called directly view.settings().add_on_change('color_scheme', lambda: set_proper_scheme(view)) set once, right after view is created _note_, color_scheme must not be set directly, but in a setting file ''' # Since we cannot create file with syntax, there is moment when view has no settings, # but it is activated, so some plugins (e.g. Color Highlighter) set wrong color scheme if view.settings().get('outline_rename_mode', False): outline_settings = sublime.load_settings('outline-rename-mode.sublime-settings') else: outline_settings = sublime.load_settings('outline.sublime-settings') if view.settings().get('color_scheme') == outline_settings.get('color_scheme'): return view.settings().set('color_scheme', outline_settings.get('color_scheme'))
def refresh(self): self.settings = sublime.load_settings('github_issue.sublime-settings') for flag in ("token", "username", "password", "debug", "syntax", "git_path", "issue_title_completion", "user_completion", "label_completion", "commit_completion","split_line_width", "commit_completion_trigger", "disable_local_repositories", "wrap_width", "draw_centered", "disable_vintageous"): self.setting_dictionary[flag] = self.settings.get(flag) ## # @brief get corresponding parameters from Setting Object ## # @param self The object # @param flag configuration parameters # @param default The default value of flag ## # @return return setting_dictionary[flag] if it is valid otherwise return the default value. ##
def get_settings(): return sublime.load_settings('LuaFormat.sublime-settings')
def _set_generic_view_setting(view, name, value, opt, globally=False): if opt.scope == _SCOPE_VI_VIEW: name = 'vintageous_' + name if opt.parser: value = opt.parser(value) if not globally or (opt.scope not in (_SCOPE_VI_VIEW, _SCOPE_VI_WINDOW)): view.settings().set(name, value) else: prefs = load_settings('Preferences.sublime-settings') prefs.set(name, value) save_settings('Preferences.sublime-settings')
def outline_target(self): prefs = sublime.load_settings('Preferences.sublime-settings') if prefs.get('vintageous_visualyank') is False: return sels = list(self._view.sel()) sublime.set_timeout(lambda: self._view.erase_regions('vi_yy_target'), 350) self._view.add_regions('vi_yy_target', sels, 'comment', '', sublime.DRAW_NO_FILL)
def _update_ignored_packages(): # Updates the list of ignored packages with packages that are redundant, # obsolete, or cause problems due to conflicts e.g. Vintage, Vintageous, # etc. settings = sublime.load_settings('Preferences.sublime-settings') ignored_packages = settings.get('ignored_packages', []) conflict_packages = [x for x in ['Six', 'Vintage', 'Vintageous'] if x not in ignored_packages] if conflict_packages: print('NeoVintageous: update ignored packages with conflicts {}'.format(conflict_packages)) ignored_packages = sorted(ignored_packages + conflict_packages) settings.set('ignored_packages', ignored_packages) sublime.save_settings('Preferences.sublime-settings')
def get_setting(name): config = sublime.load_settings(CONFIG_NAME) setting = config.get(name, None) return setting
def restore_setting(name, value): config = sublime.load_settings(CONFIG_NAME) config.set(name, value) sublime.save_settings(CONFIG_NAME)
def get_pref(key): global_settings = sublime.load_settings(SETTINGS_FILE) value = global_settings.get(key) # Load active project settings project_settings = sublime.active_window().active_view().settings() # Overwrite global config value if it's defined if project_settings.has(PROJECT_NAME): value = project_settings.get(PROJECT_NAME).get(key, value) return value
def settings(self): return sublime.load_settings('PlotGraph.sublime-settings')
def __init__(self): self.settings = sublime.load_settings("ElixirTest.sublime-settings")
def load_config(self): s = sublime.load_settings("ElixirTest.sublime-settings") global MIX_TEST_FOLDER; MIX_TEST_FOLDER = s.get("mix_test_folder") global IGNORED_DIRECTORIES; IGNORED_DIRECTORIES = s.get("ignored_directories") global HIDE_PANEL; HIDE_PANEL = s.get("hide_panel") global BEFORE_CALLBACK; BEFORE_CALLBACK = s.get("before_callback") global AFTER_CALLBACK; AFTER_CALLBACK = s.get("after_callback") global COMMAND_PREFIX; COMMAND_PREFIX = False global SAVE_ON_RUN; SAVE_ON_RUN = s.get("save_on_run") global SYNTAX; SYNTAX = s.get('syntax') global THEME; THEME = s.get('theme') global TERMINAL_ENCODING; TERMINAL_ENCODING = s.get('terminal_encoding') mix = s.get("check_for_mix") #does nothing yet
def save_test_run(self, command, working_dir): s = sublime.load_settings("ElixirTest.last-run") s.set("last_test_run", command) s.set("last_test_working_dir", working_dir) sublime.save_settings("ElixirTest.last-run")
def load_last_run(self): self.load_config() self.save_all() s = sublime.load_settings("ElixirTest.last-run") return (s.get("last_test_run"), s.get("last_test_working_dir"))
def log(cls, string): """ Log string to sublime text console if debug is enabled """ if not hasattr(cls, "enabled"): settings = sublime.load_settings('TerminalView.sublime-settings') cls.enabled = settings.get("terminal_view_print_debug", False) if cls.enabled: prefix = "[terminal_view debug] [%.3f] " % (time.time()) print(prefix + string)
def __init__(self, sublime_view, title, syntax_file=None): self._view = sublime_view self._view.set_name(title) self._view.set_scratch(True) self._view.set_read_only(True) self._view.settings().set("gutter", False) self._view.settings().set("highlight_line", False) self._view.settings().set("auto_complete_commit_on_tab", False) self._view.settings().set("draw_centered", False) self._view.settings().set("word_wrap", False) self._view.settings().set("auto_complete", False) self._view.settings().set("draw_white_space", "none") self._view.settings().set("draw_indent_guides", False) self._view.settings().set("caret_style", "blink") self._view.settings().set("scroll_past_end", False) self._view.settings().add_on_change('color_scheme', lambda: set_color_scheme(self._view)) if syntax_file is not None: self._view.set_syntax_file("Packages/User/" + syntax_file) # Mark in the views private settings that this is a terminal view so we # can use this as context in the keymap self._view.settings().set("terminal_view", True) settings = sublime.load_settings('TerminalView.sublime-settings') self._show_colors = settings.get("terminal_view_show_colors", False) self._right_margin = settings.get("terminal_view_right_margin", 3) self._bottom_margin = settings.get("terminal_view_bottom_margin", 0) # Use pyte as underlying terminal emulator hist = settings.get("terminal_view_scroll_history", 1000) ratio = settings.get("terminal_view_scroll_ratio", 0.5) self._term_emulator = pyte_terminal_emulator.PyteTerminalEmulator(80, 24, hist, ratio) self._keypress_callback = None self._view_content_cache = sublime_view_cache.SublimeViewContentCache() self._view_region_cache = sublime_view_cache.SublimeViewRegionCache() # Register the new instance of the sublime buffer class so other # commands can look it up when they are called in the same sublime view SublimeBufferManager.register(sublime_view.id(), self)
def __init__(self): active_view = sublime.active_window().active_view() self.user_settings = sublime.load_settings("CommandBox.sublime-settings") self.sources = [active_view.settings(), ProjectData(), self.user_settings]
def get_settings(): return sublime.load_settings(SETTINGS)
def is_ignored(): preferences = sublime.load_settings('Preferences.sublime-settings') if PKG in preferences.get('ignored_packages'): return True return False
def is_installed_by_package_control(): settings = sublime.load_settings('Package Control.sublime-settings') return str(__pc_name__ in set(settings.get('installed_packages', [])))
def get_current_theme(): return sublime.load_settings('Preferences.sublime-settings').get('theme')
def run(self): """Run the command.""" base_path = os.path.join(sublime.packages_path(), 'User', '*.tmTheme') sublime_path = os.path.join(sublime.packages_path(), 'User', 'SublimeLinter', '*.tmTheme') themes = glob(base_path) + glob(sublime_path) prefs = sublime.load_settings('Preferences.sublime-settings') scheme = prefs.get('color_scheme') for theme in themes: # Ensure it is a (SL) theme and it is not current current scheme if re.search(r'\(SL\)', theme) and os.path.normpath(scheme) not in theme: persist.debug('deleting {}'.format(os.path.split(theme)[1])) os.remove(theme)
def observe(self, observer=None): """Observer changes to the plugin settings.""" self.plugin_settings = sublime.load_settings('SublimeLinter.sublime-settings') self.plugin_settings.clear_on_change('sublimelinter-persist-settings') self.plugin_settings.add_on_change('sublimelinter-persist-settings', observer or self.on_update)
def settings(): """Shortcut to the settings""" return load_settings("GutterColor.sublime-settings")
def __init__(self, view, region, file_id): self.generate_webcolors() self.view = view self.region = region self.file_id = file_id self.settings = load_settings("GutterColor.sublime-settings") self.text = self.view.substr(self.region)
def parse_global(self): """Parse global settings.""" color_settings = {} for item in self.csm.plist_file["settings"]: if item.get('scope', None) is None and item.get('name', None) is None: color_settings = item["settings"] break # Get general theme colors from color scheme file self.bground = self.strip_color(color_settings.get("background", '#FFFFFF'), simple_strip=True) rgba = RGBA(self.bground) self.lums = rgba.get_luminance() is_dark = self.lums <= LUM_MIDPOINT settings = sublime.load_settings("Preferences.sublime-settings") self.variables = { "is_dark": is_dark, "is_light": not is_dark, "sublime_version": int(sublime.version()), "mdpopups_version": ver.version(), "color_scheme": self.scheme_file, "use_pygments": not settings.get('mdpopups.use_sublime_highlighter', False), "default_formatting": settings.get('mdpopups.default_formatting', True) } self.html_border = rgba.get_rgb() self.fground = self.strip_color(color_settings.get("foreground", '#000000')) # Intialize colors with the global foreground, background, and fake html_border self.colors = OrderedDict() self.colors['.foreground'] = OrderedDict([('color', 'color: %s; ' % self.fground)]) self.colors['.background'] = OrderedDict([('background-color', 'background-color: %s; ' % self.bground)])
def _get_setting(name, default=None): """Get the Sublime setting.""" return sublime.load_settings('Preferences.sublime-settings').get(name, default)
def _get_scheme(view): """Get the scheme object and user CSS.""" scheme = view.settings().get('color_scheme') settings = sublime.load_settings("Preferences.sublime-settings") obj = None user_css = '' if scheme is not None: if scheme in _scheme_cache: obj, user_css, t = _scheme_cache[scheme] # Check if cache expired or user changed pygments setting. if ( _is_cache_expired(t) or obj.variables.get('use_pygments', True) != (not settings.get(HL_SETTING, False)) or obj.variables.get('default_formatting', True) != settings.get(FORMAT_SETTING, True) ): obj = None user_css = '' if obj is None: try: obj = Scheme2CSS(scheme) _prune_cache() user_css = _get_user_css() _scheme_cache[scheme] = (obj, user_css, time.time()) except Exception: _log('Failed to convert/retrieve scheme to CSS!') _debug(traceback.format_exc(), ERROR) return obj, user_css
def get_language_from_view(view): """Guess current language from view.""" lang = None user_map = sublime.load_settings('Preferences.sublime-settings').get('mdpopups.sublime_user_lang_map', {}) syntax = os.path.splitext(view.settings().get('syntax').replace('Packages/', '', 1))[0] keys = set(list(lang_map.keys()) + list(user_map.keys())) for key in keys: v1 = lang_map.get(key, (tuple(), tuple()))[1] v2 = user_map.get(key, (tuple(), tuple()))[1] if syntax in (tuple(v2) + v1): lang = key break return lang
def get_setting(key, default=None): settings = sublime.load_settings('Terminal.sublime-settings') os_specific_settings = {} if os.name == 'nt': os_specific_settings = sublime.load_settings('Terminal (Windows).sublime-settings') elif os.name == 'darwin': os_specific_settings = sublime.load_settings('Terminal (OSX).sublime-settings') else: os_specific_settings = sublime.load_settings('Terminal (Linux).sublime-settings') return os_specific_settings.get(key, settings.get(key, default))
def get_setting(key, default): old_settings = sublime.load_settings("Preferences.sublime-settings") new_settings = sublime.load_settings("Tern.sublime-settings") setting = new_settings.get(key, None) if setting is None: return old_settings.get(key, default) else: return new_settings.get(key, default)
def on_hover(self, view, point, hover_zone): if "PHP" not in view.settings().get('syntax'): return self.settings = sublime.load_settings('CompletePHP.sublime-settings') if self.settings.get('showInlineDocsOnHover') == False: return if hover_zone != sublime.HOVER_TEXT: return wordregion = view.word(point) word = view.substr(wordregion).lower() print(word) self.show_doc_popup(view, point, word)
def get_settings(self, view, key, default=None): """Get user settings for key. Combine SwiftKitten package settings with project settings """ settings = load_settings("SwiftKitten.sublime-settings") project_data = view.window().project_data() return project_data.get(key, settings.get(key, default))