Python sublime 模块,load_resource() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sublime.load_resource()

项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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"))
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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 ''
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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
##############################
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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 ''
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
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 ''
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
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
##############################
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
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 ''
项目:docphp    作者:garveen    | 项目源码 | 文件源码
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
项目:a-file-icon    作者:ihodev    | 项目源码 | 文件源码
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
项目:a-file-icon    作者:ihodev    | 项目源码 | 文件源码
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)
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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 ''
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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
##############################
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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 ''
项目:hyperhelp    作者:OdatNurd    | 项目源码 | 文件源码
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
项目:TerminalView    作者:Wramberg    | 项目源码 | 文件源码
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)
项目:CompletePHP    作者:desean1625    | 项目源码 | 文件源码
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("&mdash;","-",html_str)
        html_str = re.sub("&quot;",'"',html_str)
        html_str = re.sub("&#039;","'",html_str)
        html_str = re.sub("&raquo;","»",html_str)
        #replace &$ with entity many functions had this
        html_str = re.sub("&\$","&amp;$",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")
项目:SublimeRegexExplainTip    作者:rubikonx9    | 项目源码 | 文件源码
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)
项目:SubVale    作者:ValeLint    | 项目源码 | 文件源码
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'))
项目:wxapp    作者:FloydaGithub    | 项目源码 | 文件源码
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
# ----------------------------------------------------------
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
def _get_default_css():
    """Get default CSS."""

    return clean_css(sublime.load_resource(DEFAULT_CSS))
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
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
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
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'
        )
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
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')
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
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
项目:docphp    作者:garveen    | 项目源码 | 文件源码
def getAllLanguages():
    return sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/languages.json'))
项目:docphp    作者:garveen    | 项目源码 | 文件源码
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
项目:ToolTip-Helper    作者:AvitanI    | 项目源码 | 文件源码
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
项目:SublimeHyperClick    作者:aziz    | 项目源码 | 文件源码
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")
项目:Spandoc    作者:geniusupgrader    | 项目源码 | 文件源码
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)
项目:a-file-icon    作者:ihodev    | 项目源码 | 文件源码
def _get_package_version():
    pkg_json = sublime.load_resource("Packages/" + settings.PACKAGE_NAME +
                                     "/package.json")

    return json.loads(pkg_json)["version"]
项目:a-file-icon    作者:ihodev    | 项目源码 | 文件源码
def _get_default():
    s = json.loads(jsonutils.sanitize_json(sublime.load_resource(
        "Packages/{0}/.sublime/{1}"
        .format(PACKAGE_NAME, PACKAGE_SETTINGS_FILE)
    )))

    del s["dev_mode"]
    del s["dev_trace"]

    return s
项目:MarkdownLivePreview    作者:math2001    | 项目源码 | 文件源码
def plugin_loaded():
    global error404, loading, DEFAULT_STYLE, USER_STYLE_FILE
    loading = sublime.load_resource('Packages/MarkdownLivePreview/loading.txt')
    error404 = sublime.load_resource('Packages/MarkdownLivePreview/404.txt')

    DEFAULT_STYLE = sublime.load_resource('Packages/MarkdownLivePreview/default.css')
    USER_STYLE_FILE = os.path.join(sublime.packages_path(), 'User', "MarkdownLivePreview.css")
项目:MarkdownLivePreview    作者:math2001    | 项目源码 | 文件源码
def get_resource(resource):
    if os.path.exists(os.path.join(sublime.packages_path(), '..', resource)):
        with open(os.path.join(sublime.packages_path(), '..', resource), encoding='utf-8') as fp:
            return fp.read()
    else:
        return sublime.load_resource(resource)
项目:EasyClangComplete    作者:niosus    | 项目源码 | 文件源码
def test_populate_flags(self):
        """Testing include population."""
        # open any existing file
        file_name = path.join(path.dirname(__file__),
                              'test_files',
                              'test_wrong_triggers.cpp')
        self.set_up_view(file_name)
        # now test the things
        manager = SettingsManager()
        settings = manager.user_settings()
        valid, _ = settings.is_valid()
        self.assertTrue(valid)

        p = path.join(sublime.packages_path(),
                      "User",
                      "EasyClangComplete.sublime-settings")
        if path.exists(p):
            user = sublime.load_resource(
                "Packages/User/EasyClangComplete.sublime-settings")
            if "common_flags" in user:
                # The user modified the default common flags, just skip the
                # next few tests.
                self.tear_down()
                return

        initial_common_flags = list(settings.common_flags)
        settings = manager.settings_for_view(self.view)
        dirs = settings.common_flags

        current_folder = path.dirname(self.view.file_name())
        parent_folder = path.dirname(current_folder)
        self.assertTrue(len(initial_common_flags) <= len(dirs))
        self.assertTrue(initial_common_flags[0] in dirs)
        self.assertFalse(initial_common_flags[1] in dirs)
        self.assertTrue(("-I" + current_folder) in dirs)
        self.assertTrue(("-I" + parent_folder) in dirs)
        self.tear_down()
项目:EasyClangComplete    作者:niosus    | 项目源码 | 文件源码
def test_flags(self):
        """Test that flags are properly defined for a completer."""
        file_name = path.join(path.dirname(__file__),
                              'test_files',
                              'test.cpp')
        self.set_up_view(file_name)
        manager = SettingsManager()
        settings = manager.settings_for_view(self.view)
        view_config = ViewConfig(self.view, settings)

        self.assertIsNotNone(view_config.completer)
        p = path.join(sublime.packages_path(),
                      "User",
                      "EasyClangComplete.sublime-settings")
        if path.exists(p):
            user = sublime.load_resource(
                "Packages/User/EasyClangComplete.sublime-settings")
            if "common_flags" in user:
                # The user modified the default common flags, just skip the
                # next few tests.
                self.tear_down()
                return
        completer = view_config.completer
        self.assertEqual(len(completer.clang_flags), 14)
        # test from the start
        self.assertEqual(completer.clang_flags[0], '-c')
        self.assertEqual(completer.clang_flags[1], '-fsyntax-only')
        self.assertEqual(completer.clang_flags[2], '-x')
        self.assertEqual(completer.clang_flags[3], 'c++')
        self.assertEqual(completer.clang_flags[4], '-std=c++11')
        # test last one
        expected = path.join(path.dirname(
            path.dirname(__file__)), 'local_folder')
        self.assertEqual(completer.clang_flags[12], '-I' + expected)
        self.tear_down()
项目:-SCRIPTS-    作者:Enteleform    | 项目源码 | 文件源码
def initialize_ProgressBar( self, view ):

        #???  Text  ???#
        self.popUp_Label_InProgress = "PROGRESS:"
        self.popUp_Label_Complete   = "COMPLETE!"

        #???  Progress Tracking  ???#
        self.maxPercent      = 100
        self.updateFrequency = 50 # In Milliseconds

        #???  Dimensions  ???#
        self.popupWidth         = 500
        self.popupMaxHeight     = 500
        self.progressBar_Height = 21

        #???  Colors  ???#
        self.progressBar_Incomplete_Color = "#0B121A"
        self.progressBar_Complete_Color   = "#57BB80"
        self.progressBar_Progress_Color   = "#5A91BC"
        self.progressBar_BorderColor      = "#000000"

        self.popupCSS = sublime.load_resource( sublime.find_resources( "ProgressBarDemo_ProgressBar.css" )[ 0 ] )
        self.progressBar_Width = int( float( self.popupWidth * 0.8 ) )
        self.progressPercent   = 0

        mdpopups.show_popup(
            view,               # view
            "",                 # content
            True,               # markdown
            self.popupCSS,      # css
            0,                  # flags
            -1,                 # location
            self.popupWidth,    # width
            self.popupMaxHeight # height
        )
项目:ElectricImp-Sublime    作者:electricimp    | 项目源码 | 文件源码
def copy_template_resource(self, dest_path, resource_name):
        plugin_dir_name = os.path.basename(os.path.dirname(os.path.realpath(__file__)))
        # extract plugin name from file with extention ".sublime-package":
        # Electric Imp Developer.sublime-package
        plugin_name, ext = os.path.splitext(plugin_dir_name)
        # see https://www.sublimetext.com/docs/3/api_reference.html:
        #       load_resource(name) - Loads the given resource.
        #       The name should be in the format Packages/Default/Main.sublime-menu.
        resource_path = '/'.join(["Packages", plugin_name, PR_TEMPLATE_DIR_NAME, resource_name])
        content = sublime.load_resource(resource_path)

        dest_path = os.path.join(dest_path, resource_name) if os.path.isdir(dest_path) else dest_path
        with open(dest_path, 'a', encoding="utf-8") as f:
            f.write(content)
项目:ElectricImp-Sublime    作者:electricimp    | 项目源码 | 文件源码
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
项目:new-file-pro    作者:KevinHoo    | 项目源码 | 文件源码
def get_code(self, type='text' ):
        code = ''
        file_name = "%s.tmpl" % type
        isIOError = False

        if IS_GTE_ST3:
            tmpl_dir = 'Packages/' + PACKAGE_NAME + '/' + TMLP_DIR + '/'
            user_tmpl_dir = 'Packages/User/' + PACKAGE_NAME + '/' + TMLP_DIR + '/'
        else:
            tmpl_dir = os.path.join(PACKAGES_PATH, PACKAGE_NAME, TMLP_DIR)
            user_tmpl_dir = os.path.join(PACKAGES_PATH, 'User', PACKAGE_NAME, TMLP_DIR)

        self.user_tmpl_path = os.path.join(user_tmpl_dir, file_name)
        self.tmpl_path = os.path.join(tmpl_dir, file_name)

        if IS_GTE_ST3:
            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

        if isIOError:
            sublime.message_dialog('[Warning] No such file: ' + self.tmpl_path + ' or ' + self.user_tmpl_path)

        return self.format_tag(code)
项目:SublimeLinter-inline-errors    作者:alexkuz    | 项目源码 | 文件源码
def get_template(self, theme_path):
        s = self.settings()

        if theme_path == 'none' or theme_path is None:
            return None

        tooltip_text = sublime.load_resource(theme_path)

        return Template(tooltip_text)
项目:sublime_gpg    作者:dmitrievav    | 项目源码 | 文件源码
def run(self, edit):
        v = self.view.window().new_file()
        v.set_name('GPG: Readme')
        v.settings().set('gutter', False)
        v.insert(edit, 0, sublime.load_resource('Packages/GPG/README.md'))
        v.set_syntax_file('Packages/Markdown/Markdown.sublime-syntax')
        v.set_read_only(True)
        v.set_scratch(True)
项目:sublime_gpg    作者:dmitrievav    | 项目源码 | 文件源码
def run(self, edit):
        v = self.view.window().new_file()
        v.set_name('GPG: Changelog')
        v.settings().set('gutter', False)
        v.insert(edit, 0, sublime.load_resource('Packages/GPG/CHANGELOG.md'))
        v.set_syntax_file('Packages/Markdown/Markdown.sublime-syntax')
        v.set_read_only(True)
        v.set_scratch(True)
项目:QuickEdit    作者:gamcoh    | 项目源码 | 文件源码
def formatCodeVar(self):
        reportHtml = '<div class="var">'
        reportHtml += '<p class="files"><em>in this file, at line : </em><a href="line-{line}">{line}</a></p>'.format(line=self.varsFound['line'])

        # format the code for a better syntax coloration
        reportHtmlContent = re.sub('(\$|=|new|->)', '<p class="monokai_red">\g<1></p>', self.varsFound['code'])
        reportHtmlContent = re.sub('(class)(;|,)', '<p class="monokai_blue">\g<1></p>\g<2>', reportHtmlContent)
        reportHtmlContent = re.sub('(\[| |=|>)([0-9]+)(\]| |;|,)', '\g<1><p class="monokai_int">\g<2></p>\g<3>', reportHtmlContent)
        # print(reportHtmlContent)

        reportHtml += reportHtmlContent
        reportHtml += '</div>'

        # load the font
        settings = sublime.load_settings('Preferences.sublime-settings')
        font = ''
        if settings.has('font_face'):
            font = '"%s",' % settings.get('font_face')

        # getting the errors that occured during the execution
        htmlErrors = ''
        if self.QuickEditSetting.get('show_errors'):
            for e in self.aErrors:
                htmlErrors += '<p class="error">• %s</p>' % e

            # if errors were found 
            if htmlErrors:
                htmlErrors = '<div class="panel panel-error mt20"><div class="panel-header">Errors that occured during the search</div><div class="panel-body">{errors}</div></div>'.format(errors=htmlErrors)

        # load css, and html ui
        css = sublime.load_resource('Packages/QuickEdit/resources/ui.css').replace('@@font', font)
        html = sublime.load_resource('Packages/QuickEdit/resources/report.html').format(css=css, html=reportHtml, errors=htmlErrors)

        self.view.erase_phantoms('quick_edit')
        self.view.add_phantom("quick_edit", self.view.sel()[0], html, sublime.LAYOUT_BLOCK, self.click)

    ########################################################################
    # format the code for the functions
    ########################################################################
项目:sublime-color-scheme-unit    作者:gerardroche    | 项目源码 | 文件源码
def load_color_scheme_resource(color_scheme):
    return plistlib.readPlistFromBytes(bytes(load_resource(color_scheme), 'UTF-8'))
项目:st_package_reviewer    作者:packagecontrol    | 项目源码 | 文件源码
def random_func():
    # Generally safe
    sublime.load_resource()


# but not if called from within the global module scope
项目:ToolTip-Helper    作者:doobleweb    | 项目源码 | 文件源码
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
项目:hyperhelp    作者:OdatNurd    | 项目源码 | 文件源码
def _load_index(package, index_file):
    """
    Takes a package name and its associated hyperhelp.json index resource name
    and loads it. Returns None on failure or a HelpData tuple for the loaded
    help information on success.
    """
    try:
        _log("Loading help index for package %s", package)
        json = sublime.load_resource(index_file)
        raw_dict = sublime.decode_value(json)

    except:
        return _log("Unable to load help index from '%s'", index_file)

    # Extract all known top level dictionary keys from the help index
    description = raw_dict.pop("description", "No description available")
    doc_root = raw_dict.pop("doc_root", None)
    toc = raw_dict.pop("toc", None)
    help_files = raw_dict.pop("help_files", dict())
    package_files = raw_dict.pop("package_files", dict())
    urls = raw_dict.pop("urls", dict())

    # Warn about unknown keys still in the dictionary; they are harmless, but
    # probably the author did something dodgy.
    for key in raw_dict.keys():
        _log("Unknown key '%s' in help index for package '%s'", key, package)

    if doc_root is None:
        doc_root = path.split(index_file)[0]
    else:
        doc_root = path.normpath("Packages/%s/%s" % (package, doc_root))

    # Pull in all the topics.
    topics = dict()
    _process_topic_dict(package, topics, help_files)
    _process_topic_dict(package, topics, package_files)
    _process_topic_dict(package, topics, urls)

    if toc is None:
        toc = [topics.get(topic) for topic in sorted(topics.keys())]
    else:
        _validate_toc(package, toc, topics)

    return HelpData(package, description, index_file, doc_root, topics,
                    sorted(help_files.keys()),
                    sorted(package_files.keys()),
                    list(urls.keys()),
                    toc)
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
def update_gutter_marks(self):
        """Update the gutter mark info based on the the current "gutter_theme" setting."""

        theme_path = self.settings.get('gutter_theme', DEFAULT_GUTTER_THEME_PATH)
        theme = os.path.splitext(os.path.basename(theme_path))[0]

        if theme_path.lower() == 'none':
            gutter_marks['warning'] = gutter_marks['error'] = ''
            return

        info = None

        for path in (theme_path, DEFAULT_GUTTER_THEME_PATH):
            try:
                info = sublime.load_resource(path)
                break
            except IOError:
                pass

        if info is not None:
            if theme != 'Default' and os.path.basename(path) == 'Default.gutter-theme':
                printf('cannot find the gutter theme \'{}\', using the default'.format(theme))

            path = os.path.dirname(path)

            for error_type in ('warning', 'error'):
                icon_path = '{}/{}.png'.format(path, error_type)
                gutter_marks[error_type] = icon_path

            try:
                info = json.loads(info)
                colorize = info.get('colorize', False)
            except ValueError:
                colorize = False

            gutter_marks['colorize'] = colorize
        else:
            sublime.error_message(
                'SublimeLinter: cannot find the gutter theme "{}",'
                ' and the default is also not available. '
                'No gutter marks will display.'.format(theme)
            )
            gutter_marks['warning'] = gutter_marks['error'] = ''
项目:KodiDevKit    作者:phil65    | 项目源码 | 文件源码
def load_data(self, kodi_version="krypton"):
        """
        loads the xml with control nodes for sanity checking (controls.xml)
        as well as builtins including their help string (data.xml)
        """
        # TODO: clean this up
        try:
            # since we get packaged we need to use load_resource() to load external files
            import sublime
            controls = sublime.load_resource("Packages/KodiDevKit/data/%s/controls.xml" % kodi_version)
            self.template_root = ET.fromstring(controls.encode("utf-8"), PARSER)
            # resolve includes
            data = sublime.load_resource("Packages/KodiDevKit/data/%s/data.xml" % kodi_version)
            root = ET.fromstring(data.encode("utf-8"), PARSER)
            WINDOW_MAP = json.loads(sublime.load_resource("Packages/KodiDevKit/data/%s/windows.json" % kodi_version))
        except (ImportError, OSError):
            # fallback to old method so that class still can get used without sublime import
            path = os.path.normpath(os.path.abspath(__file__))
            folder = os.path.split(path)[0]
            self.template_root = utils.get_root_from_file(os.path.join(folder, "..", "data", kodi_version, "controls.xml"))
            root = utils.get_root_from_file(os.path.join(folder, "..", "data", kodi_version, "data.xml"))
            with open(os.path.join(folder, "..", "data", kodi_version, "windows.json")) as f:
                WINDOW_MAP = json.load(f)
        self.WINDOW_FILENAMES = [item[2] for item in WINDOW_MAP]
        self.WINDOW_NAMES = [item[0] for item in WINDOW_MAP]
        self.WINDOW_IDS = [str(item[1]) for item in WINDOW_MAP]

        self.builtins = [[i.find("code").text, i.find("help").text] for i in root.find("builtins")]
        self.conditions = [[i.find("code").text, i.find("help").text] for i in root.find("conditions")]
        for include in self.template_root.xpath("//include[@name]"):
            for node in self.template_root.xpath("//include[not(@*)]"):
                if node.text == include.attrib.get("name"):
                    for child in include.getchildren():
                        child = copy.deepcopy(child)
                        node.getparent().append(child)
                    node.getparent().remove(node)
            self.template_root.remove(include)
        self.template_attribs = {}
        self.template_values = {}
        for template in self.template_root:
            self.template_attribs[template.attrib.get("type")] = {i.tag: i.attrib for i in template.iterchildren()}
            self.template_values[template.attrib.get("type")] = {i.tag: i.text for i in template.iterchildren()}
项目:Verilog-Gadget    作者:poucotm    | 项目源码 | 文件源码
def run(self, edit):
        if not check_extension(self.view.file_name(), self.view.name()):
            return

        vgs = get_prefs()
        fname = vgs.get("header", "")
        if fname == "example":
            if ST3:
                text  = sublime.load_resource('Packages/Verilog Gadget/template/verilog_header.v')
            else:
                fname = os.path.join(sublime.packages_path(), 'Verilog Gadget/template/verilog_header.v')
        if fname != "example":
            if fname.startswith('Packages'):
                fname = re.sub('Packages', sublime.packages_path(), fname)
            if not os.path.isfile(fname):
                disp_error("Insert Header : File not found (" + fname + ")")
                return
            else:
                with open(fname, "r", encoding="utf8") as f:
                    text  = str(f.read())

        # replace {DATE}, {FILE}, {YEAR}, {TIME}, {TABS}, {SUBLIME_VERSION}
        date  = time.strftime('%Y-%m-%d', time.localtime())
        year  = time.strftime('%Y', time.localtime())
        ntime = time.strftime('%H:%M:%S', time.localtime())
        tabs  = str(self.view.settings().get('tab_size'))
        enco  = self.view.encoding()
        sver  = sublime.version()[0]
        text  = re.sub("{DATE}", date, text)                # {DATE}
        text  = re.sub("{YEAR}", year, text)                # {YEAR}
        text  = re.sub("{TIME}", ntime, text)               # {TIME}
        text  = re.sub("{TABS}", tabs, text)                # {TABS}
        text  = re.sub("{SUBLIME_VERSION}", sver, text)     # {SUBLIME_VERSION}
        _file = re.compile(r"{FILE}").findall(text)
        if _file:
            fname = self.view.file_name()
            if not fname:
                disp_msg("Insert Header : Save with name")
                fname = ""
            else:
                fname = os.path.split(fname)[1]
                text = re.sub("{FILE}", fname, text)        # {FILE}
        self.view.insert(edit, 0, text)