Ejemplo n.º 1
0
def clean_cache():
    """Delete cache"""
    for fl in os.listdir(sublime.cache_path() + os.path.sep + 'Xkcd'):
        try:
            os.remove(sublime.cache_path() + os.path.sep + 'Xkcd' + os.path.sep + fl)
        except OSError as e:
            raise IOError('Could not remove previous files.')
Ejemplo n.º 2
0
 def run(self, edit):
     decoder = json.JSONDecoder()
     platform = sublime.platform()
     if platform == 'linux' or platform == 'osx':
         path = sublime.cache_path() + '/CodeIniter/config.json'
     else:
         path = sublime.cache_path() + '\CodeIniter\config.json'
     fobj = open(path, 'r')
     s = fobj.read()
     db = decoder.decode(s)
     file_name = self.view.file_name()
     index = int(file_name.rfind('.')) + 1
     file_type = file_name[index:]
     fobj.close()
     self.view.insert(edit, 0, db[file_type])
Ejemplo n.º 3
0
def plugin_loaded():
    """Called directly from sublime on plugin load."""
    try:
        os.makedirs(sublime.cache_path() + os.path.sep + 'Xkcd')
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise IOError('Error encountered during file creation.')
Ejemplo n.º 4
0
    def __on_folder_path_entered(cls, path):
        """
        Executed after a path is entered.

        Checks the given user input to verify some basic requirements like that it is a directory.
        """
        if not os.path.exists(path):
            sublime.error_message("The entered path '" + path + "' is not valid. Please check your input.")
            return

        if not os.path.isdir(path):
            sublime.error_message("The entered path '" + path + "' is not a directory. Please check your input.")
            return

        if not from_folder.find_inis_in_folder(path):
            message = "The entered path '" + path + "' is not a valid Rainmeter skin. Please check your input."
            sublime.error_message(message)
            return

        # we expect the user to enter a new path which we need to persist
        install_cache_path = os.path.join(sublime.cache_path(), "Rainmeter", "install", "last_entered_folder.cache")
        if os.path.exists(install_cache_path):
            write_mode = 'w'
        else:
            write_mode = 'x'
            os.makedirs(os.path.dirname(install_cache_path))

        with open(install_cache_path, write_mode) as cache_handler:
            cache_handler.write(path)

        dest_folder = from_folder.install_into_skins_folder(path)
        sublime.message_dialog("Skin was successfully installed into \n\n" + dest_folder)
Ejemplo n.º 5
0
    def run(self):
        """Automatically executed upon calling this command."""
        # check cache first to determine the default path shown to the user
        install_cache_path = os.path.join(sublime.cache_path(), "Rainmeter",
                                          "install", "last_entered_zip.cache")
        if os.path.exists(install_cache_path) and os.path.isfile(
                install_cache_path):
            with open(install_cache_path, 'r') as cache_handler:
                cache_content = cache_handler.read()
                default_path = cache_content

        else:
            # show some default location from which the user can search from
            user = os.path.expanduser("~")
            downloads = os.path.join(user, "Downloads")

            if os.path.exists(downloads) and os.path.isdir(downloads):
                default_path = downloads
            else:
                default_path = None

        sublime.active_window().show_input_panel("Enter skin zip location:",
                                                 default_path,
                                                 self.__on_zip_path_entered,
                                                 None, None)
Ejemplo n.º 6
0
 def on_load_async(self, view):
     platform = sublime.platform()
     path = sublime.cache_path()
     if platform == 'linux' or platform == 'osx':
         path = path + '/CodeIniter'
     else:
         path = path + '\CodeIniter'
     if os.path.exists(path):
         print()
     else:
         os.makedirs(path)
     if platform == 'linux' or platform == 'osx':
         path = path + '/config.json'
     else:
         path = path + '\config.json'
     if os.path.isfile(path):
         print()
     else:
         fobj = open(path, 'w')
         data = {}
         data['cpp'] = '#include <iostream>\nusing namespace std\nint main() {\n}'
         data['java'] = 'import java.util.*;\nimport java.io.*;\nclass {\npublic static void main(String[] args) {\n}'
         data['py'] = 'import os'
         fobj.write(json.dumps(data))
         fobj.close()
def check_settings_changes():
    settings_package_file = os.path.join(
        sublime.installed_packages_path(),
        "%s.sublime-package" % SETTINGS_PACKAGE_NAME)
    if not os.path.exists(settings_package_file): return True

    has_changed_hashes = False
    hashes_cache_path = os.path.join(sublime.cache_path(),
                                     "zz_reload_default_package.json")

    clean_file_hashes = {}
    loaded_file_hashes = load_data_file(hashes_cache_path)

    for file_name in g_settings_files:
        file_path = os.path.join(DEFAULT_PACKAGE_DIRECTORY, file_name)
        current_hash = compute_file_hash(file_path)

        if file_name in loaded_file_hashes:

            if current_hash != loaded_file_hashes[file_name]:
                has_changed_hashes = True
                print(
                    "[zz_reload_default_package.py] Hash change for setting file: %s"
                    % file_path)

        else:
            has_changed_hashes = True

        clean_file_hashes[file_name] = current_hash

    if clean_file_hashes != loaded_file_hashes:
        write_data_file(hashes_cache_path, clean_file_hashes)

    return has_changed_hashes
Ejemplo n.º 8
0
def extract_variables(window: sublime.Window) -> Dict[str, str]:
    variables = window.extract_variables()
    variables["storage_path"] = get_storage_path()
    variables["cache_path"] = sublime.cache_path()
    variables["temp_dir"] = tempfile.gettempdir()
    variables["home"] = os.path.expanduser('~')
    return variables
Ejemplo n.º 9
0
def _get_cache():
    if _ST3:
        cache_path = os.path.normpath(
            os.path.join(sublime.cache_path(), "LaTeXTools"))
    else:
        cache_path = os.path.normpath(
            os.path.join(sublime.packages_path(), "User"))

    pkg_cache_file = os.path.normpath(
        os.path.join(
            cache_path,
            'pkg_cache.cache' if _ST3 else 'latextools_pkg_cache.cache'))

    cache = None
    if not os.path.exists(pkg_cache_file):
        gen_cache = sublime.ok_cancel_dialog(
            "Cache files for installed packages, "
            "classes and bibliographystyles do not exists, "
            "would you like to generate it? After generating complete, "
            "please re-run this completion action!")

        if gen_cache:
            sublime.active_window().run_command("latex_gen_pkg_cache")
    else:
        with open(pkg_cache_file) as f:
            cache = json.load(f)
    return cache
Ejemplo n.º 10
0
def cache_mendeley():
    settings = tools.load_settings("LaTeXing", cache={"mendeley": 24}, mendeley=False)

    if not settings["mendeley"] or not "mendeley" in settings["cache"] or not settings["cache"]["mendeley"]:
        if os.path.exists(os.path.join(sublime.cache_path(), "LaTeXing", "mendeley.cache")):
            CACHE.clear_cache("mendeley.cache", False)
        return

    # Get MendeleyFile
    f = MendeleyFile()

    # Get Cache data an rebuild cahce if necessary
    mendeley_data = CACHE.get_cache_data("mendeley.cache")
    if CACHE.is_cache_outdated("mendeley.cache", settings["cache"]["mendeley"]):
        f = MendeleyFile()
        f.run(cache=False, save=True)
        if f.status == "Error":
            log.error("error while caching")
            # CACHE.clear_cache("mendeley.cache", True)
        elif f.status == "Ok":
            mendeley_data = f.data
            CACHE.set_cache_data("mendeley.cache", mendeley_data, True)
    else:
        log.debug("up to date")

        # Rebuild Keys
        for item in mendeley_data["cites"]:
            item["cite_key"] = f.build_cite_key(item)

        # Set the new cache
        CACHE.set_cache_data("mendeley.cache", mendeley_data, True)
Ejemplo n.º 11
0
def cache_zotero():
    settings = tools.load_settings("LaTeXing", cache={"zotero": 24}, zotero=False)

    if not settings["zotero"] or not "zotero" in settings["cache"] or not settings["cache"]["zotero"]:
        if os.path.exists(os.path.join(sublime.cache_path(), "LaTeXing", "zotero.cache")):
            CACHE.clear_cache("zotero.cache", False)
        return

    # Get ZoteroFile
    f = ZoteroFile()

    zotero_data = CACHE.get_cache_data("zotero.cache")
    if CACHE.is_cache_outdated("zotero.cache", settings["cache"]["zotero"]):
        f.run(cache=False, save=True)
        if f.status == "Error":
            log.error("error while caching")
            # CACHE.clear_cache("zotero.cache", True)
        elif f.status == "Ok":
            zotero_data = f.data
            CACHE.set_cache_data("zotero.cache", zotero_data, True)
    else:
        log.debug("rebuild cite_key")
        # Rebuild Keys
        for item in zotero_data["cites"]:
            item["cite_key"] = f.build_cite_key(item)

        # Set the new cache
        CACHE.set_cache_data("zotero.cache", zotero_data, True)
def plugin_loaded():
  """Finds the script path and run the script for each window.

  Called by ST once this plugin has been fully loaded.
  """
  if PLATFORM == "linux":
    global _SCRIPT_PATH_
    _SCRIPT_PATH_ = os.path.join(sublime.cache_path(),
                                 "list_window_with_title.sh")
    with open(_SCRIPT_PATH_, "w") as o:
      o.write(SCRIPT)

  global _READY_
  _READY_ = True

  # Update all window titles on setting change.
  settings = sublime.load_settings("set_window_title.sublime-settings")
  setting_keys = [
    "unregistered",
    "template",
    "has_project_true",
    "has_project_false",
    "is_dirty_true",
    "is_dirty_false",
    "path_display",
    "untitled",
  ]
  for k in setting_keys:
    settings.add_on_change(k, refresh_all)

  if PLATFORM == "linux":
    # Set the title when the plugin is loaded.
    # Only enabled on Linux because for some reason it freezes ST on Windows.
    # TODO: Find how to enable a similar behavior on Windows.
    refresh_all()
Ejemplo n.º 13
0
def cache_bibsonomy():
    settings = tools.load_settings("LaTeXing", cache={"bibsonomy": 24}, bibsonomy=False)

    if not settings["bibsonomy"] or not "bibsonomy" in settings["cache"] or not settings["cache"]["bibsonomy"]:
        if os.path.exists(os.path.join(sublime.cache_path(), "LaTeXing", "bibsonomy.cache")):
            CACHE.clear_cache("bibsonomy.cache", False)
        return

    # Get BibsonomyFile
    f = BibsonomyFile()

    bibsonomy_data = CACHE.get_cache_data("bibsonomy.cache")
    if CACHE.is_cache_outdated("bibsonomy.cache", settings["cache"]["bibsonomy"]):
        f.run(cache=False, save=True)
        if f.status == "Error":
            log.error("error while caching")
            # CACHE.clear_cache("bibsonomy.cache", True)
        elif f.status == "Ok":
            bibsonomy_data = f.data
            CACHE.set_cache_data("bibsonomy.cache", bibsonomy_data, True)
    else:
        log.debug("up to date")

        # Rebuild Keys
        for item in bibsonomy_data["cites"]:
            item["cite_key"] = f.build_cite_key(item)

        # Set the new cache
        CACHE.set_cache_data("bibsonomy.cache", bibsonomy_data, True)
Ejemplo n.º 14
0
def _generate_package_cache():
    installed_tex_items = _get_files_matching_extensions(
        _get_tex_searchpath('tex'), ['sty', 'cls'])

    installed_bst = _get_files_matching_extensions(_get_tex_searchpath('bst'),
                                                   ['bst'])

    # create the cache object
    pkg_cache = {
        'pkg': installed_tex_items['sty'],
        'bst': installed_bst['bst'],
        'cls': installed_tex_items['cls']
    }

    # For ST3, put the cache files in cache dir
    # and for ST2, put it in the user packages dir
    # and change the name
    cache_path = os.path.normpath(
        os.path.join(sublime.cache_path(), "LaTeXTools"))

    if not os.path.exists(cache_path):
        os.makedirs(cache_path)

    pkg_cache_file = os.path.normpath(
        os.path.join(cache_path, 'pkg_cache.cache'))

    with open(pkg_cache_file, 'w+') as f:
        json.dump(pkg_cache, f)

    sublime.set_timeout(
        partial(sublime.status_message,
                'Finished generating LaTeX package cache'), 0)
Ejemplo n.º 15
0
 def precompile(self, sysimage_path):
     settings = sublime.load_settings(SETTINGS_FILE)
     julia_bin = settings.get("julia_executable_path") or "julia"
     cache_path = os.path.join(sublime.cache_path(), "JuliaLanguageServer")
     if not os.path.exists(cache_path):
         os.mkdir(cache_path)
     # copy precompile execution file to cache_path
     precompile_execution_file = os.path.join(
         cache_path, "precompile_execution_file.jl")
     if os.path.exists(precompile_execution_file):
         os.remove(precompile_execution_file)
     file = open(precompile_execution_file, "w")
     file.write(
         sublime.load_resource(
             "Packages/LSP-julia/precompile_execution_file.jl"))
     file.close()
     # load and execute precompile script
     precompile_script = sublime.load_resource(
         "Packages/LSP-julia/precompile.jl").replace("\n", ";")
     returncode = subprocess.call(
         [julia_bin, "-e", precompile_script, cache_path, sysimage_path])
     if returncode == 0:
         settings.set("sysimage_path", sysimage_path)
         sublime.save_settings(SETTINGS_FILE)
         env_path = get_active_environment()[1]
         update_starting_command(env_path)
         sublime.message_dialog(
             "The language server has successfully been precompiled into a sysimage, which will be used after Sublime Text is restarted."
         )
     else:
         sublime.error_message(
             "An error occured while precompiling the language server.")
Ejemplo n.º 16
0
def clean():
    dir_path = os.path.join(sublime.packages_path(), "LaTeXing3")
    if os.path.isdir(dir_path):
        sublime.message_dialog("Please remove your old LaTeXing installation. Close Sublime Text and delete the following directory: %s!" % dir_path)

    file_path = os.path.join(sublime.installed_packages_path(), "LaTeXing3.sublime-package")
    if os.path.isfile(file_path):
        sublime.message_dialog("Please remove your old LaTeXing installation. Close Sublime Text and delete the following file: %s!" % file_path)

    dir_path = os.path.join(sublime.cache_path(), "LaTeXing3")
    if os.path.isdir(dir_path):
        shutil.rmtree(dir_path)

    dir_path = os.path.join(sublime.cache_path(), "LaTeXing ST3")
    if os.path.isdir(dir_path):
        shutil.rmtree(dir_path)
def toggle():
    current_color_scheme = sublime.load_settings(
        "Preferences.sublime-settings").get("color_scheme").replace("\\", "/")
    packages_path = sublime.packages_path().replace("\\", "/")
    cache_path = sublime.cache_path().replace("\\", "/")
    package_name, theme_file, relative_path_to_theme_file = get_current_color_scheme_parts(
        current_color_scheme)

    current_theme = plistlib.readPlistFromBytes(
        sublime.load_binary_resource(current_color_scheme))
    non_cfml_settings = [
        row for row in current_theme["settings"]
        if "scope" not in row or not row["scope"].endswith("cfml")
    ]

    # if there are no cfml styles, then add them, else remove them (i.e. toggle)
    adding_styles = len(non_cfml_settings) == len(current_theme["settings"])
    if adding_styles:
        current_theme["settings"].extend(get_style_settings())
    else:
        current_theme["settings"] = non_cfml_settings

    if adding_styles or not is_installed_package(package_name):
        directory_exists = create_directory_if_not_exists(
            packages_path + "/" + relative_path_to_theme_file)
        if not directory_exists:
            return
        plistlib.writePlist(
            current_theme, packages_path + "/" + relative_path_to_theme_file +
            "/" + theme_file)
    else:
        remove_directory_if_exists(packages_path + "/" + package_name)
        remove_file_if_exists(cache_path + "/" + relative_path_to_theme_file +
                              "/" + theme_file + ".cache")
Ejemplo n.º 18
0
    def __on_zip_path_entered(cls, path):
        """Executed after a zip path is entered."""
        if not os.path.exists(path):
            sublime.error_message("The entered path '" + path + "' is not valid. Please check your input.")
            return

        if not os.path.isfile(path):
            sublime.error_message("The entered path '" + path + "' is not a file. Please check your input.")
            return

        if not path.endswith(".zip"):
            sublime.error_message("The entered path '" + path + "' is not a zip file. Please check your input.")
            return

        # we expect the user to enter a new path which we need to persist
        install_cache_path = os.path.join(sublime.cache_path(), "Rainmeter", "install", "last_entered_zip.cache")
        if os.path.exists(install_cache_path):
            write_mode = 'w'
        else:
            write_mode = 'x'
            os.makedirs(os.path.dirname(install_cache_path))

        with open(install_cache_path, write_mode) as cache_handler:
            cache_handler.write(path)

        from_zip.install_skin_zip(path)
        sublime.status_message("Skin was successfully installed!")
Ejemplo n.º 19
0
def _get_cache():
    if _ST3:
        cache_path = os.path.normpath(
            os.path.join(sublime.cache_path(), "LaTeXTools"))
    else:
        cache_path = os.path.normpath(
            os.path.join(sublime.packages_path(), "User"))

    pkg_cache_file = os.path.normpath(
        os.path.join(cache_path, 'pkg_cache.cache'
                     if _ST3 else 'latextools_pkg_cache.cache'))

    cache = None
    if not os.path.exists(pkg_cache_file):
        gen_cache = sublime.ok_cancel_dialog(
            "Cache files for installed packages, "
            "classes and bibliographystyles do not exists, "
            "would you like to generate it? After generating complete, "
            "please re-run this completion action!"
        )

        if gen_cache:
            sublime.active_window().run_command("latex_gen_pkg_cache")
    else:
        with open(pkg_cache_file) as f:
            cache = json.load(f)
    return cache
Ejemplo n.º 20
0
def cached_resource(res, alias=None):
    #res = 'Packages/Plugin Debugger/start_sublime_winpdb.py'
    log("cached_resource: %s => %s", res, alias)

    if alias is None:
        alias = os.path.basename(res)

    log("cached_resource: %s => %s", res, alias)

    cache_dir = os.path.join(sublime.cache_path(), 'Plugin Debugger')
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)
    fn = os.path.join(cache_dir, alias)

    log("cached name: %s", fn)

    if not os.path.exists(fn):
        log("create cached file: %s\n" % fn)
        data = sublime.load_binary_resource(res)
        with open(fn, 'wb') as fh:
            fh.write(data)

    log("cache done: %s", fn)

    return fn
Ejemplo n.º 21
0
def get_cached_pkgs_list() -> Optional[List[Tuple[str, str, str, str]]]:
    cache_dir = Path(sublime.cache_path()) / 'sublime-nextflow'
    cache_path = cache_dir / 'conda_search.pickle'
    if not cache_path.exists():
        return None
    with open(cache_path, 'rb') as fh:
        return pickle.load(fh)
Ejemplo n.º 22
0
def install_languages_async():
    plugin_dir = os.path.dirname(os.path.dirname(__file__))

    for language in ['HTML']:
        # See if our version of the language already exists in Packages
        src_dir = os.path.join(plugin_dir, language)
        version_file = os.path.join(src_dir, 'sublimelinter.version')

        if os.path.isdir(src_dir) and os.path.isfile(version_file):
            with open(version_file, encoding='utf8') as f:
                my_version = int(f.read().strip())

            dest_dir = os.path.join(sublime.packages_path(), language)
            version_file = os.path.join(dest_dir, 'sublimelinter.version')

            if os.path.isdir(dest_dir):
                if os.path.isfile(version_file):
                    with open(version_file, encoding='utf8') as f:
                        try:
                            other_version = int(f.read().strip())
                        except ValueError:
                            other_version = 0

                    copy = my_version > other_version
                else:
                    copy = sublime.ok_cancel_dialog(
                        'An existing {} language package exists, '.format(language) +
                        'and SublimeLinter wants to overwrite it with its version. ' +
                        'Is that okay?')

                if copy:
                    try:
                        shutil.rmtree(dest_dir)
                    except OSError as ex:
                        from . import persist
                        persist.printf(
                            'could not remove existing {} language package: {}'
                            .format(language, str(ex))
                        )
                        copy = False
            else:
                copy = True

            if copy:
                from . import persist

                try:
                    cached = os.path.join(sublime.cache_path(), language)

                    if os.path.isdir(cached):
                        shutil.rmtree(cached)

                    shutil.copytree(src_dir, dest_dir)
                    persist.printf('copied {} language package'.format(language))
                except OSError as ex:
                    persist.printf(
                        'could not copy {} language package: {}'
                        .format(language, str(ex))
                    )
Ejemplo n.º 23
0
 def is_enabled(self):
     try:
         return os.path.isfile(
             os.path.join(
                 os.path.join(sublime.cache_path(), "File Navigator",
                              "History.json")))
     except Exception as e:
         return False
    def setup(self):
        if self._initialized:
            return

        self._initialized = True
        self._package_cache_path = os.path.join(sublime.cache_path(), self._package_name)

        self._copy_to_cache()
Ejemplo n.º 25
0
 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)))
def plugin_unloaded():
    from package_control import events

    package_name = GLOBAL_SET['package_name']
    if events.remove(package_name):
        print('remove {0}'.format(package_name))
        cache_dir = os.path.join(sublime.cache_path(), package_name)
        shutil.rmtree(cache_dir)
Ejemplo n.º 27
0
def plugin_loaded():
    imp.reload(verilogutil)
    imp.reload(sublimeutil)
    fname = os.path.join(sublime.cache_path(), "systemverilog_lmf.json")
    # print('Cache file = {}'.format(fname))
    if os.path.isfile(fname):
        global list_module_files
        list_module_files = json.load(open(fname))
Ejemplo n.º 28
0
    def cache_directory(self):
        sublime_cache = sublime.cache_path()
        cache_path = sublime_cache + "/gem-spy"

        if not os.path.exists(cache_path):
            os.makedirs(cache_path)

        return cache_path
Ejemplo n.º 29
0
    def run(self, edit, selected_thread_object):

        global comment_view_obj, list_of_threads, location_of_cbrt

        # sublime.status_message("view id of UI is set here: "+str(comment_view_obj))
        current_thread = list_of_threads[selected_thread_object]
        sum_of_chars = 0
        com_list = current_thread.list_of_comments
        #package_directory = sublime.packages_path() + '/' + 'CollaBroText'

        location_of_cbrt = sublime.cache_path() + '/CollaBroText'

        #creates CollaBroText directory in cache_path() if it does not exist
        if not os.path.exists(location_of_cbrt):
            os.makedirs(location_of_cbrt)

        # for comment in reversed(com_list):
        #     #self.view.insert(edit, 0, "comment")
        #     sum_of_chars = self.view.insert(
        #         edit, 0, "\n" + comment.comment_string)
        #     split_timestamp = comment.timestamp.split(' ')
        #     split_only_date = split_timestamp[0].split('-')
        #     if(split_timestamp[0] == str(date.today())):
        #         final_timestamp = "Today @ " + split_timestamp[1]
        #     elif(split_timestamp[0] == str(date.today() - timedelta(days=1))):
        #         final_timestamp = "Yesterday @ " + split_timestamp[1]
        #     elif(split_only_date[0] == str(date.today().year)):
        #         final_timestamp = split_only_date[1] + "-" + split_only_date[2] + " @ " + split_timestamp[1]
        #     self.view.insert(edit, 0, "\n\n\n@" +
        #                      comment.username + "\t" + final_timestamp)

        with open(location_of_cbrt + '/comments.cbrt', 'w+') as fl:

            for comment in (com_list):

                split_timestamp = comment.timestamp.split(' ')
                split_only_date = split_timestamp[0].split('-')
                if (split_timestamp[0] == str(date.today())):
                    timeperiod = "Today "
                elif (split_timestamp[0] == str(date.today() -
                                                timedelta(days=1))):
                    timeperiod = "Yesterday "
                elif (split_only_date[0] == str(date.today().year)):
                    timeperiod = split_only_date[1] + "-" + split_only_date[2]
                else:
                    timeperiod = split_only_date[1] + "-" + split_only_date[
                        2] + "-" + split_only_date[0]

                fl.write("\n\n" + timeperiod)
                fl.write("\n@" + comment.username + "\t" + split_timestamp[1])
                fl.write("\n" + ' ' + comment.comment_string)

        #print("current view" + str(self.view))
        comment_view_obj = window.open_file(location_of_cbrt +
                                            '/comments.cbrt')
        #print("layout_view " + str(comment_view_obj))

        comment_view_obj.set_read_only(True)
Ejemplo n.º 30
0
    def resolve_sm_package_dir(self):
        # if user has specified the installation path, resolve package directory based on that
        if self.sm_path:
            return path.join(self.sm_path, 'Packages', 'User')

        # else, figure out based on the Sublime Text installation path
        st_path = path.realpath(
            path.join(sublime.cache_path().replace('Cache', ''), '..'))
        return path.join(st_path, 'Sublime Merge', 'Packages', 'User')
Ejemplo n.º 31
0
 def __init__(self, conf):
     self.plugin_cache = os.path.join(sublime.cache_path(), 'AFTP')
     self.conf = conf
     #Open debug,level's val with 0,1,2.
     self.aftp.set_debuglevel(1)
     #0 active mode, 1 passive
     self.aftp.set_pasv(conf['ftp_passive_mode'])
     #Connect host
     self.aftp.connect(conf['host'], conf['port'])
Ejemplo n.º 32
0
 def run(self):
     try:
         if sublime.ok_cancel_dialog("Delete File Navigator History?",
                                     "Delete"):
             os.remove(
                 os.path.join(sublime.cache_path(), "FileNavigator",
                              "History.json"))
     except Exception as e:
         pass
Ejemplo n.º 33
0
def install_cli():
    python_command = get_python_command()
    if not python_command:
        python_command = get_default_python_command()
        if not python_command:
            sublime.error_message(
                "DeepCodeAI plugin requires python >= 3.6.5. If you want to use a virtual python environment, please adjust package setting 'python'"
            )
            return
        
        set_python_command(python_command)
    
    pip_command = get_pip_command()
    if not pip_command:
        sublime.error_message(
            "DeepCodeAI plugin requires you to have python pip globally available. \n\nFor more instructions visit: \nhttps://pip.pypa.io/en/stable/installing"
        )
        return

    cache_path = sublime.cache_path()
    lib_dir = os.path.join(cache_path, 'deepcode_lib')
    
    try:
        default_args = dict(
            stderr=subprocess.PIPE,
            cwd=cache_path,
            shell=platform.system() == 'Windows',
            env=get_custom_env()
        )
        # Make directory for our dependencies
        subprocess.check_call(
            ['mkdir', '-p', 'deepcode_lib'],
            **default_args
        )
        
        # Upgrade pip
        subprocess.check_call(
            pip_command + ['install', '-U', 'pip'],
            **default_args
        )

        subprocess.check_call(
            pip_command
            + [
                'install',
                CLI_DEPENDENCY,
                '-t',
                lib_dir
            ],
            **default_args
        )

    except Exception as e:
        print('path local deepcode exception: ', e)
        sublime.error_message(
            'There was an error installing/upgrading DeepCodeAI scripts'
        )
Ejemplo n.º 34
0
   def run(self):
      plugin_helpers.DebugLogMessage("--> " + __name__ + ": " + type(self).__name__ + "." + sys._getframe().f_code.co_name)

      # sublime.active_window().run_command("new_window")
      # sublime.active_window().run_command("wam_project_init")

      print(sublime.cache_path())

      plugin_helpers.DebugLogMessage("<-- " + __name__ + ": " + type(self).__name__ + "." + sys._getframe().f_code.co_name)
def plugin_loaded():
    global cache

    cache_dir = os.path.join(sublime.cache_path(), GLOBAL_SET['package_name'])
    cache['libs'] = DataCache('libs', cache_dir, [get_erl_lib_dir()])
    cache['libs'].build_data_async()

    cache['project'] = DataCache('project', cache_dir)
    cache['project'].build_data_async()
Ejemplo n.º 36
0
def _global_cache_path():
    # For ST3, put the cache files in cache dir
    # and for ST2, put it in the user packages dir
    if _ST3:
        cache_path = os.path.join(sublime.cache_path(), "LaTeXTools")
    else:
        cache_path = os.path.join(sublime.packages_path(),
                                  "User",
                                  ST2_GLOBAL_CACHE_FOLDER)
    return os.path.normpath(cache_path)
def get_cache_dir(*name):
	try:
		p = os.path.join(sublime.cache_path(), PLUGIN_NAME, *name)
	except:
		p = os.path.normpath(os.path.join(sublime.packages_path(), '..', PLUGIN_NAME, *name))

	if not os.path.exists(p):
		os.makedirs(p)

	return p
Ejemplo n.º 38
0
def plugin_loaded():
    try:
        cache_dir = os.path.join(sublime.cache_path(), 'Zip Browser')
    except:
        cache_dir = os.path.join(sublime.packages_path(), '..', 'Cache', 'Zip Browser')

    if os.path.exists(cache_dir):
        shutil.rmtree(cache_dir)

    cleanup_temp_dir()
Ejemplo n.º 39
0
 def plugin_loaded(self):
     print("Plugin loaded!")
     self.settings = sublime.load_settings("ccomplete")
     cachepath = sublime.cache_path() + "/ccomplete_cache"
     if not os.path.exists(cachepath):
         os.mkdir(cachepath)
     self.cc = CComplete(self.settings.get('cache', 500), cachepath)
     self.currentfile = None
     self.ready = False
     self.extensions = self.settings.get("extensions", ["c", "cpp", "cxx", "h", "hpp", "hxx"])
     self.load_matching = self.settings.get("load_matching", True)
     self.init = True
Ejemplo n.º 40
0
def init_settings():
	global encoding_cache, TMP_DIR, CACHE_ROOT
	if ST3:
		CACHE_ROOT = os.path.join(sublime.cache_path(), 'ConvertToUTF8')
	else:
		CACHE_ROOT = os.path.join(sublime.packages_path(), 'User')
	TMP_DIR = os.path.join(CACHE_ROOT, 'c2u_tmp')
	if not os.path.exists(TMP_DIR):
		os.makedirs(TMP_DIR)
	encoding_cache = EncodingCache()
	get_settings()
	sublime.load_settings('ConvertToUTF8.sublime-settings').add_on_change('get_settings', get_settings)
Ejemplo n.º 41
0
 def clear_cache(self, file_name, soft):
     if soft and file_name in self.cache_data:
         file_json = self.get_cache(file_name)
         file_json["rtime"] = "01.01.2000T00:00:00"
         self.set_cache(file_name, file_json)
     else:
         file_path = os.path.join(sublime.cache_path(), "LaTeXing", file_name)
         if os.path.isfile(file_path):
             os.remove(file_path)
         if file_name in self.cache_data:
             self.cache_data.pop(file_name)
     log.info("%s (%s)" % (file_name, "soft" if soft else "hard"))
Ejemplo n.º 42
0
 def get_cache_bin(self, bin):
     """
     Returns a cache bin. If the bin doesn't exist, it is created.
     """
     cache_bin_name = hashlib.sha224(bin.encode("utf-8")).hexdigest()
     sublime_cache_path = sublime.cache_path()
     cache_bin = sublime_cache_path + "/" + "sublime-drush" + "/" + cache_bin_name
     if os.path.isdir(cache_bin) is False:
         print("Bin not found. Created new cache bin: %s" % cache_bin)
         os.makedirs(cache_bin)
     else:
         print('Returning cache bin for "%s"' % bin)
     return cache_bin
def _generate_package_cache():
    installed_tex_items = _get_files_matching_extensions(
        _get_tex_searchpath('tex'),
        ['sty', 'cls']
    )

    installed_bst = _get_files_matching_extensions(
        _get_tex_searchpath('bst'),
        ['bst']
    )

    # create the cache object
    pkg_cache = {
        'pkg': installed_tex_items['sty'],
        'bst': installed_bst['bst'],
        'cls': installed_tex_items['cls']
    }

    # For ST3, put the cache files in cache dir
    # and for ST2, put it in the user packages dir
    # and change the name
    if _ST3:
        cache_path = os.path.normpath(
            os.path.join(
                sublime.cache_path(),
                "LaTeXTools"
            ))
    else:
        cache_path = os.path.normpath(
            os.path.join(
                sublime.packages_path(),
                "User"
            ))

    if not os.path.exists(cache_path):
        os.makedirs(cache_path)

    pkg_cache_file = os.path.normpath(
        os.path.join(cache_path, 'pkg_cache.cache' if _ST3 else 'latextools_pkg_cache.cache'))

    with open(pkg_cache_file, 'w+') as f:
        json.dump(pkg_cache, f)

    sublime.set_timeout(
        partial(
            sublime.status_message,
            'Finished generating LaTeX package cache'
        ),
        0
    )
    def gutter_icon_path(self):
        try:
            resource = sublime.load_binary_resource("gutter-icon.png")
            cache_path = os.path.join(sublime.cache_path(), "Merlin",
                                      "gutter-icon.png")

            if not os.path.isfile(cache_path):
                if not os.path.isdir(os.path.dirname(cache_path)):
                    os.makedirs(os.path.dirname(cache_path))
                with open(cache_path, "wb") as f:
                    f.write(resource)

            return "Cache/Merlin/gutter-icon.png"

        except IOError:
            return "Packages/" + self._plugin_dir() + "/gutter-icon.png"
Ejemplo n.º 45
0
    def update_colors(self, view):
        cache_file_path = os.path.join(sublime.cache_path(), "Rainbowth", "Rainbowth" + ".cache")
        base_dir = sublime.packages_path()
        scheme_path = base_dir[:-8] + view.settings().get("color_scheme")
        scheme_name = scheme_path.split("/")[-1].split(".")[0]

        try:
            with open(cache_file_path, "r") as cache_file:
                cache = json.load(cache_file)
        except (EnvironmentError, ValueError):
            cache = {}

        settings = sublime.load_settings("Rainbowth.sublime-settings")
        palettes = settings.get("palettes")
        self.colors = palettes.get(scheme_name, palettes["default"])
        if self.colors == cache.get(scheme_name, None):
            return

        with open(scheme_path, "r") as scheme_file:
            scheme_xml = scheme_file.read()  # .decode('utf-8')

        bg = re.search("background.+?g>(.+?)<", scheme_xml, re.DOTALL).group(1)
        bg = "#%06x" % max(1, (int(bg[1:], 16) - 1))
        fragment = (
            "<dict><key>scope</key><string>rainbowth%d</string><key>settings</key><dict><key>background</key><string>"
            + bg
            + "</string><key>foreground</key><string>%s</string></dict></dict>"
        )
        scheme_xml = re.sub("\t+<!-- rainbowth -->.+\n", "", scheme_xml)

        rainbowth = "\t<!-- rainbowth -->"
        for i, c in enumerate(self.colors):
            rainbowth += fragment % (i, c)

        scheme_xml = re.sub("</array>", rainbowth + "<!---->\n\t</array>", scheme_xml)
        with open(scheme_path, "w") as scheme_file:
            scheme_file.write(scheme_xml)  # .encode('utf-8'))
        cache[scheme_name] = self.colors

        cache_file_folder = os.path.split(cache_file_path)[0]
        if not os.path.exists(cache_file_folder):
            # ensure folder exists for cache file
            os.makedirs(cache_file_folder)

        with open(cache_file_path, "w") as cache_file:
            json.dump(cache, cache_file)
Ejemplo n.º 46
0
def copy_syntax(syntax, src_dir, version, dest_dir):
    """Copy a customized syntax and related files to Packages."""
    from . import persist

    try:
        cached = os.path.join(sublime.cache_path(), syntax)

        if os.path.isdir(cached):
            shutil.rmtree(cached)

        if not os.path.exists(dest_dir):
            os.mkdir(dest_dir)

        for filename in os.listdir(src_dir):
            shutil.copy2(os.path.join(src_dir, filename), dest_dir)

        persist.printf("copied {} syntax version {}".format(syntax, version))
    except OSError as ex:
        persist.printf("ERROR: could not copy {} syntax package: {}".format(syntax, str(ex)))
Ejemplo n.º 47
0
  def update_colors(self, view):
    cache_file_path = os.path.join(sublime.cache_path(), 'Rainbowth', 'Rainbowth' + '.cache')
    base_dir = sublime.packages_path()
    scheme_path = base_dir[:-8] + view.settings().get('color_scheme')
    scheme_name = scheme_path.split('/')[-1].split('.')[0]

    try:
      with open(cache_file_path, 'r') as cache_file:
        cache = json.load(cache_file)
    except (EnvironmentError, ValueError):
      cache = {}

    settings = sublime.load_settings('Rainbowth.sublime-settings')
    palettes = settings.get('palettes')
    self.colors = palettes.get(scheme_name, palettes['default'])
    if self.colors == cache.get(scheme_name, None):
      return

    with open(scheme_path, 'r') as scheme_file:
      scheme_xml = scheme_file.read()#.decode('utf-8')

    bg = re.search('background.+?g>(.+?)<', scheme_xml, re.DOTALL).group(1)
    bg = '#%06x' % max(1, (int(bg[1:], 16) - 1))
    fragment = '<dict><key>scope</key><string>rainbowth%d</string><key>settings</key><dict><key>background</key><string>' + bg + '</string><key>foreground</key><string>%s</string></dict></dict>'
    scheme_xml = re.sub('\t+<!-- rainbowth -->.+\n', '', scheme_xml)

    rainbowth = '\t<!-- rainbowth -->'
    for i, c in enumerate(self.colors):
      rainbowth += fragment % (i, c)

    scheme_xml = re.sub('</array>', rainbowth + '<!---->\n\t</array>', scheme_xml)
    with open(scheme_path, 'w') as scheme_file:
      scheme_file.write(scheme_xml)#.encode('utf-8'))
    cache[scheme_name] = self.colors

    cache_file_folder = os.path.split(cache_file_path)[0]
    if not os.path.exists(cache_file_folder):
      # ensure folder exists for cache file
      os.makedirs(cache_file_folder)

    with open(cache_file_path, 'w') as cache_file:
      json.dump(cache, cache_file)
Ejemplo n.º 48
0
Archivo: xkcd.py Proyecto: bizoo/xkcd
    def getComic(self, id=None):
        """Background loop."""
        result = xJson(id)

        if result is not None:
            self.title = result['title']
            self.img = result['img']
            self.alt = result['alt']
            self.num = result['num']

            try:
                local_img = sublime.cache_path() + os.path.sep + 'Xkcd' + \
                    os.path.sep + self.img.split('/')[-1]
                urllib.request.urlretrieve(self.img, local_img)

            except urllib.error.HTTPError as e:
                sublime.error_message(
                    'Xkcd: %s: HTTP error %s retrieving image' % (__name__, str(e.code)))
            except urllib.error.URLError as e:
                sublime.error_message(
                    'Xkcd: %s: URL error %s retrieving image' % (__name__, str(e.reason)))

            self.output = '[' + str(self.num) + '] ' + \
                self.title + '\n\n' + self.alt

            panel = self.window.create_output_panel('xkcd_meta')
            panel.run_command('erase_view')
            self.window.run_command(
                "show_panel", {"panel": "output.xkcd_meta"})
            self.window.get_output_panel('xkcd_meta').run_command(
                'append', {'characters': self.output})
            panel.settings().set("word_wrap", True)
            # print(int(self.window.active_view().viewport_extent()[0]-self.window.active_view().layout_extent()[0]))

            self.window.open_file(local_img, sublime.TRANSIENT)

            global xkcd_open
            xkcd_open.append(self.num)

            # HANDLE NAVIGATION (first/previous/next/last) HERE...
        else:
            sublime.error_message('Xkcd: Error reading API response')
Ejemplo n.º 49
0
def get_cache_path():
    global _file_path, ST2
    if _file_path:
        return _file_path

    cache_end_point = ['CSS', 'CSS.completions.cache']
    if ST2:
        _file_path = [sublime.packages_path(), '..', 'Cache'] + cache_end_point
    else:
        _file_path = [sublime.cache_path()] + cache_end_point

    _file_path = os.path.join(*_file_path)

    _file_path = os.path.abspath(_file_path)
    cache_dir = _file_path.replace('CSS.completions.cache', '')

    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)

    return _file_path
Ejemplo n.º 50
0
Archivo: xkcd.py Proyecto: bizoo/xkcd
def plugin_loaded():
    """Called directly from sublime on plugin load."""
    try:
        os.makedirs(sublime.cache_path() + os.path.sep + 'Xkcd')
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise IOError('Error encountered during file creation.')

    # Set up http(s) proxy
    settings = sublime.load_settings("Package Control.sublime-settings")
    http_proxy = settings.get('http_proxy')
    https_proxy = settings.get('https_proxy')
    if http_proxy or https_proxy:
        proxies = {}
        if http_proxy:
            proxies['http'] = http_proxy
        if https_proxy:
            proxies['https'] = https_proxy
        #print("Proxies:", proxies)

    # sublime.error_message(str(proxies))

    proxy_username = settings.get('proxy_username')
    proxy_password = settings.get('proxy_password')
    if proxy_username and proxy_password:
        if http_proxy:
            proxies['http'] = proxy_username + ":" + \
                proxy_password + "@" + http_proxy
        if https_proxy:
            proxies['https'] = proxy_username + ":" + \
                proxy_password + "@" + https_proxy

    global opener
    opener = urllib.request.build_opener(
        urllib.request.ProxyHandler(
            #{"http":"http://[user]:[password]@[proxy_IP]:[proxy_port]"}
            proxies
            #{"http": https_proxy, "https": https_proxy}
        )
    )
    urllib.request.install_opener(opener)
Ejemplo n.º 51
0
def clear_cache(force = False):
  """
  If the folder exists, and has more than 5MB of icons in the cache, delete
  it to clear all the icons then recreate it.
  """
  from os.path import getsize, join, isfile, exists
  from os import makedirs, listdir
  from sublime import cache_path
  from shutil import rmtree
  
  # The icon cache path
  icon_path = join(cache_path(), "GutterColor")

  # The maximum amount of space to take up
  limit = 5242880 # 5 MB

  if exists(icon_path):
    size = sum(getsize(join(icon_path, f)) for f in listdir(icon_path) if isfile(join(icon_path, f)))
    if force or (size > limit): rmtree(icon_path)

  if not exists(icon_path): makedirs(icon_path)
Ejemplo n.º 52
0
def cache_bin():
    dir_path = os.path.join(sublime.cache_path(), "LaTeXing", "bin")

    if os.path.isdir(dir_path):
        for item in os.listdir(dir_path):
            os.remove(os.path.join(dir_path, item))
    else:
        os.makedirs(dir_path)

    if sublime.platform() == "osx":
        items = ["activate_application", "preview"]
    elif sublime.platform() == "linux":
        items = ["evince", "evince_forward_sync", "evince_reverse_sync", "https_request"]
    else:
        items = []

    for item in items:
        content = sublime.load_binary_resource("Packages/LaTeXing/bin/%s" % item)
        with open(os.path.join(dir_path, item), 'wb') as f:
            f.write(content)
            os.chmod(f.name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH)
            log.debug("bin/%s: up to date" % item)
def toggle():
	current_color_scheme = sublime.load_settings("Preferences.sublime-settings").get("color_scheme").replace("\\","/")
	packages_path = sublime.packages_path().replace("\\","/")
	cache_path = sublime.cache_path().replace("\\","/")
	package_name, theme_file, relative_path_to_theme_file = get_current_color_scheme_parts(current_color_scheme)

	current_theme = plistlib.readPlistFromBytes(sublime.load_binary_resource(current_color_scheme))
	non_cfml_settings = [row for row in current_theme["settings"] if "scope" not in row or not row["scope"].endswith("cfml")]

	# if there are no cfml styles, then add them, else remove them (i.e. toggle)
	adding_styles = len(non_cfml_settings) == len(current_theme["settings"])
	if adding_styles:
		current_theme["settings"].extend(get_style_settings())
	else:
		current_theme["settings"] = non_cfml_settings

	if adding_styles or not is_installed_package(package_name):
		directory_exists = create_directory_if_not_exists(packages_path + "/" + relative_path_to_theme_file)
		if not directory_exists:
			return
		plistlib.writePlist(current_theme, packages_path + "/" + relative_path_to_theme_file + "/" + theme_file)
	else:
		remove_directory_if_exists(packages_path + "/" + package_name)
		remove_file_if_exists(cache_path  + "/" + relative_path_to_theme_file + "/" + theme_file + ".cache")