def generate_scheme_fix(old_scheme, new_scheme_path):
"""Appends background-correction XML to a color scheme file"""
from os.path import join
from re import sub
UUID_REGEX = '[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}'
with open(join(packages_path(),current_directory(),'background_fix.xml')) as f:
xml = f.read()
scheme_data = load_resource(old_scheme) # only valid for ST3 API!
insertion_point = scheme_data.rfind("</array>")
new_scheme_data = scheme_data[:insertion_point] + xml + scheme_data[insertion_point:]
def uuid_gen(args):
from uuid import uuid4
return str(uuid4())
new_scheme_data = sub(UUID_REGEX, uuid_gen, new_scheme_data)
with open(new_scheme_path, "wb") as f:
f.write(new_scheme_data.encode("utf-8"))
python类load_resource()的实例源码
def read_css(self, css):
"""Read the CSS file."""
try:
var = copy.copy(self.variables)
var.update(
{
'is_phantom': self.css_type == PHANTOM,
'is_popup': self.css_type == POPUP
}
)
return self.env.from_string(
clean_css(sublime.load_resource(css))
).render(var=var, colors=self.colors, plugin=self.plugin_vars)
except Exception:
return ''
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 ''
##############################
# Markdown parsing
##############################
def _get_theme(view, css=None, css_type=POPUP, template_vars=None):
"""Get the theme."""
global base_css
if base_css is None:
base_css = clean_css(sublime.load_resource(BASE_CSS))
obj, user_css = _get_scheme(view)
font_size = view.settings().get('font_size', 12)
try:
return obj.apply_template(
base_css +
obj.get_css() +
(clean_css(css) if css else '') +
user_css,
css_type,
font_size,
template_vars
) if obj is not None else ''
except Exception:
_log('Failed to retrieve scheme CSS!')
_debug(traceback.format_exc(), ERROR)
return ''
def read_css(self, css):
"""Read the CSS file."""
try:
var = copy.copy(self.variables)
var.update(
{
'is_phantom': self.css_type == PHANTOM,
'is_popup': self.css_type == POPUP
}
)
return self.env.from_string(
clean_css(sublime.load_resource(css))
).render(var=var, colors=self.colors, plugin=self.plugin_vars)
except Exception:
return ''
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:
pass
return css if css else ''
##############################
# Markdown parsing
##############################
def _get_theme(view, css=None, css_type=POPUP, template_vars=None):
"""Get the theme."""
global base_css
if base_css is None:
base_css = clean_css(sublime.load_resource(BASE_CSS))
obj, user_css, default_css = _get_scheme(view)
font_size = view.settings().get('font_size', 12)
try:
return obj.apply_template(
base_css +
default_css +
obj.get_css() +
(clean_css(css) if css else '') +
user_css,
css_type,
font_size,
template_vars
) if obj is not None else ''
except Exception:
_log('Failed to retrieve scheme CSS!')
_debug(traceback.format_exc(), ERROR)
return ''
def formatPopup(self, content, symbol, can_back=False):
if not isinstance(content, str):
return
content = decodeEntity(content)
parser = PopupHTMLParser(symbol, language, can_back)
try:
parser.feed(content)
except FinishError:
pass
content = parser.output
content = '<style>'+sublime.load_resource('Packages/' + package_name + '/style.css') + \
'</style><div id="outer"><div id="container">' + content + "</div></div>"
content = re.sub('<strong><code>([A-Z_]+)</code></strong>', '<strong><code><a class="constant" href="constant.\\1">\\1</a></code></strong>', content)
return content
def get_missing(theme_package):
missing_icons = []
all_icons = sublime.find_resources("*.png")
package_icons = json.loads(sublime.load_resource("Packages/" +
settings.PACKAGE_NAME +
"/common/icons.json"))
theme_icons_path = get_path(theme_package)
theme_icons = [
os.path.basename(os.path.splitext(i)[0])
for i in all_icons if i.startswith(theme_icons_path)
]
for icon in package_icons:
if icon not in theme_icons:
missing_icons.append(icon)
return missing_icons
def run(self):
view = self.window.new_file()
view.set_name("{} – Changelog".format(settings.PACKAGE_NAME))
view.settings().set("gutter", False)
view.settings().set("line_numbers", False)
view.settings().set("caret_extra_top", 0)
view.settings().set("caret_extra_bottom", 0)
view.settings().set("caret_extra_width", 0)
html = str(sublime.load_resource(
"Packages/{}/.sublime/CHANGELOG.html".format(settings.PACKAGE_NAME)
))
view.add_phantom(
"afi_changelog",
sublime.Region(0),
html,
sublime.LAYOUT_INLINE,
on_navigate=self.on_navigate
)
view.set_read_only(True)
view.set_scratch(True)
def read_css(self, css):
"""Read the CSS file."""
try:
var = copy.copy(self.variables)
var.update(
{
'is_phantom': self.css_type == PHANTOM,
'is_popup': self.css_type == POPUP
}
)
return self.env.from_string(
clean_css(sublime.load_resource(css))
).render(var=var, colors=self.colors, plugin=self.plugin_vars)
except Exception:
return ''
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 ''
##############################
# Markdown parsing
##############################
def _get_theme(view, css=None, css_type=POPUP, template_vars=None):
"""Get the theme."""
global base_css
if base_css is None:
base_css = clean_css(sublime.load_resource(BASE_CSS))
obj, user_css = _get_scheme(view)
font_size = view.settings().get('font_size', 12)
try:
return obj.apply_template(
base_css +
obj.get_css() +
(clean_css(css) if css else '') +
user_css,
css_type,
font_size,
template_vars
) if obj is not None else ''
except Exception:
_log('Failed to retrieve scheme CSS!')
_debug(traceback.format_exc(), ERROR)
return ''
def load_help(pkg_info, help_file):
"""
Load and return the contents of the help file with the given name from the
provided package. The help file name should be relative to the set document
root for the package given.
Returns the contents of the help file or None.
"""
try:
return sublime.load_resource("%s/%s" % (pkg_info.doc_root, help_file))
except:
pass
return None
def set_color_scheme(view):
"""
Set color scheme for view
"""
color_scheme = "Packages/TerminalView/TerminalView.hidden-tmTheme"
# Check if user color scheme exists
try:
sublime.load_resource("Packages/User/TerminalView.hidden-tmTheme")
color_scheme = "Packages/User/TerminalView.hidden-tmTheme"
except:
pass
if view.settings().get('color_scheme') != color_scheme:
view.settings().set('color_scheme', color_scheme)
def show_doc_popup(self, view, point, word):
if not word in functions:
return
max_width, max_height = 600, 300
word = word.replace("_","-")
filepath = re.sub("{{.*?}}",word,self.settings.get('pathToPHPDocs'))
print(filepath)
html_file = filepath
html_str = sublime.load_resource(html_file)
html_str = re.sub("<!DOCTYPE.*?>","",html_str)
#strip Meta tag
html_str = re.sub("<meta .*?>","",html_str)
#remove entities that python has trouble with from what I saw
html_str = re.sub("—","-",html_str)
html_str = re.sub(""",'"',html_str)
html_str = re.sub("'","'",html_str)
html_str = re.sub("»","»",html_str)
#replace &$ with entity many functions had this
html_str = re.sub("&\$","&$",html_str)
#remove all spans
html_str = re.sub("<span.*?>(.*?)</span>",r"\1",html_str)
html_str = re.sub("<head>","",html_str)
html_str = re.sub("</head>","",html_str)
view.show_popup(html_str,
sublime.HIDE_ON_MOUSE_MOVE_AWAY,
point,
max_width,
max_height,
lambda s: self.on_navigate(s, view, point),
)
print("here")
def load_css(self):
"""
Loads CSS from file and stores it as object property.
"""
settings = sublime.load_settings("RegexExplainTip.sublime-settings")
css_file = settings.get("css_file")
self.observe_settings()
try:
self.css = sublime.load_resource(css_file).replace("\r", "")
except IOError:
self.css = ""
print("RegexExplainTip:\nSpecified file: '%s' does not seem to exists." % css_file)
def __load_resources(self):
"""Load Vale's static resources.
"""
self.error_template = sublime.load_resource(
self.settings.get('vale_error_template'))
self.warning_template = sublime.load_resource(
self.settings.get('vale_warning_template'))
self.info_template = sublime.load_resource(
self.settings.get('vale_info_template'))
self.css = sublime.load_resource(self.settings.get('vale_css'))
def open_doc(self, json_path, prefix_url):
doc_dict = json.loads(sublime.load_resource(json_path))
doc_list = list(doc_dict.keys())
doc_list = sorted(doc_list)
show_list = copy.copy(doc_list)
for i in range(len(show_list)):
api = doc_list[i]
info = doc_dict[api]
show_list[i] = '%s (%s)' % (api, info['desc'])
def on_done(index):
if index == -1: return
api = doc_list[index]
info = doc_dict[api]
url = prefix_url + info['href']
open_url(url)
window = sublime.active_window()
window.show_quick_panel(show_list, on_done)
# ----------------------------------------------------------
# Commands
# ----------------------------------------------------------
def _get_default_css():
"""Get default CSS."""
return clean_css(sublime.load_resource(DEFAULT_CSS))
def get_scratch_view_from_resource(self, resource):
content = sublime.load_resource(resource)
view = self.window.new_file()
view.set_name('Requester Tests')
view.run_command('requester_replace_view_text', {'text': content})
view.set_scratch(True)
return view
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 run(self, online=False):
if online:
webbrowser.open_new_tab('http://requester.org')
return
show_read_only_doc_view(self.window.new_file(),
sublime.load_resource('Packages/Requester/docs/_content/body.md'),
'Requester Documentation')
def set_syntax(view, syntax):
"""Attempts to set syntax for view without showing error pop-up.
"""
try:
sublime.load_resource(syntax)
except:
return False
else:
view.set_syntax_file(syntax)
return True
def getAllLanguages():
return sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/languages.json'))
def decodeEntity(xml, category='iso'):
global entities
if not isinstance(xml, str):
return xml
if entities[category]:
forward, reverse = entities[category]
else:
resourceMap = {
"iso": "IsoEntities.json",
"html": "HtmlEntities.json",
}
forward = sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/' + resourceMap[category]))
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 load_stylesheets_content(self):
"""Load the content of the scheme_styles.json file."""
content = ""
if os.path.isfile(self.theme_file_path):
content = sublime.load_resource(self.resource_path)
return content
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):
if self.window.active_view().file_name():
configFile = os.path.join(os.path.dirname(self.window.active_view().file_name()), 'spandoc.json')
else:
sublime.status_message("Cannot create project configuration for unsaved files.")
return
if os.path.exists(configFile):
self.window.open_file(configFile)
return
defaultConfigFile = os.path.join(sublime.packages_path(), 'Spandoc', 'Spandoc.sublime-settings')
userConfigFile = os.path.join(sublime.packages_path(), 'User', 'Spandoc.sublime-settings')
if not os.path.exists(defaultConfigFile) and not os.path.exists(userConfigFile):
try:
s = sublime.load_resource("Packages/Spandoc/Spandoc.sublime-settings")
except OSError as e:
sublime.status_message("Could not load default Pandoc configuration.")
print("[Spandoc could not find a default configuration file in Packages/Spandoc/Spandoc.sublime-settings]")
print("[Loading from the binary package resource file also failed.]")
print("[e: {0}]".format(e))
return
with codecs.open(configFile, "w", "utf-8") as f:
f.write(s)
self.window.open_file(configFile)
else:
try:
toCopy = defaultConfigFile if not os.path.exists(userConfigFile) else userConfigFile
shutil.copy(toCopy, configFile)
except Exception as e:
sublime.status_message("Could not write {0}".format(configFile))
print("[Spandoc encountered an exception:]")
print("[e: {0}]".format(e))
else:
self.window.open_file(configFile)
def _get_package_version():
pkg_json = sublime.load_resource("Packages/" + settings.PACKAGE_NAME +
"/package.json")
return json.loads(pkg_json)["version"]