本文整理汇总了Python中sublime.encode_value函数的典型用法代码示例。如果您正苦于以下问题:Python encode_value函数的具体用法?Python encode_value怎么用?Python encode_value使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了encode_value函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:programadorsito,项目名称:SublimeXml,代码行数:7,代码来源:xml.py
示例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()
开发者ID:yungsters,项目名称:SublimeNodeServer,代码行数:25,代码来源:SublimeNodeServer.py
示例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')
开发者ID:dinfekted,项目名称:sublime-keyword,代码行数:34,代码来源:keyword.py
示例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'),
})
开发者ID:rust-lang,项目名称:sublime-rust,代码行数:31,代码来源:cargo_config.py
示例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
开发者ID:facelessuser,项目名称:ThemeTweaker,代码行数:60,代码来源:theme_tweaker.py
示例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)
开发者ID:facelessuser,项目名称:ThemeTweaker,代码行数:33,代码来源:theme_tweaker.py
示例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))
开发者ID:chmln,项目名称:sublime-text-theme-switcher-menu,代码行数:29,代码来源:theme_switcher.py
示例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()
开发者ID:mkeeler,项目名称:Project-Manager,代码行数:7,代码来源:pm.py
示例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)
开发者ID:bofm,项目名称:sublime-a-file-icon,代码行数:31,代码来源:themes.py
示例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()
开发者ID:xiamizy,项目名称:Javatar,代码行数:34,代码来源:javatar_utils.py
示例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)))
开发者ID:LaTeXing,项目名称:LaTeXing,代码行数:8,代码来源:cache.py
示例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"))
开发者ID:ckeyer,项目名称:sublime-config,代码行数:9,代码来源:jsonclient.py
示例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
开发者ID:huot25,项目名称:StyledPopup,代码行数:9,代码来源:styled_popup.py
示例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)
开发者ID:SublimeText,项目名称:PackageDev,代码行数:9,代码来源:known_settings.py
示例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()
开发者ID:programadorsito,项目名称:Packages,代码行数:10,代码来源:abrir.py
示例16: request
def request(self, method, url, params=None, body=None, headers=None, raw_response=False, as_json=False):
try:
import ssl
pool_manager = PoolManager(
num_pools=4,
maxsize=8,
block=False,
timeout=60.0,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=GDriveUtil.get_cert_file(),
ssl_version=ssl.PROTOCOL_TLSv1,
)
except (ImportError):
pool_manager = PoolManager(
num_pools=4,
maxsize=8,
block=False,
timeout=60.0,
)
params = params or {}
headers = headers or {}
headers["User-Agent"] = "DrSync/0.1"
if params:
if body:
raise ValueError("body parameter cannot be used with params parameter")
if as_json:
body = sublime.encode_value(params)
headers["Content-type"] = "application/json"
headers["Content-Length"] = len(body)
else:
body = urllib.parse.urlencode(params)
headers["Content-type"] = "application/x-www-form-urlencoded"
if hasattr(body, "getvalue"):
body = str(body.getvalue())
headers["Content-Length"] = len(body)
if hasattr(body, "read"):
headers["Content-Length"] = len(body.read())
for key, value in headers.items():
if type(value) == str and "\n" in value:
raise ValueError("headers should not contain newlines (" + key + ": " + value + ")")
try:
response = pool_manager.urlopen(method=method, url=url, body=body, headers=headers, preload_content=False)
except socket.error as e:
raise SocketError(url, e)
except exceptions.SSLError as e:
raise SocketError(url, "SSL certificate error: %s" % e)
if response.status != 200:
raise ErrorResponse(response, response.read())
return {"headers": response.headers, "data": self.process_response(response, raw_response)}
开发者ID:spywhere,项目名称:DrSync,代码行数:55,代码来源:gdrive_connection.py
示例17: send_command
def send_command(self, callback, **data):
"""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'))
开发者ID:Cesar456,项目名称:Sublime_Text3_Properties-Pacage,代码行数:11,代码来源:jsonclient.py
示例18: __overwrite
def __overwrite(self):
import os
cur_name = self.get_current_settings()
contents = self.get_settings_contents()
current_content = contents[cur_name]
preferences = os.path.join(sublime.packages_path(), 'User', 'Preferences.sublime-settings')
with open(preferences, mode='w') as f:
f.write(sublime.encode_value(current_content, True))
return True
开发者ID:t8m8,项目名称:SwitchSettings,代码行数:11,代码来源:switch_settings_core.py
示例19: _key_snippet
def _key_snippet(key, value, bol="", eol=",\n"):
"""Create snippet with default value depending on type.
Arguments:
key (string):
the settings key name
value (any):
the default value of the setting read from base file
bol (string):
the prefix to add to the beginning of line
eol (string):
the suffix to add to the end of line
Returns:
string: the contents field to insert into completions entry
"""
encoded = sublime.encode_value(value)
encoded = encoded.replace("\\", "\\\\") # escape snippet markers
encoded = encoded.replace("$", "\\$")
encoded = encoded.replace("}", "\\}")
if isinstance(value, str):
# create the snippet for json strings and exclude quotation marks
# from the input field {1:}
#
# "key": "value"
#
fmt = '{bol}"{key}": "${{1:{encoded}}}"{eol}'
encoded = encoded[1:-1] # strip quotation
elif isinstance(value, list):
# create the snippet for json lists and exclude brackets
# from the input field {1:}
#
# "key":
# [
# value
# ]
#
fmt = '{bol}"{key}":\n[\n\t${{1:{encoded}}}\n]{eol}'
encoded = encoded[1:-1] # strip brackets
elif isinstance(value, dict):
# create the snippet for json dictionaries braces
# from the input field {1:}
#
# "key":
# {
# value
# }
#
fmt = '{bol}"{key}":\n{{\n\t${{1:{encoded}}}\n}}{eol}'
encoded = encoded[1:-1] # strip braces
else:
fmt = '{bol}"{key}": ${{1:{encoded}}}{eol}'
return fmt.format(**locals())
开发者ID:SublimeText,项目名称:PackageDev,代码行数:54,代码来源:known_settings.py
示例20: on_done
def on_done(i):
if i < 0:
return
key = items[i]
value = CACHE.cache_data[key]
view = self.window.new_file()
view.set_name("temp::" + key)
view.set_scratch(True)
view.set_read_only(True)
view.run_command("ltx_append_text", {"string": sublime.encode_value(value, True)})
view.run_command("ltx_select_point", {"point": 0})
开发者ID:LaTeXing,项目名称:LaTeXing,代码行数:11,代码来源:cache.py
注:本文中的sublime.encode_value函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论