本文整理汇总了Python中sublime.encode_value函数的典型用法代码示例。如果您正苦于以下问题:Python encode_value函数的具体用法?Python encode_value怎么用?Python encode_value使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了encode_value函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: guardar
def guardar(self):
archivo=open(self.rutaArchivo, "w")
d={}
d["tags"]=self.tags
d["attrs"]=self.attrs
archivo.write(sublime.encode_value(d, True))
archivo.close()
示例2: run
def run(self):
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
end_time = time.time() + SublimeNodeClient.CONNECT_TIMEOUT
while not self.connected:
remaining_time = end_time - time.time()
if remaining_time < 0:
raise Exception(
"Unable to connect to `{0}`".format(self.server_address)
)
try:
client.connect(self.server_address)
self.connected = True
except (ConnectionRefusedError, FileNotFoundError):
pass
while self.connected:
while not self.queue.empty():
(message, callback) = self.queue.get()
encoded = sublime.encode_value(message) + "\n"
client.send(bytes(encoded, "utf-8"))
if callback:
sublime.set_timeout(callback, 0)
time.sleep(SublimeNodeClient.BRIDGE_THROTTLE)
client.close()
示例3: _write_aliases
def _write_aliases(self, aliases):
view = None
for current_view in sublime.active_window().views():
if current_view.file_name().endswith('.sublime-project'):
view = current_view
break
if view == None:
raise Exception('Project settings not found')
raw_settings = view.substr(sublime.Region(0, view.size()))
root_settings = sublime.decode_value(raw_settings)
if 'settings' not in root_settings:
root_settings['settings'] = {}
settings = root_settings['settings']
for keyword in aliases:
key = 'keyword.' + keyword
if key not in settings:
settings[key] = {}
if 'aliases' not in settings[key]:
settings[key]['aliases'] = {}
settings[key]['aliases'].update(aliases[keyword])
args = {
'region': [0, view.size()],
'text': sublime.encode_value(root_settings)
}
view.run_command('replace_region', args)
view.run_command('pretty_json')
view.run_command('save')
示例4: done
def done(self):
view = self.window.new_file()
view.set_scratch(True)
default = self.get_setting('env')
template = util.multiline_fix("""
// Enter environment variables here in JSON syntax.
// Close this view when done to commit the settings.
""")
if 'contents' in self.cmd_input:
# Used when parsing fails to attempt to edit again.
template = self.cmd_input['contents']
elif default:
template += sublime.encode_value(default, True)
else:
template += util.multiline_fix("""
{
// "RUST_BACKTRACE": "1"
}
""")
# Unfortunately Sublime indents on 'insert'
view.settings().set('auto_indent', False)
view.run_command('insert', {'characters': template})
view.settings().set('auto_indent', True)
view.set_syntax_file('Packages/JavaScript/JSON.sublime-syntax')
view.settings().set('rust_environment_editor', True)
view.settings().set('rust_environment_editor_settings', {
'package': self.choices.get('package'),
'which': self.choices['which'],
'variant': self.choices.get('variant'),
'target': self.choices.get('target'),
})
示例5: _theme_valid
def _theme_valid(self, scheme_file, noedit=False):
"""Check if theme is valid."""
is_working = scheme_file.startswith(TEMP_PATH + '/')
if (
is_working and self.scheme_map is not None and
self.scheme_map["working"] == scheme_file and
self._exists(self.scheme_map["original"])
):
if self._exists(self.scheme_map["working"]):
self.scheme_file = packages_path(self.scheme_map["original"])
self.scheme_clone = packages_path(self.scheme_map["working"])
else:
# Recover from missing temp
log("Revert to original because temp is missing")
if self.set_safe:
self._set_theme_safely(self.scheme_map["original"])
else:
self.settings.set(SCHEME, self.scheme_map["original"])
self.scheme_map["redo"] = ""
self.scheme_map["undo"] = ""
self.p_settings["scheme_map"] = self.scheme_map
self._save_tweak_settings()
return True
elif not is_working and not noedit:
self._ensure_temp()
csm = ColorSchemeMatcher(scheme_file)
content = get_tmtheme(csm.get_scheme_obj()) if not NEW_SCHEMES else csm.get_scheme_obj()
self.scheme_file = packages_path(scheme_file)
base, old_ext = splitext(basename(scheme_file))
if NEW_SCHEMES:
ext = '.hidden-color-scheme' if old_ext == '.hidden-color-scheme' else '.sublime-color-scheme'
else:
ext = '.tmTheme'
self.scheme_clone = packages_path(join(normpath(TEMP_PATH), 'tweak-' + base + ext))
try:
if NEW_SCHEMES:
with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f:
f.write(sublime.encode_value(content, pretty=True))
else:
with open(self.scheme_clone, "wb") as f:
f.write(writePlistToBytes(content))
self.scheme_map = {
"original": scheme_file,
"working": "%s/%s" % (TEMP_PATH, 'tweak-' + base + ext),
"undo": "",
"redo": ""
}
self.set_tweaked_scheme = {
"set_safe": self.set_safe,
"scheme": self.scheme_map["working"],
}
self.p_settings["scheme_map"] = self.scheme_map
self._save_tweak_settings()
return True
except Exception as e:
log(e)
sublime.error_message("Cannot clone theme")
return False
return False
示例6: clear
def clear(self):
"""Clear tweaks."""
if not self._lock():
log('Failed to acquire lock!')
return
self._setup(noedit=True)
if self.theme_valid:
csm = ColorSchemeMatcher(self.scheme_map["original"])
content = self._get_tmtheme(csm.get_scheme_obj()) if not NEW_SCHEMES else csm.get_scheme_obj()
if NEW_SCHEMES:
with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f:
f.write(sublime.encode_value(content, pretty=True))
self.scheme_map["redo"] = ""
self.scheme_map["undo"] = ""
self.p_settings["scheme_map"] = self.scheme_map
self._save_tweak_settings()
else:
with open(self.scheme_clone, "wb") as f:
f.write(writePlistToBytes(content))
self.scheme_map["redo"] = ""
self.scheme_map["undo"] = ""
self.p_settings["scheme_map"] = self.scheme_map
self._save_tweak_settings()
if self.set_tweaked_scheme:
sublime.set_timeout(self._set_tweaked_scheme, 300)
else:
Lock.release_lock()
else:
Lock.release_lock()
log("Theme has not been tweaked!", status=True)
示例7: run
def run(self):
"""API entry point to rebuild main menu."""
# create cache directory
cache_path = menu_cache_path()
if not os.path.isdir(cache_path):
os.makedirs(cache_path)
# build main menu structure
menu = [{
"id": "preferences",
"children": [{
"caption": "Theme",
"children": self.create_menu(
"switch_theme", ["*.sublime-theme"], "themes_exclude")
}]
}]
if _HAVE_ST_UI:
# ST3127+ no longer provides its own "Color Scheme" sub menu.
menu[0]["children"].insert(0, {
"caption": "Color Scheme",
"children": self.create_menu(
"switch_color_scheme",
["*.sublime-color-scheme", "*.tmTheme"],
"colors_exclude"
)
})
# save main menu to file
cache_path = os.path.join(cache_path, "Main.sublime-menu")
with open(cache_path, "w", encoding="utf-8") as menu_file:
menu_file.write(sublime.encode_value(menu, False))
示例8: save
def save(self, data, indent=4):
self.fdir = os.path.dirname(self.fpath)
if not os.path.isdir(self.fdir):
os.makedirs(self.fdir)
f = codecs.open(self.fpath, "w+", encoding=self.encoding)
f.write(sublime.encode_value(data, True))
f.close()
示例9: _patch_general
def _patch_general(themes, dest, isettings):
theme_content = []
color = isettings.get("color")
opacity = isettings.get("opacity")
size = isettings.get("size")
row_padding = isettings.get("row_padding")
if color or opacity or size or row_padding:
icon = _patch_icon(None, color, opacity)
if size:
icon["content_margin"] = [size, size]
if row_padding:
icon["row_padding"] = row_padding
theme_content.append(icon)
color = isettings.get("color_on_hover")
opacity = isettings.get("opacity_on_hover")
if color or opacity:
theme_content.append(_patch_icon("hover", color, opacity))
color = isettings.get("color_on_select")
opacity = isettings.get("opacity_on_select")
if color or opacity:
theme_content.append(_patch_icon("selected", color, opacity))
text = sublime.encode_value(theme_content)
for theme in themes:
log("Patching `{}`".format(theme))
with open(os.path.join(dest, theme), "w") as t:
t.write(text)
示例10: run
def run(self, edit, type="", text="", region=None, dest=None):
if type == "insert":
self.view.insert(edit, 0, text)
elif type == "add":
self.view.insert(edit, self.view.size(), text)
elif type == "replace":
self.view.insert(edit, region, text)
elif type == "set_read_only":
self.view.set_read_only(True)
elif type == "test":
if not isStable():
self.view.show_popup_menu(["A", "B"], self.nothing)
elif type == "remote_hash":
if not isStable():
sublime.active_window().show_input_panel("URL:", "", self.remote_hash, None, None)
elif type == "hash":
if not isStable():
print(hashlib.sha256(self.view.substr(sublime.Region(0,self.view.size())).encode("utf-8")).hexdigest())
elif type == "tojson":
if not isStable():
jsonObj = sublime.decode_value(self.view.substr(sublime.Region(0,self.view.size())))
self.view.replace(edit, sublime.Region(0,self.view.size()), sublime.encode_value(jsonObj, True));
elif type == "reload":
if isDebug():
getAction().addAction("javatar.command.utils.reload", "Reload Javatar")
print("Reloading Javatar...")
import sys
from imp import reload
for mod in sys.modules:
if mod.lower().startswith("javatar") and not mod.lower().endswith("_utils") and sys.modules[mod] is not None:
print("Reloading module " + mod + "...")
reload(sys.modules[mod])
from ..Javatar import plugin_loaded
plugin_loaded()
示例11: save
def save():
for file_name in mode if mode else CACHE_NAMES:
if file_name in self.cache_data:
str_json = sublime.encode_value(self.cache_data[file_name])
with open(os.path.join(sublime.cache_path(), "LaTeXing", file_name), 'w', encoding="utf-8") as f:
log.trace("%s", f)
f.write(str_json)
log.info("%s (%s)" % (file_name, tools.size_of_string(str_json)))
示例12: send_command
def send_command(self, callback: Callable, **data: Any) -> None:
"""Send the given command that should be handled bu the given callback
"""
data["uid"] = self.add_callback(callback)
try:
self.push(bytes("{}\r\n".format(sublime.encode_value(data)), "utf8"))
except NameError:
self.push(bytes("{}\r\n".format(json.dumps(data)), "utf8"))
示例13: save_stylesheets
def save_stylesheets(self, style_sheets):
"""Save the stylesheet dictionary to file"""
content = sublime.encode_value(style_sheets, True)
with open(self.theme_file_path, "w") as f:
f.write(content)
self.style_sheets = style_sheets
示例14: format_completion_item
def format_completion_item(value, default=False):
"""Create a completion item with its type as description."""
if isinstance(value, dict):
raise ValueError("Cannot format dictionary value", value)
default_str = "(default) " if default else ""
return ("{0} \t{2}{1}".format(sublime.encode_value(value).strip('"'),
type(value).__name__,
default_str),
value)
示例15: configurarCadena
def configurarCadena(self, cadena):
comando={}
if self.lenguaje=="plsql":
comando["cmd"]=["sqlplus", cadena, "@", "$file"]
comando["selector"]="source.plsql"
comando=sublime.encode_value(comando, True)
ruta=os.path.join(sublime.packages_path(), "user", self.lenguaje+".sublime-build")
archivo=open(ruta, "w")
archivo.write(comando)
archivo.close()