python类load_resource()的实例源码

settings.py 文件源码 项目:a-file-icon 作者: ihodev 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
functions.py 文件源码 项目:MarkdownLivePreview 作者: math2001 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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")
functions.py 文件源码 项目:MarkdownLivePreview 作者: math2001 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
test_settings.py 文件源码 项目:EasyClangComplete 作者: niosus 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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()
test_view_config.py 文件源码 项目:EasyClangComplete 作者: niosus 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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()
ProgressBarDemo.py 文件源码 项目:-SCRIPTS- 作者: Enteleform 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
        )
imp_developer.py 文件源码 项目:ElectricImp-Sublime 作者: electricimp 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
package_resources.py 文件源码 项目:ElectricImp-Sublime 作者: electricimp 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
NewFileBase.py 文件源码 项目:new-file-pro 作者: KevinHoo 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
inline-errors.py 文件源码 项目:SublimeLinter-inline-errors 作者: alexkuz 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
text_commands.py 文件源码 项目:sublime_gpg 作者: dmitrievav 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
text_commands.py 文件源码 项目:sublime_gpg 作者: dmitrievav 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:QuickEdit 作者: gamcoh 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
    ########################################################################
color_scheme.py 文件源码 项目:sublime-color-scheme-unit 作者: gerardroche 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def load_color_scheme_resource(color_scheme):
    return plistlib.readPlistFromBytes(bytes(load_resource(color_scheme), 'UTF-8'))
plugin.py 文件源码 项目:st_package_reviewer 作者: packagecontrol 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def random_func():
    # Generally safe
    sublime.load_resource()


# but not if called from within the global module scope
ToolTipHelper.py 文件源码 项目:ToolTip-Helper 作者: doobleweb 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
operations.py 文件源码 项目:hyperhelp 作者: OdatNurd 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
persist.py 文件源码 项目:sublime-text-3-packages 作者: nickjj 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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'] = ''
infoprovider.py 文件源码 项目:KodiDevKit 作者: phil65 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:Verilog-Gadget 作者: poucotm 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号