Python sublime.decode_value() Examples

The following are 17 code examples of sublime.decode_value(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sublime , or try the search function .
Example #1
Source File: json_file.py    From UnitTesting with MIT License 6 votes vote down vote up
def load(self, default=[]):
        self.fdir = os.path.dirname(self.fpath)
        if not os.path.isdir(self.fdir):
            os.makedirs(self.fdir)
        if os.path.exists(self.fpath):
            f = codecs.open(self.fpath, "r+", encoding=self.encoding)
            try:
                content = f.read()
                data = sublime.decode_value(content)
            except Exception:
                print("%s is bad!" % self.fpath)
                f.close()
                raise
            if not data:
                data = default
            f.close()
        else:
            f = codecs.open(self.fpath, "w+", encoding=self.encoding)
            data = default
            f.close()
        return data 
Example #2
Source File: exec_command.py    From sublime-import-helper with MIT License 6 votes vote down vote up
def run_command(command, data=None, callback=None):
    debug("run_command", [NODE_BIN, command, data])
    json = sublime.encode_value({"command": command, "args": data})
    err = None
    out = None
    try:
        (err, out) = exec([NODE_BIN, "--no-warnings", RUN_PATH], json)
    except Exception as e:
        err = traceback.format_exc()
    if bool(err):
        if callback is not None:
            return callback(err, None)
        raise err
    # debug('run_command: trying to decode', out)
    result = sublime.decode_value(out)
    if callback is not None:
        return callback(None, result)
    return result 
Example #3
Source File: json_file.py    From ProjectManager with MIT License 6 votes vote down vote up
def load(self, default=[]):
        self.fdir = os.path.dirname(self.fpath)
        if not os.path.isdir(self.fdir):
            os.makedirs(self.fdir)
        if os.path.exists(self.fpath):
            with open(self.fpath, mode='r', encoding=self.encoding) as f:
                content = f.read()
                try:
                    data = sublime.decode_value(content)
                except Exception:
                    sublime.message_dialog('%s is bad!' % self.fpath)
                    raise
                if not data:
                    data = default
        else:
            with open(self.fpath, mode='w', encoding=self.encoding, newline='\n') as f:
                data = default
                f.write(sublime.encode_value(data, True))
        return data 
Example #4
Source File: project_watcher.py    From sublimetext-cfml with MIT License 6 votes vote down vote up
def on_post_save_async(self, view):
        file_name = utils.normalize_path(view.file_name())

        # check to see if the updated file was a .sublime-project
        if file_name.lower().endswith(".sublime-project"):
            project_name = file_name
            project_data = sublime.decode_value(
                view.substr(sublime.Region(0, view.size()))
            )
            self.project_updated(project_name, project_data)
        else:
            project_name = utils.get_project_name(view)
            if project_name:
                self.project_file_changed(
                    project_name, file_name, "project_file_updated"
                ) 
Example #5
Source File: docphp.py    From docphp with MIT License 6 votes vote down vote up
def getJsonOrGenerate(name, callback):
    filename = getI18nCachePath() + name + '.json'
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf8') as f:
            json = f.read(10485760)
        content = sublime.decode_value(json)

    else:
        content = callback()

        dirname = os.path.dirname(filename)
        if not os.path.isdir(dirname):
            os.makedirs(dirname)
        with open(filename, 'w', encoding="utf8") as f:
            f.write(sublime.encode_value(content))

    return content 
Example #6
Source File: linter.py    From SublimeLinter-contrib-htmlhint with MIT License 5 votes vote down vote up
def find_errors(self, output):
        """
        Override find_errors, parsing output json into json_object.

        Calls parse_message for each error found.

        """
        output_json = sublime.decode_value(output)
        logger.debug('output_json:"%s", file: "%s"', output_json, self.filename)

        for file in output_json:
            for message in file["messages"]:
                yield self.parse_message(message) 
Example #7
Source File: cfml_syntax.py    From sublimetext-cfml with MIT License 5 votes vote down vote up
def load_member_functions():

    member_functions = set()
    data = sublime.load_resource(
        "Packages/CFML/src/plugins_/basecompletions/json/cfml_member_functions.json"
    )
    data = sublime.decode_value(data)

    for member_type in data:
        methods = [m.lower() for m in data[member_type].keys()]
        member_functions.update(methods)

    return list(member_functions) 
Example #8
Source File: cfml_syntax.py    From sublimetext-cfml with MIT License 5 votes vote down vote up
def load_tag_list():
    tags_to_filter = [
        'abort',
        'admin',
        'case',
        'catch',
        'component',
        'continue',
        'defaultcase',
        'else',
        'elseif',
        'exit',
        'finally',
        'function',
        'if',
        'interface',
        'print',
        'rethrow',
        'retry',
        'return',
        'script',
        'servlet',
        'servletparam',
        'set',
        'sleep',
        'switch',
        'try',
        'while',
    ]
    tags = sublime.load_resource(
        "Packages/CFML/src/plugins_/basecompletions/json/cfml_tags.json"
    )
    tags = sublime.decode_value(tags).keys()
    return [t.lower()[2:] for t in tags if t.lower()[2:] not in tags_to_filter] 
Example #9
Source File: color_scheme_styles.py    From sublimetext-cfml with MIT License 5 votes vote down vote up
def get_user_color_scheme(color_scheme_file):
    try:
        src_str = sublime.load_resource(color_scheme_file)
        user_color_scheme = sublime.decode_value(src_str)
        if "rules" not in user_color_scheme:
            user_color_scheme["rules"] = []
        return user_color_scheme
    except IOError:
        return {"rules": []} 
Example #10
Source File: docphp.py    From docphp with MIT License 5 votes vote down vote up
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 
Example #11
Source File: docphp.py    From docphp with MIT License 5 votes vote down vote up
def getAllLanguages():
    return sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/languages.json')) 
Example #12
Source File: theme_generator.py    From GitSavvy with MIT License 5 votes vote down vote up
def __init__(self, original_color_scheme):
        super().__init__(original_color_scheme)
        self.dict = OrderedDict(sublime.decode_value(self.color_scheme_string)) 
Example #13
Source File: read_json.py    From sublime-import-helper with MIT License 5 votes vote down vote up
def read_json(file):
    if not os.path.isfile(file):
        return None
    fo = open(file, "r")
    data = fo.read()
    fo.close()
    return sublime.decode_value(data) 
Example #14
Source File: config.py    From AutomaticPackageReloader with MIT License 5 votes vote down vote up
def read_config(package, key, default=None):
    try:
        context = sublime.load_resource(
            "Packages/{}/.package_reloader.json".format(package))
        value = sublime.decode_value(context).get(key, default)
    except Exception:
        value = default

    return value 
Example #15
Source File: st_color_scheme_matcher.py    From sublime-markdown-popups with MIT License 4 votes vote down vote up
def merge_overrides(self):
        """Merge override schemes."""

        package_overrides = []
        user_overrides = []
        if self.scheme_file.endswith('.hidden-color-scheme'):
            pattern = '%s.hidden-color-scheme'
        else:
            pattern = '%s.sublime-color-scheme'
        for override in sublime.find_resources(pattern % path.splitext(self.scheme_file)[0]):
            if override.startswith('Packages/User/'):
                user_overrides.append(override)
            else:
                package_overrides.append(override)
        for override in (package_overrides + user_overrides):
            try:
                ojson = sublime.decode_value(sublime.load_resource(override))
            except IOError:
                # Fallback if file was created manually and not yet found in resources
                # Though it is unlikely this would ever get executed as `find_resources`
                # probably wouldn't have seen it either.
                with codecs.open(packages_path(override), 'r', encoding='utf-8') as f:
                    ojson = sublime.decode_value(sanitize_json(f.read()))

            for k, v in ojson.get('variables', {}).items():
                self.scheme_obj['variables'][k] = v

            for k, v in ojson.get(GLOBAL_OPTIONS, {}).items():
                self.scheme_obj[GLOBAL_OPTIONS][k] = v

            for item in ojson.get('rules', []):
                self.scheme_obj['rules'].append(item)

            self.overrides.append(override)

        # Rare case of being given a file but sublime hasn't indexed the files and can't find it
        if (
            not self.overrides and
            self.color_scheme.endswith(('.sublime-color-scheme', '.hidden-color-scheme')) and
            self.color_scheme.startswith('Packages/')
        ):
            with codecs.open(packages_path(self.color_scheme), 'r', encoding='utf-8') as f:
                ojson = sublime.decode_value(sanitize_json(f.read()))

                for k, v in ojson.get('variables', {}).items():
                    self.scheme_obj['variables'][k] = v

                for k, v in ojson.get(GLOBAL_OPTIONS, {}).items():
                    self.scheme_obj[GLOBAL_OPTIONS][k] = v

                for item in ojson.get('rules', []):
                    self.scheme_obj['rules'].append(item)

                self.overrides.append(self.color_scheme) 
Example #16
Source File: theme.py    From Terminus with MIT License 4 votes vote down vote up
def run(self, theme=None, remove=False, force=False):
        settings = sublime.load_settings("Terminus.sublime-settings")

        if not theme:
            theme = settings.get("theme", "default")
        if theme == "user":
            variables = settings.get("user_theme_colors", {})
            for key, value in list(variables.items()):
                if key.isdigit():
                    variables[ANSI_COLORS[int(key)]] = value
                    del variables[key]

        elif theme == "default":
            variables = {}
        else:
            content = sublime.load_resource("Packages/Terminus/themes/{}.json".format(theme))
            theme_data = sublime.decode_value(content)
            variables = theme_data["theme_colors"]

        path = os.path.join(
            sublime.packages_path(),
            "User",
            "Terminus",
            "Terminus.hidden-color-scheme"
        )

        path256 = os.path.join(
            sublime.packages_path(),
            "User",
            "Terminus.hidden-color-scheme"
        )

        if remove:
            if os.path.isfile(path):
                os.unlink(path)
                print("Theme removed: {}".format(path))
            if os.path.isfile(path256):
                os.unlink(path256)
                print("Theme removed: {}".format(path256))
            sublime.status_message("Theme {} removed".format(theme))
        else:
            if settings.get("256color", False):
                if force or not os.path.isfile(path256):
                    generate_theme_file(
                        path256, ansi_scopes=True, color256_scopes=True, pretty=False)
                    print("Theme {} generated: {}".format(theme, path256))
            else:
                if os.path.isfile(path256):
                    os.unlink(path256)

            generate_theme_file(path, variables=variables, ansi_scopes=False, color256_scopes=False)
            print("Theme {} generated: {}".format(theme, path))

            sublime.status_message("Theme generated") 
Example #17
Source File: cfml_syntax.py    From sublimetext-cfml with MIT License 4 votes vote down vote up
def load_functions():

    functions = sublime.load_resource(
        "Packages/CFML/src/plugins_/basecompletions/json/cfml_functions.json"
    )
    keys = [k.lower() for k in sublime.decode_value(functions)]

    prefixes = [
        'array',
        'struct',
        'component',
        'cache',
        'entity',
        'image',
        'date',
        'transaction',
        'xml',
        'spreadsheet',
        'orm',
        'object',
        'list',
        'query',
        'create',
        'get',
        'url',
        'is',
        'store',
        'to',
        'replace',
    ]

    prefixed = {}
    non_prefixed = []

    for item in sorted(keys):
        for prefix in prefixes:
            if item.startswith(prefix) and len(item) > len(prefix):
                prefixed.setdefault(prefix, []).append(item[len(prefix) :])
                break
        else:
            non_prefixed.append(item)

    return prefixed, non_prefixed