Python sublime.packages_path() Examples

The following are 30 code examples of sublime.packages_path(). 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: build.py    From sublimetext-cfml with MIT License 6 votes vote down vote up
def run(self, src_dir=None):

        if src_dir is None:
            src_dir = os.path.join(sublime.packages_path(), DEST_DIR)

        for file_name in FILES:
            file_name = ".".join(file_name.split(".")[:-1])
            src_path, src_txt = get_file_txt(src_dir, file_name)

            if file_name == "cfscript-in-tags.sublime-syntax":
                src_txt = self.move_keys_to_top(
                    src_txt, ["variables", "hidden", "scope", "name"]
                )

            src_txt = self.clean_comments(src_txt)
            src_txt = self.clean_dashes(src_txt)
            src_txt = self.normalize_context_newlines(src_txt)

            with open(src_path, "w") as f:
                f.write(src_txt)

        self.order_contexts(
            src_dir, "cfscript.sublime-syntax", "cfscript-in-tags.sublime-syntax"
        ) 
Example #2
Source File: xdotool.py    From SendCode with MIT License 6 votes vote down vote up
def xdotool(*args):
    xdotool_path = shutil.which("xdotool")
    if not xdotool_path:
        xdotool_install_path = os.path.join(sublime.packages_path(), "User", "SendCode", "xdotool")
        if os.path.isfile(xdotool_install_path):
            xdotool_path = xdotool_install_path
        else:
            global prompt_installing_xdotool
            if not prompt_installing_xdotool:
                sublime.active_window().run_command(
                    "send_code_install_xdotool", {"path": xdotool_install_path})
                prompt_installing_xdotool = True

    if not xdotool_path:
        raise FileNotFoundError("xdotool cannot be found")

    return subprocess.check_output([xdotool_path] + list(args)) 
Example #3
Source File: gutter_color.py    From GutterColor with MIT License 6 votes vote down vote up
def fix_scheme_in_settings(settings_file,current_scheme, new_scheme, regenerate=False):
  """Change the color scheme in the given Settings to a background-corrected one"""
  from os.path import join, normpath, isfile

  settings = load_settings(settings_file)
  settings_scheme = settings.get("color_scheme")
  if current_scheme == settings_scheme:
    new_scheme_path =  join(packages_path(), normpath(new_scheme[len("Packages/"):]))
    if isfile(new_scheme_path) and not regenerate:
      settings.set("color_scheme", new_scheme)
    else:
      generate_scheme_fix(current_scheme, new_scheme_path)
      settings.set("color_scheme", new_scheme)
    save_settings(settings_file)
    return True
  return False 
Example #4
Source File: build.py    From sublimetext-cfml with MIT License 6 votes vote down vote up
def run(self, src=None, dest=None):
        if src is None:
            src = os.path.join(sublime.packages_path(), SRC_DIR)
        if dest is None:
            dest = os.path.join(sublime.packages_path(), DEST_DIR)

        output = sublime_lib.OutputPanel.create(self.window, "YAMLMacros")
        output.show()

        def run():
            for file_name in FILES:
                target_name, _ = os.path.splitext(file_name)
                file_path, file_txt = get_file_txt(src, file_name)
                yamlmacros.build(
                    source_text=file_txt,
                    destination_path=os.path.join(dest, target_name),
                    arguments={"file_path": file_path},
                    error_stream=output,
                )

        threading.Thread(target=run).start() 
Example #5
Source File: gutter_color.py    From GutterColor with MIT License 6 votes vote down vote up
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")) 
Example #6
Source File: package.py    From AutomaticPackageReloader with MIT License 6 votes vote down vote up
def package_of(path):
    spp = sublime.packages_path()
    spp_real = realpath(spp)
    for p in {path, realpath(path)}:
        for sp in {spp, spp_real}:
            if p.startswith(sp + os.sep):
                return p[len(sp):].split(os.sep)[1]

    if not sys.platform.startswith("win"):
        # we try to follow symlink if the real file is not located in spp
        for d in os.listdir(spp):
            subdir = os.path.join(spp, d)
            subdir_real = realpath(subdir)
            if not (os.path.islink(subdir) and os.path.isdir(subdir)):
                continue
            for sd in {subdir, subdir_real}:
                for p in {path, realpath(path)}:
                    if p.startswith(sd + os.sep):
                        return d

    return None 
Example #7
Source File: mixin.py    From UnitTesting with MIT License 6 votes vote down vote up
def load_stream(self, package, settings):
        output = settings["output"]
        if not output or output == "<panel>":
            output_panel = OutputPanel(
                'UnitTesting', file_regex=r'File "([^"]*)", line (\d+)')
            output_panel.show()
            stream = output_panel
        else:
            if not os.path.isabs(output):
                if sublime.platform() == "windows":
                    output = output.replace("/", "\\")
                output = os.path.join(sublime.packages_path(), package, output)
            if os.path.exists(output):
                os.remove(output)
            stream = open(output, "w")

        return stream 
Example #8
Source File: sublimefunctions.py    From FileManager with MIT License 6 votes vote down vote up
def get_template(created_file):
    """Return the right template for the create file"""
    global TEMPLATE_FOLDER

    if TEMPLATE_FOLDER is None:
        TEMPLATE_FOLDER = os.path.join(sublime.packages_path(), "User", ".FileManager")
        makedirs(TEMPLATE_FOLDER, exist_ok=True)

    template_files = os.listdir(TEMPLATE_FOLDER)
    for item in template_files:
        if (
            os.path.splitext(item)[0] == "template"
            and os.path.splitext(item)[1] == os.path.splitext(created_file)[1]
        ):
            return file_get_content(os.path.join(TEMPLATE_FOLDER, item))
    return "" 
Example #9
Source File: addons.py    From sublime-boxy-theme with MIT License 6 votes vote down vote up
def unified_mode():
    source = UNIFIED_SETTINGS['source']
    target = os.path.join(sublime.packages_path(), UNIFIED_SETTINGS['target'])
    package = os.path.join(sublime.installed_packages_path(),
                           UNIFIED_SETTINGS['package'])
    is_unified = get_settings().get('theme_unified', False)
    main = os.path.join(sublime.packages_path(), PARENT, source)

    if is_unified:
        if not os.path.exists(target):
            os.mkdir(target)

            if os.path.exists(main):
                copy_dir(main, target)
            else:
                extract_dir(package, source, target)

    elif os.path.exists(target):
        shutil.rmtree(target) 
Example #10
Source File: build.py    From sublime-ide-r with MIT License 6 votes vote down vote up
def on_activated_async(self, view):
        if view.settings().get('is_widget'):
            return

        if not selector_is_active(view=view):
            return

        if hasattr(self, "timer") and self.timer:
            self.timer.cancel()

        def set_build():
            build_path = os.path.join(
                sublime.packages_path(), 'User', 'R-IDE', 'R-IDE.sublime-build')
            generate_build(build_path, view=view)

        self.timer = threading.Timer(0.5, set_build)
        self.timer.start() 
Example #11
Source File: sync_manager.py    From SyncSettings with MIT License 6 votes vote down vote up
def fetch_files(files, to=''):
    if not path.exists(to, folder=True):
        os.mkdir(to)
    rq = Queue(maxsize=0)
    user_path = path.join(sublime.packages_path(), 'User')
    items = files.items()
    for k, file in items:
        decoded_name = path.decode(k)
        name = path.join(user_path, decoded_name)
        if should_exclude(name) and not should_include(name):
            continue
        rq.put((file['raw_url'], path.join(to, k)))
    threads = min(10, len(items))
    for i in range(threads):
        worker = threading.Thread(target=download_file, args=(rq,))
        worker.setDaemon(True)
        worker.start()
        time.sleep(0.1)
    rq.join() 
Example #12
Source File: sync_manager.py    From SyncSettings with MIT License 6 votes vote down vote up
def move_files(origin):
    user_path = path.join(sublime.packages_path(), 'User')
    for f in os.listdir(origin):
        # set preferences and package control files to the final of the list
        if fnmatch(f, '*Preferences.sublime-settings') or fnmatch(f, '*Package%20Control.sublime-settings'):
            continue
        name = path.join(user_path, path.decode(f))
        directory = os.path.dirname(name)
        if not path.exists(directory, True):
            os.makedirs(directory)
        shutil.move(path.join(origin, f), name)

    pending_files = ['Preferences.sublime-settings', 'Package%20Control.sublime-settings']
    for f in pending_files:
        if not path.exists(path.join(origin, f)):
            continue
        shutil.move(path.join(origin, f), path.join(user_path, path.decode(f))) 
Example #13
Source File: build.py    From sublime-ide-r with MIT License 6 votes vote down vote up
def on_activated_async(self, view):
        if view.settings().get('is_widget'):
            return
        if hasattr(self, "timer") and self.timer:
            self.timer.cancel()

        if not ride_settings.get("r_ide_menu", False):
            return

        def set_main_menu():

            menu_path = os.path.join(
                sublime.packages_path(), 'User', 'R-IDE', 'Main.sublime-menu')

            if selector_is_active(view=view):
                if not os.path.exists(menu_path):
                    generate_menu(menu_path)
            else:
                if os.path.exists(menu_path):
                    os.remove(menu_path)

        self.timer = threading.Timer(0.5, set_main_menu)
        self.timer.start() 
Example #14
Source File: request_history.py    From Requester with MIT License 6 votes vote down vote up
def move_requester_file(view, old_path, new_path):
    if os.path.exists(new_path):
        sublime.error_message('Move Requester File Error: `{}` already exists'.format(new_path))
        return
    try:
        os.rename(old_path, new_path)
    except Exception:
        sublime.error_message("Move Requester File Error: you couldn't move file to `{}`\n\n\
Remember to create the destination folder first".format(new_path))
        return
    window = view.window()
    window.run_command('close_file')
    window.open_file(new_path)

    rh = load_history(as_dict=True)
    for k, v in rh.items():
        if v.get('file') == old_path:
            v['file'] = new_path

    config = sublime.load_settings('Requester.sublime-settings')
    history_file = config.get('history_file', None)
    write_json_file(rh, os.path.join(sublime.packages_path(), 'User', history_file)) 
Example #15
Source File: request_history.py    From Requester with MIT License 6 votes vote down vote up
def load_history(rev=True, as_dict=False):
    """Returns list of past requests. Raises exception if history file doesn't
    exist.
    """
    history_file = sublime.load_settings('Requester.sublime-settings').get('history_file', None)
    if not history_file:
        raise KeyError

    history_path = os.path.join(sublime.packages_path(), 'User', history_file)
    with open(history_path, 'r') as f:
        rh = json.loads(f.read() or '{}', object_pairs_hook=OrderedDict)
    if as_dict:
        return rh
    requests = list(rh.items())
    if rev:
        requests.reverse()
    return requests 
Example #16
Source File: reloader.py    From Terminus with MIT License 5 votes vote down vote up
def reload_plugin(pkg_name):
    pkg_path = os.path.join(os.path.realpath(sublime.packages_path()), pkg_name)
    plugins = [pkg_name + "." + os.path.splitext(file_path)[0]
               for file_path in os.listdir(pkg_path) if file_path.endswith(".py")]
    for plugin in plugins:
        sublime_plugin.reload_plugin(plugin) 
Example #17
Source File: st_color_scheme_matcher.py    From sublime-markdown-popups with MIT License 5 votes vote down vote up
def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = scheme_file.replace('\\', '/')
        self.scheme_file = path.basename(self.color_scheme)

        if NEW_SCHEMES and scheme_file.endswith(('.sublime-color-scheme', '.hidden-color-scheme')):
            self.legacy = False
            self.scheme_obj = {
                'variables': {},
                GLOBAL_OPTIONS: {},
                'rules': []
            }
        else:
            try:
                content = sublime.load_binary_resource(sublime_format_path(self.color_scheme))
            except IOError:
                # Fallback if file was created manually and not yet found in resources
                with open(packages_path(self.color_scheme), 'rb') as f:
                    content = f.read()
            self.legacy = True
            self.convert_format(readPlistFromBytes(XML_COMMENT_RE.sub(b'', content)))
        self.overrides = []
        if NEW_SCHEMES:
            self.merge_overrides()
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}
        self.parse_scheme()
        self.scheme_obj = color_filter(self.scheme_obj)
        self.setup_matcher() 
Example #18
Source File: st_color_scheme_matcher.py    From sublime-markdown-popups with MIT License 5 votes vote down vote up
def packages_path(pth):
    """Get packages path."""

    return path.join(path.dirname(sublime.packages_path()), path.normpath(pth)) 
Example #19
Source File: SyntaxFold.py    From sublimetext-syntaxfold with MIT License 5 votes vote down vote up
def plugin_loaded():
    user_settings_path = os.path.join(
        sublime.packages_path(),
        "User",
        "syntax_fold.sublime-settings")

    if not os.path.exists(user_settings_path):
        default_settings_path = os.path.join(
            sublime.packages_path(),
            "SyntaxFold",
            "syntax_fold.sublime-settings")

        shutil.copyfile(default_settings_path, user_settings_path) 
Example #20
Source File: MarkdownLivePreview.py    From MarkdownLivePreview with MIT License 5 votes vote down vote up
def get_resource(resource):
    path = "Packages/MarkdownLivePreview/resources/" + resource
    abs_path = os.path.join(sublime.packages_path(), "..", path)
    if os.path.isfile(abs_path):
        with open(abs_path, "r") as fp:
            return fp.read()
    return sublime.load_resource(path) 
Example #21
Source File: install_xdotool.py    From SendCode with MIT License 5 votes vote down vote up
def run(self, path=None):
        if not sublime.ok_cancel_dialog(
                "xdotool was not installed. " +
                "Do you want to download xdotool binary now?"):
            return
        self.progress_bar = ProgressBar("installing xdotool")
        self.progress_bar.start()
        if not path:
            path = os.path.join(sublime.packages_path(), "User", "SendCode", "xdotool")
        sublime.set_timeout_async(lambda: self.install_xdotool(path)) 
Example #22
Source File: project_manager.py    From ProjectManager with MIT License 5 votes vote down vote up
def __init__(self, window):
        self.window = window
        s = 'project_manager.sublime-settings'
        self.settings = sublime.load_settings(s)

        default_projects_dir = os.path.join(
            sublime.packages_path(), 'User', 'Projects')
        user_projects_dirs = self.settings.get('projects_path')

        self.projects_path = []
        for folder in user_projects_dirs:
            if os.path.isdir(os.path.expanduser(folder)):
                self.projects_path.append(folder)

        if not self.projects_path:
            self.projects_path = [default_projects_dir]

        self.projects_path = [
            os.path.normpath(os.path.expanduser(d)) for d in self.projects_path]

        node = computer_name()
        if self.settings.get('use_local_projects_dir', False):
            self.projects_path = \
                [d + ' - ' + node for d in self.projects_path] + self.projects_path

        self.primary_dir = self.projects_path[0]

        if not os.path.isdir(self.primary_dir):
            os.makedirs(self.primary_dir)

        self.projects_info = self.get_all_projects_info() 
Example #23
Source File: Localization.py    From Chinese-Localization with MIT License 5 votes vote down vote up
def cleanup():
    PACKAGES_PATH = sublime.packages_path()
    DEFAULT_PATH = os.path.join(PACKAGES_PATH, "Default")
    ZZZZ_LOCALE = os.path.join(PACKAGES_PATH, "ZZZZZZZZ-Localization")
    import shutil
    shutil.rmtree(DEFAULT_PATH)
    shutil.rmtree(ZZZZ_LOCALE) 
Example #24
Source File: color_scheme_styles.py    From sublimetext-cfml with MIT License 5 votes vote down vote up
def toggle():
    preferences = sublime.load_settings("Preferences.sublime-settings")
    color_scheme = os.path.basename(preferences.get("color_scheme"))
    color_scheme_file = os.path.splitext(color_scheme)[0] + ".sublime-color-scheme"
    user_color_scheme = get_user_color_scheme("Packages/User/" + color_scheme_file)
    user_color_scheme_path = os.path.join(
        sublime.packages_path(), "User", color_scheme_file
    )

    non_cfml_rules = [
        row
        for row in user_color_scheme["rules"]
        if "scope" not in row or not row["scope"].endswith("cfml")
    ]
    has_cfml_rules = len(user_color_scheme["rules"]) > len(non_cfml_rules)

    if has_cfml_rules:
        user_color_scheme["rules"] = non_cfml_rules
    else:
        user_color_scheme["rules"].extend(get_cfml_rules())

    with open(user_color_scheme_path, "w") as f:
        f.write(sublime.encode_value(user_color_scheme, True))

    if len(user_color_scheme.keys()) == 1 and len(user_color_scheme["rules"]) == 0:
        print("CFML: Packages/User/{} is now empty.".format(color_scheme_file)) 
Example #25
Source File: component_index.py    From sublimetext-cfml with MIT License 5 votes vote down vote up
def init_parser(self):
        cache_dir = os.path.join(sublime.packages_path(), "User", "CFML")
        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)
        cache_path = cache_dir + '/cfc_index_cache.sqlite'
        self.parser = component_parser.Parser(cache_path) 
Example #26
Source File: build.py    From sublime-ide-r with MIT License 5 votes vote down vote up
def plugin_unloaded():
    menu_path = os.path.join(
        sublime.packages_path(), 'User', 'R-IDE', 'Main.sublime-menu')
    if os.path.exists(menu_path):
        os.unlink(menu_path)

    build_path = os.path.join(
        sublime.packages_path(), 'User', 'R-IDE', 'R-IDE.sublime-build')
    if os.path.exists(build_path):
        os.unlink(build_path) 
Example #27
Source File: request_history.py    From Requester with MIT License 5 votes vote down vote up
def delete_request(view, history_path=None):
    """Delete request in this staging `view` from request history.
    """
    if not view.settings().get('requester.response_view') or not view.settings().get('requester.history_view'):
        return

    reqs = load_history(rev=False)
    index = view.settings().get('requester.request_history_index', None)
    if index is None:
        sublime.error_message("History Error: request index doesn't exist")
        return

    try:
        params_dict = reqs[index][1]
    except IndexError as e:
        sublime.error_message('RequestHistory Error: {}'.format(e))
        return

    request = params_dict['request']
    file = params_dict['file']
    key = '{};;{}'.format(request, file) if file else request
    rh = load_history(as_dict=True)
    try:
        del rh[key]
    except KeyError:
        pass
    try:
        del rh[request]  # also delete identical requests not sent from any file
    except KeyError:
        pass

    config = sublime.load_settings('Requester.sublime-settings')
    history_file = config.get('history_file', None)
    if not history_path:
        history_path = os.path.join(sublime.packages_path(), 'User', history_file)
    write_json_file(rh, history_path) 
Example #28
Source File: request_history.py    From Requester with MIT License 5 votes vote down vote up
def run(self):
        history_file = sublime.load_settings('Requester.sublime-settings').get('history_file', None)
        if not history_file:
            raise KeyError
        view = self.window.open_file(os.path.join(sublime.packages_path(), 'User', history_file))
        view.set_read_only(True) 
Example #29
Source File: code_map.py    From sublime-codemap with MIT License 5 votes vote down vote up
def mapper_path(syntax, prefix=None):
    prefix_str = ''
    if prefix:
        prefix_str = prefix
    return path.join(sublime.packages_path(), 'User', 'CodeMap', 'custom_mappers', prefix_str + syntax+'.py') 
Example #30
Source File: theme_generator.py    From GitSavvy with MIT License 5 votes vote down vote up
def write_new_theme(self, name):
        full_path = os.path.join(sublime.packages_path(), self.get_theme_path(name))

        with util.file.safe_open(full_path, "wb", buffering=0) as out_f:
            out_f.write(STYLES_HEADER.encode("utf-8"))
            out_f.write(ElementTree.tostring(self.plist, encoding="utf-8"))