Example #1
0
 def get_drush_path(self):
     """
     Get the path to the Drush executable. It's either in Packages or
     Installed Packages, depending on the user's installation method.
     If either of those fail, check for system-wide Drush.
     """
     settings = sublime.load_settings("subDrush.sublime-settings")
     if (settings):
         drush_path = settings.get('drush_executable')
         if str(drush_path) != 'subDrush':
             print('subDrush: Using user defined path to Drush: %s' %
                   drush_path)
             if not os.path.exists(drush_path):
                 sublime.error_message('You specified "%s" as the path to \
                 Drush but this does not seem to be valid. Please fix your \
                 settings at Preferences > Package Settings > subDrush > \
                 Settings - User' % drush_path)
                 return False
             return drush_path
     print('subDrush: Using subDrush\'s bundled version of Drush.')
     if os.path.exists("%s/subDrush/lib/drush/drush" %
                       sublime.packages_path()):
         return "%s/subDrush/lib/drush/drush" % sublime.packages_path()
     elif os.path.exists("%s/subDrush/lib/drush/drush" %
                         sublime.installed_packages_path()):
         return "%s/subDrush/lib/drush/drush" % \
             sublime.installed_packages_path()
     else:
         print('subDrush: Using system-wide Drush install.')
         return shutil.which('drush')
    def check_overriding(self):
        """
        Check key binding overriding plugin with:
            - sublime.installed_packages_path
                other plugins keybindigs
            - user/default
                user/default keybindigs in sublime
        """
        default_keymap = sublime.load_resource(KeyMapRegex.DEFAULT_KEY_MAP)
        default_keys = re.findall(syntax.key_value_command, default_keymap)

        self.load_plugin_keybindigs()
        self.check_override(default_keys, self.DEFAULT_KEY_MAP)

        for file in os.listdir(sublime.installed_packages_path()):

            if str(file).find(SettingsTags.PACKAGE_EXTENTION) != -1:
                zip_ = zipfile.ZipFile(
                    path.join(sublime.installed_packages_path(), file))
                arr_keys = []
                arr_keys.extend(
                    filter(
                        lambda file_name: re.search(syntax.key_map,
                                                    str(file_name)),
                        zip_.namelist()))

            for item in arr_keys:
                temp_keys = re.findall(syntax.key_value_command,
                                       str(zip_.open(item).read()))
                self.check_override(temp_keys, file)
    def __init__(self, view):
        # Setup the plugin in the super class
        sublime_plugin.TextCommand.__init__(self, view)

        try:
            pluginPath = sublime.packages_path() + '/AndroidImport'
            classes_file = open(pluginPath + '/classes.txt')
        except IOError:
            try:
                pluginPath = sublime.installed_packages_path() + '/AndroidImport'
                classes_file = open(pluginPath + '/classes.txt')
            except IOError:
                try:
                    pluginPath = sublime.packages_path() + '/AndroidImport.sublime-package'
                    with zipfile.ZipFile(pluginPath) as package_zip:
                        classes_file = package_zip.open('classes.txt')
                except IOError:
                    try:
                        pluginPath = sublime.installed_packages_path() + '/AndroidImport.sublime-package'
                        with zipfile.ZipFile(pluginPath) as package_zip2:
                            classes_file = package_zip2.open('classes.txt')
                    except IOError:
                        sublime.error_message("Couldn't load AndroidImport plugin. Maybe try reinstalling...")
                        return

        self.androidClassList = dict()
        for line in classes_file.readlines():
            line_parts = line.split('::')
            key = line_parts[0]
            line_parts.remove(key)

            self.androidClassList[key] = list()
            for package in line_parts:
                self.androidClassList[key].append(''.join(package.split()))
Example #4
0
 def get_drush_path(self):
     """
     Get the path to the Drush executable. It's either in Packages or
     Installed Packages, depending on the user's installation method.
     If either of those fail, check for system-wide Drush.
     """
     settings = sublime.load_settings("subDrush.sublime-settings")
     if settings:
         drush_path = settings.get("drush_executable")
         if str(drush_path) != "subDrush":
             print("subDrush: Using user defined path to Drush: %s" % drush_path)
             if not os.path.exists(drush_path):
                 sublime.error_message(
                     'You specified "%s" as the path to \
                 Drush but this does not seem to be valid. Please fix your \
                 settings at Preferences > Package Settings > subDrush > \
                 Settings - User'
                     % drush_path
                 )
                 return False
             return drush_path
     print("subDrush: Using subDrush's bundled version of Drush.")
     if os.path.exists("%s/subDrush/lib/drush/drush" % sublime.packages_path()):
         return "%s/subDrush/lib/drush/drush" % sublime.packages_path()
     elif os.path.exists("%s/subDrush/lib/drush/drush" % sublime.installed_packages_path()):
         return "%s/subDrush/lib/drush/drush" % sublime.installed_packages_path()
     else:
         print("subDrush: Using system-wide Drush install.")
         return shutil.which("drush")
Example #5
0
    def __init__(self, view):
        # Setup the plugin in the super class
        sublime_plugin.TextCommand.__init__(self, view)

        try:
            plugin_path = sublime.packages_path() + '/AndroidImport'
            classes_file = open(plugin_path + '/classes.txt')
        except IOError:
            try:
                plugin_path = sublime.installed_packages_path() + '/AndroidImport'
                classes_file = open(plugin_path + '/classes.txt')
            except IOError:
                try:
                    plugin_path = sublime.packages_path() + '/AndroidImport.sublime-package'
                    with zipfile.ZipFile(plugin_path) as package_zip:
                        classes_file = package_zip.open('classes.txt')
                except IOError:
                    try:
                        plugin_path = sublime.installed_packages_path() + '/AndroidImport.sublime-package'
                        with zipfile.ZipFile(plugin_path) as package_zip2:
                            print(package_zip2)
                            classes_file = package_zip2.open('classes.txt')
                    except IOError:
                        sublime.error_message("Couldn't load AndroidImport plugin. Maybe try reinstalling...")
                        return

        self.android_class_list = dict()
        for line in classes_file.readlines():
            line_parts = line.decode("utf-8").split('::')
            key = line_parts[0]
            line_parts.remove(key)

            self.android_class_list[key] = list()
            for package in line_parts:
                self.android_class_list[key].append(''.join(package.split()))
Example #6
0
	def load_themes(self):
		all_themes = set()

		try: # use find_resources() first for ST3
			for theme_resource in sublime.find_resources('*.sublime-theme'):
				filename = os.path.basename(theme_resource)
				all_themes.add(filename)

		except: # fallback to walk() for ST2
			for root, dirs, files in os.walk(sublime.packages_path()):
				for filename in (filename for filename in files if filename.endswith('.sublime-theme')):
					all_themes.add(filename)

			for root, dirs, files in os.walk(sublime.installed_packages_path()):
				for package in (package for package in files if package.endswith('.sublime-package')):
					zf = zipfile.ZipFile(os.path.join(sublime.installed_packages_path(), package))
					for filename in (filename for filename in zf.namelist() if filename.endswith('.sublime-theme')):
						all_themes.add(filename)

		favorite_themes = self.get_favorites()
		themes = []

		for theme in all_themes:
			favorited = theme in favorite_themes
			pretty_name = 'Theme: ' + theme.replace('.sublime-theme', '')
			if favorited: pretty_name += u' \N{BLACK STAR}' # Put a pretty star icon next to favorited themes. :)
			themes.append([pretty_name, theme, favorited])

		themes.sort()
		return themes
Example #7
0
	def load_schemes(self):
		scheme_paths = []
		favorites = self.get_favorites()

		try: # use find_resources() first for ST3.
			scheme_paths = sublime.find_resources('*.tmTheme')

		except: # fallback to walk() for ST2
			# Load the paths for schemes contained in zipped .sublime-package files.
			for root, dirs, files in os.walk(sublime.installed_packages_path()):
				for package in (package for package in files if package.endswith('.sublime-package')):
					zf = zipfile.ZipFile(os.path.join(sublime.installed_packages_path(), package))
					for filename in (filename for filename in zf.namelist() if filename.endswith('.tmTheme')):
						filepath = os.path.join(root, package, filename).replace(sublime.installed_packages_path(), 'Packages').replace('.sublime-package', '').replace('\\', '/')
						scheme_paths.append(filepath)

			# Load the paths for schemes contained in folders.
			for root, dirs, files in os.walk(sublime.packages_path()):
				for filename in (filename for filename in files if filename.endswith('.tmTheme')):
					filepath = os.path.join(root, filename).replace(sublime.packages_path(), 'Packages').replace('\\', '/')
					scheme_paths.append(filepath)

		scheme_paths = self.filter_scheme_list(scheme_paths)

		# Given the paths of all the color schemes, add in the information for
		# the pretty-printed name and whether or not it's been favorited.
		schemes = []
		for scheme_path in scheme_paths:
			scheme_name = self.filter_scheme_name(scheme_path)
			is_favorite = ''
			if scheme_path in favorites: is_favorite = u'   \u2605' # Put a pretty star icon next to favorited schemes. :)
			schemes.append([scheme_name, scheme_path, is_favorite])

		schemes.sort(key=lambda s: s[0].lower())
		return schemes
Example #8
0
 def __init__(self):
     """
     Stores sublime packages paths
     """
     self.directory_list = {sublime.packages_path(): "", sublime.installed_packages_path(): ".sublime-package"}
     self.packages_bak_path = "%s.bak" % sublime.packages_path()
     self.installed_packages_bak_path = "%s.bak" % (sublime.installed_packages_path())
     self.settings = sublime.load_settings(SETTINGS_USER_FILE)
Example #9
0
 def __init__(self):
     """
     Stores sublime packages paths
     """
     self.directory_list = {
         sublime.packages_path(): '',
         sublime.installed_packages_path(): '.sublime-package'
     }
     self.packages_bak_path = '%s.bak' % sublime.packages_path()
     self.installed_packages_bak_path = '%s.bak' % sublime.installed_packages_path()
Example #10
0
    def move_packages_to_backup_dirs(self):
        """
        Moves packages directories to backups
        """
        self.remove_backup_dirs()

        logger.info("Move %s to %s" % (sublime.installed_packages_path(), self.installed_packages_bak_path))
        self._safe_copy(sublime.installed_packages_path(), self.installed_packages_bak_path)
        logger.info("Move %s to %s" % (sublime.packages_path(), self.packages_bak_path))
        self._safe_copy(sublime.packages_path(), self.packages_bak_path)
Example #11
0
 def __init__(self):
     """
     Stores sublime packages paths
     """
     self.directory_list = {
         sublime.packages_path(): '',
         sublime.installed_packages_path(): '.sublime-package'
     }
     self.packages_bak_path = '%s.bak' % sublime.packages_path()
     self.installed_packages_bak_path = '%s.bak' % sublime.installed_packages_path(
     )
Example #12
0
 def __init__(self):
     """
     Stores sublime packages paths
     """
     self.directory_list = {
         sublime.packages_path(): '',
         sublime.installed_packages_path(): '.sublime-package'
     }
     self.packages_bak_path = '%s.bak' % sublime.packages_path()
     self.installed_packages_bak_path = '%s.bak' % (
         sublime.installed_packages_path())
     self.settings = sublime.load_settings(SETTINGS_USER_FILE)
Example #13
0
    def load_schemes(self):
        all_scheme_paths = []
        favorite_scheme_paths = self.get_favorites()

        try:  # use find_resources() first for ST3
            all_scheme_paths = sublime.find_resources('*.tmTheme')

        except:  # fallback to walk() for ST2
            # Load the paths for schemes contained in zipped .sublime-package files.
            for root, dirs, files in os.walk(
                    sublime.installed_packages_path()):
                for package in (package for package in files
                                if package.endswith('.sublime-package')):
                    zf = zipfile.ZipFile(
                        os.path.join(sublime.installed_packages_path(),
                                     package))
                    for filename in (filename for filename in zf.namelist()
                                     if filename.endswith('.tmTheme')):
                        filepath = os.path.join(
                            root, package, filename).replace(
                                sublime.installed_packages_path(),
                                'Packages').replace('.sublime-package',
                                                    '').replace('\\', '/')
                        all_scheme_paths.append(filepath)

            # Load the paths for schemes contained in folders.
            for root, dirs, files in os.walk(sublime.packages_path()):
                for filename in (filename for filename in files
                                 if filename.endswith('.tmTheme')):
                    filepath = os.path.join(root, filename).replace(
                        sublime.packages_path(),
                        'Packages').replace('\\', '/')
                    all_scheme_paths.append(filepath)

        # Filter schemes generated by known plugins
        regex = re.compile('\(SL\)|Color Highlighter', re.IGNORECASE)
        all_scheme_paths = [
            scheme for scheme in all_scheme_paths if not regex.search(scheme)
        ]

        # Given the paths of all the color schemes, add in the information for
        # the pretty-printed name and whether or not it's been favorited.
        all_schemes = []
        for scheme_path in all_scheme_paths:
            scheme_name = self.filter_scheme_name(scheme_path)
            favorite = ''
            is_favorited = scheme_path in favorite_scheme_paths
            if is_favorited:
                favorite = u'   \u2605'  # Put a pretty star icon next to favorited schemes. :)
            all_schemes.append([scheme_name, scheme_path, favorite])

        all_schemes.sort(key=lambda s: s[0].lower())
        return all_schemes
Example #14
0
    def move_packages_to_backup_dirs(self):
        """
        Moves packages directories to backups
        """
        self.remove_backup_dirs()

        logger.info('Move %s to %s' % (sublime.installed_packages_path(),
                                       self.installed_packages_bak_path))
        self._safe_copy(sublime.installed_packages_path(),
                        self.installed_packages_bak_path)
        logger.info('Move %s to %s' %
                    (sublime.packages_path(), self.packages_bak_path))
        self._safe_copy(sublime.packages_path(), self.packages_bak_path)
Example #15
0
def update_binary():
    bindir = os.path.join(sublime.packages_path(), usrbin)
    binpath = os.path.join(bindir, binname)
    pkgpath = os.path.join(sublime.installed_packages_path(), 'ColorPicker.sublime-package')
    respath = 'Packages/ColorPicker/lib/' + binname
    libdir = os.path.join(sublime.packages_path(), 'ColorPicker', 'lib')
    libpath = os.path.join(libdir, binname)

    bininfo = None
    bindata = None

    if os.path.exists(binpath):
        bininfo = os.stat(binpath)
    elif not os.path.exists(bindir):
        os.makedirs(bindir, 0o755)

    if os.path.exists(libpath):
        libinfo = os.stat(libpath)
        if bininfo == None or bininfo[ST_MTIME] < libinfo[ST_MTIME]:
            with open(libpath, 'rb') as libfile:
                bindata = libfile.read()
                libfile.close()
    elif sublime_version == 3 and os.path.exists(pkgpath):
        pkginfo = os.stat(pkgpath)
        if bininfo == None or bininfo[ST_MTIME] < pkginfo[ST_MTIME]:
            bindata = sublime.load_binary_resource(respath)

    if bindata != None:
        print("* Updating " + binpath)
        with open(binpath, 'wb') as binfile:
            binfile.write(bindata)
            binfile.close()

    if not os.access(binpath, os.X_OK):
        os.chmod(binpath, 0o755)
Example #16
0
    def run(self, edit):
        def_path = join(dirname(sublime.executable_path()), 'Packages')
        default = set([re.sub(r'\.sublime-package', '', p) for p in listdir(def_path)])
        user = get_user_packages() - get_dependencies()
        pc = set([re.sub(r'\.sublime-package', '', p) for p in listdir(sublime.installed_packages_path())])
        disabled = set(sublime.load_settings('Preferences.sublime-settings').get('ignored_packages', []))
        ignored = set(["User", "bz2", "0_package_control_loader", ".DS_Store"])

        enabled_def = default - disabled
        disabled_def = default - enabled_def
        pc_total = (pc | (user - default)) - ignored
        enabled_pc = pc_total - disabled
        disabled_pc = pc_total - enabled_pc
        total = (pc | user | disabled | default) - ignored
        enabled = total - disabled

        Row = namedtuple('Row', ['Type', 'Total', 'Disabled', 'Enabled'])
        row1 = Row("Built-in", len(default), len(disabled_def), len(enabled_def))
        row2 = Row("Package Control", len(pc_total), len(disabled_pc), len(enabled_pc))
        row3 = Row("Total", len(total), len(disabled), len(enabled))
        results = pprinttable([row1, row2, row3])
        sep_line = "\n————————————————————————————————————————————\n\t"

        out = self.view.window().get_output_panel("stats")
        self.view.window().run_command("show_panel", {"panel": "output.stats"})
        out.insert(edit, out.size(), results)
        out.insert(edit, out.size(), "\n\nPackage Control Packages (Enabled):" + sep_line + '\n\t'.join(sorted(enabled_pc, key=lambda s: s.lower())))
        out.insert(edit, out.size(), "\n\nPackage Control Packages (Disabled):" + sep_line + '\n\t'.join(sorted(disabled_pc, key=lambda s: s.lower())))
        out.insert(edit, out.size(), "\n\nDefault Packages (Enabled):" + sep_line + '\n\t'.join(sorted(enabled_def, key=lambda s: s.lower())))
        out.insert(edit, out.size(), "\n\nDefault Packages (Disabled):" + sep_line + '\n\t'.join(sorted(disabled_def, key=lambda s: s.lower())))
def get_changed_files(files):
    basepath = sublime.installed_packages_path()
    changed = []

    for package, path, timestamp, hash_value in files:
        package_path = os.path.join(basepath, package + ".sublime-package")

        try:
            mtime = os.stat(package_path).st_mtime
        except FileNotFoundError:
            sublime.error_message("{}: package {} not found".format(PACKAGE_NAME, package))
            continue

        if timestamp == mtime:
            continue

        zf = ZipFile(package_path)

        try:
            content = zf.read(path)
        except KeyError:
            sublime.error_message("{}: there is no {} in {}".format(PACKAGE_NAME, path, package))
            continue

        new_hash_value = get_hash(content)

        if new_hash_value == hash_value:
            continue

        changed.append([package, path, mtime, new_hash_value])

    return changed
    def remove_package(self, package):
        # Check for installed_package path
        try:
            installed_package_path = os.path.join(sublime.installed_packages_path(), package + ".sublime-package")
            if os.path.exists(installed_package_path):
                os.remove(installed_package_path)
        except:
            return False

        # Check for pristine_package_path path
        try:
            pristine_package_path = os.path.join(
                os.path.dirname(sublime.packages_path()), "Pristine Packages", package + ".sublime-package"
            )
            if os.path.exists(pristine_package_path):
                os.remove(pristine_package_path)
        except:
            return False

        # Check for package dir
        try:
            os.chdir(sublime.packages_path())
            package_dir = os.path.join(sublime.packages_path(), package)
            if os.path.exists(package_dir):
                if shutil.rmtree(package_dir):
                    open(os.path.join(package_dir, "package-control.cleanup"), "w").close()
        except:
            return False

        return True
Example #19
0
    def _install(self):
        """
        RUNS IN A THREAD

        Downloads and then installs Package Control, alerting the user to
        the result
        """

        try:
            package_data = self._download()
            if package_data is None:
                sublime.set_timeout(self._show_error, 10)
                return

            dest = os.path.join(sublime.installed_packages_path(),
                                self.filename)

            with open(dest, 'wb') as f:
                f.write(package_data)

            sublime.set_timeout(self._show_success, 10)

        except (Exception) as e:
            print(self.error_prefix + str(e))
            sublime.set_timeout(self._show_error, 10)
Example #20
0
def plugin_loaded():
    if DEBUG:
        UTC_TIME = datetime.utcnow()
        PYTHON = sys.version_info[:3]
        VERSION = sublime.version()
        PLATFORM = sublime.platform()
        ARCH = sublime.arch()
        PACKAGE = sublime.packages_path()
        INSTALL = sublime.installed_packages_path()

        message = ('Jekyll debugging mode enabled...\n'
                   '\tUTC Time: {time}\n'
                   '\tSystem Python: {python}\n'
                   '\tSystem Platform: {plat}\n'
                   '\tSystem Architecture: {arch}\n'
                   '\tSublime Version: {ver}\n'
                   '\tSublime Packages Path: {package}\n'
                   '\tSublime Installed Packages Path: {install}\n').format(
                       time=UTC_TIME,
                       python=PYTHON,
                       plat=PLATFORM,
                       arch=ARCH,
                       ver=VERSION,
                       package=PACKAGE,
                       install=INSTALL)

        sublime.status_message('Jekyll: Debugging enabled...')
        debug('Plugin successfully loaded.', prefix='\n\nJekyll', level='info')
        debug(message, prefix='Jekyll', level='info')
Example #21
0
def update_resources(*target):
    targetpath = os.path.join(sublime.packages_path(), 'User', PKGNAME, *target)
    targetdir = os.path.dirname(targetpath)
    respath = 'Packages/%s/' % PKGNAME + "/".join(target)
    pkgpath = os.path.join(sublime.installed_packages_path(), '%s.sublime-package' % PKGNAME)
    unpkgpath = os.path.join(sublime.packages_path(), PKGNAME, *target)

    if os.path.exists(targetpath):
        targetinfo = os.stat(targetpath)
    else:
        if not os.path.exists(targetdir):
            os.makedirs(targetdir, 0o755)
        targetinfo = None

    if os.path.exists(unpkgpath):
        pkginfo = os.stat(unpkgpath)
    elif os.path.exists(pkgpath):
        pkginfo = os.stat(pkgpath)
    else:
        return

    if targetinfo is None or targetinfo.st_mtime < pkginfo.st_mtime:
        print("* Updating " + targetpath)
        if sublime.version() < '3000':
            shutil.copy2(unpkgpath, targetpath)
        else:
            data = sublime.load_binary_resource(respath)
            with open(targetpath, 'wb') as f:
                f.write(data)
                f.close()

    if not os.access(targetpath, os.X_OK):
        os.chmod(targetpath, 0o755)
Example #22
0
    def list_packages(self, unpacked_only=False):
        """
        :param unpacked_only:
            Only list packages that are not inside of .sublime-package files

        :return: A list of all installed, non-default, package names
        """

        package_names = os.listdir(sublime.packages_path())
        package_names = [path for path in package_names if
            os.path.isdir(os.path.join(sublime.packages_path(), path))]

        if int(sublime.version()) > 3000 and unpacked_only == False:
            package_files = os.listdir(sublime.installed_packages_path())
            package_names += [f.replace('.sublime-package', '') for f in package_files if re.search('\.sublime-package$', f) != None]

        # Ignore things to be deleted
        ignored = ['User']
        for package in package_names:
            cleanup_file = os.path.join(sublime.packages_path(), package,
                'package-control.cleanup')
            if os.path.exists(cleanup_file):
                ignored.append(package)

        packages = list(set(package_names) - set(ignored) -
            set(self.list_default_packages()))
        packages = sorted(packages, key=lambda s: s.lower())

        return packages
Example #23
0
    def get_coffee(this):
        import os

        # package locations
        locations = [sublime.installed_packages_path(), sublime.packages_path()]

        # supported packages
        packages = ["Better CoffeeScript", "CoffeeScript", "IcedCoffeeScript", "Mongoose CoffeeScript"]

        # iterate over packages locations
        for location in locations:
            # iterate over packages installed with Package Control
            for package in packages:
                # is "ignored_package"?
                settings = sublime.load_settings("Preferences.sublime-settings").get("ignored_packages")
                if package in settings:
                    continue

                if os.path.isfile(location + "/" + package + ".sublime-package") is True:
                    if package is "IcedCoffeeScript":
                        this.view.set_syntax_file("Packages/IcedCoffeeScript/Syntaxes/IcedCoffeeScript.tmLanguage")
                        return True
                    elif package is "Mongoose CoffeeScript":
                        this.view.set_syntax_file("Packages/Mongoose CoffeeScript/CoffeeScript.tmLanguage")
                        return True
                    else:
                        this.view.set_syntax_file("Packages/" + package + "/CoffeeScript.tmLanguage")
                        return True

        sublime.message_dialog(
            "Atomizr\n\nAutomatic conversion requires a supported CoffeeScript package to be installed"
        )
        return False
Example #24
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
Example #25
0
def list_package_files(package, ignore_patterns=[]):
    """
    List files in the specified package.
    """
    package_path = os.path.join(sublime.packages_path(), package, "")
    path = None
    file_set = set()
    file_list = []
    if os.path.exists(package_path):
        for root, directories, filenames in os.walk(package_path):
            temp = root.replace(package_path, "")
            for filename in filenames:
                file_list.append(os.path.join(temp, filename))

    file_set.update(file_list)

    if VERSION >= 3006:
        sublime_package = package + ".sublime-package"
        packages_path = sublime.installed_packages_path()

        if os.path.exists(os.path.join(packages_path, sublime_package)):
            file_set.update(_list_files_in_zip(packages_path, sublime_package))

        packages_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages"

        if os.path.exists(os.path.join(packages_path, sublime_package)):
           file_set.update(_list_files_in_zip(packages_path, sublime_package))

    file_list = []

    for filename in file_set:
        if not _ignore_file(filename, ignore_patterns):
            file_list.append(_normalize_to_sublime_path(filename))

    return sorted(file_list)
Example #26
0
def get_package_and_resource_name(path):
    """
    This method will return the package name and resource name from a path.

    Arguments:
    path    Path to parse for package and resource name.
    """
    package = None
    resource = None
    path = _normalize_to_sublime_path(path)
    if os.path.isabs(path):
        packages_path = _normalize_to_sublime_path(sublime.packages_path())
        if path.startswith(packages_path):
            package, resource = _search_for_package_and_resource(path, packages_path)

        if int(sublime.version()) >= 3006:
            packages_path = _normalize_to_sublime_path(sublime.installed_packages_path())
            if path.startswith(packages_path):
                package, resource = _search_for_package_and_resource(path, packages_path)

            packages_path = _normalize_to_sublime_path(os.path.dirname(sublime.executable_path()) + os.sep + "Packages")
            if path.startswith(packages_path):
                package, resource = _search_for_package_and_resource(path, packages_path)
    else:
        path = re.sub(r"^Packages/", "", path)
        split = re.split(r"/", path, 1)
        package = split[0]
        package = package.replace(".sublime-package", "")
        resource = split[1]

    return (package, resource)
Example #27
0
def get_package_modules(pkg_name):
    in_installed_path = functools.partial(
        path_contains,
        os.path.join(
            sublime.installed_packages_path(),
            pkg_name + '.sublime-package'
        )
    )

    in_package_path = functools.partial(
        path_contains,
        os.path.join(sublime.packages_path(), pkg_name)
    )

    def module_in_package(module):
        file = getattr(module, '__file__', '')
        paths = getattr(module, '__path__', ())
        return (
            in_installed_path(file) or any(map(in_installed_path, paths)) or
            in_package_path(file) or any(map(in_package_path, paths))
        )

    return {
        name: module
        for name, module in sys.modules.items()
        if module_in_package(module)
    }
Example #28
0
    def update_resource(binname):
        # from https://github.com/weslly/ColorPicker/blob/master/sublimecp.py=
        targetdir = os.path.join(sublime.packages_path(), 'User', 'R-Box', 'bin')
        targetpath = os.path.join(targetdir, binname)
        respath = 'Packages/R-Box/bin/' + binname
        pkgpath = os.path.join(sublime.installed_packages_path(), 'R-Box.sublime-package')
        unpkgpath = os.path.join(sublime.packages_path(), 'R-Box', 'bin', binname)

        if os.path.exists(targetpath):
            targetinfo = os.stat(targetpath)
        else:
            if not os.path.exists(targetdir):
                os.makedirs(targetdir, 0o755)
            targetinfo = None

        if os.path.exists(unpkgpath):
            pkginfo = os.stat(unpkgpath)
        elif os.path.exists(pkgpath):
            pkginfo = os.stat(pkgpath)
        else:
            return

        if targetinfo == None or targetinfo.st_mtime < pkginfo.st_mtime:
            data = sublime.load_binary_resource(respath)
            print("* Updating " + targetpath)
            with open(targetpath, 'wb') as binfile:
                binfile.write(data)
                binfile.close()

        if not os.access(targetpath, os.X_OK):
            os.chmod(targetpath, 0o755)
def list_package_files(package, ignore_patterns=[]):
    """
    List files in the specified package.
    """
    package_path = os.path.join(sublime.packages_path(), package, "")
    path = None
    file_set = set()
    file_list = []
    if os.path.exists(package_path):
        for root, directories, filenames in os.walk(package_path):
            temp = root.replace(package_path, "")
            for filename in filenames:
                file_list.append(os.path.join(temp, filename))

    file_set.update(file_list)

    if VERSION >= 3006:
        sublime_package = package + ".sublime-package"
        packages_path = sublime.installed_packages_path()

        if os.path.exists(os.path.join(packages_path, sublime_package)):
            file_set.update(_list_files_in_zip(packages_path, sublime_package))

        packages_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages"

        if os.path.exists(os.path.join(packages_path, sublime_package)):
           file_set.update(_list_files_in_zip(packages_path, sublime_package))

    file_list = []

    for filename in file_set:
        if not _ignore_file(filename, ignore_patterns):
            file_list.append(_normalize_to_sublime_path(filename))

    return sorted(file_list)
Example #30
0
def _read_zip_file(package, relative_path, binary=False, debug=False):
    zip_path = os.path.join(sublime.installed_packages_path(),
        package + '.sublime-package')

    if not os.path.exists(zip_path):
        return False

    try:
        package_zip = zipfile.ZipFile(zip_path, 'r')

    except (zipfile.BadZipfile):
        console_write(u'An error occurred while trying to unzip the sublime-package file for %s.' % package, True)
        return False

    try:
        contents = package_zip.read(relative_path)
        if not binary:
            contents = contents.decode('utf-8')
        return contents

    except (KeyError) as e:
        pass

    except (IOError) as e:
        message = unicode_from_os(e)
        console_write(u'Unable to read file from sublime-package file for %s due to an invalid filename' % package, True)

    except (UnicodeDecodeError):
        console_write(u'Unable to read file from sublime-package file for %s due to an invalid filename or character encoding issue' % package, True)

    return False
Example #31
0
def find_snippets():
	global snippets

	new_snippets = []
	# Packages folder
	for root, dirs, files in os.walk(sublime.packages_path()):
		for name in files:
			try:
				ext = os.path.splitext(name)[-1]
				if ext in ('.sublime-snippet', '.tmSnippet'):
					path = os.path.join(root, name)
					f = open(path, 'rb')
					new_snippets.append(parse_snippet(f, ext))
					f.close()
				elif ext == '.sublime-package':
					new_snippets += read_zip(path)

			except:
				pass
	
	# Installed Packages folder
	for root, dirs, files in os.walk(sublime.installed_packages_path()):
		for name in files:
			try:
				ext = os.path.splitext(name)[-1]
				if ext == '.sublime-package':
					path = os.path.join(root, name)
					new_snippets += read_zip(path)
			except:
				pass

	snippets = new_snippets
Example #32
0
def patch():
    smp = os.path.join(sublime.installed_packages_path(), PLUGIN_NAME)
    path = smp + '.sublime-package'
    if not os.path.isfile(path):
        print('File does not exist: %s' % path)
        return None

    linsp = SM3.core.linsp
    verifyu = linsp.VERIFYU
    if URL_NEW == linsp.b64d(verifyu):
        print('File already patched.')
        return None

    verifyn = linsp.b64e(linsp.b64d(verifyu).replace(URL_OLD, URL_NEW))
    bytes_a = verifyu.encode('utf-8')
    bytes_b = verifyn.encode('utf-8')
    if bytes_a != bytes_b and len(bytes_a) == len(bytes_b):
        src = 'Packages/' + PLUGIN_NAME + '/core/linsp.pyc'
        bytes_old = sublime.load_binary_resource(src)
        bytes_new = bytes_old.replace(bytes_a, bytes_b)
        if bytes_old != bytes_new:
            unpack(smp, smp)
            with open(os.path.join(smp, 'core', 'linsp.pyc'), 'wb') as fhr:
                fhr.write(bytes_new)
            pack(smp, smp)
            shutil.rmtree(smp, ignore_errors=True)
            return True
        print('File already patched.')
    print('File has been raped by chuck borys.')
    return None
def get_package_modules(pkg_name):
    in_installed_path = functools.partial(
        path_contains,
        os.path.join(
            sublime.installed_packages_path(),
            pkg_name + '.sublime-package'
        )
    )

    in_package_path = functools.partial(
        path_contains,
        os.path.join(sublime.packages_path(), pkg_name)
    )

    def module_in_package(module):
        file = getattr(module, '__file__', '')
        paths = getattr(module, '__path__', ())
        return (
            in_installed_path(file) or any(map(in_installed_path, paths)) or
            in_package_path(file) or any(map(in_package_path, paths))
        )

    return {
        name: module
        for name, module in sys.modules.items()
        if module_in_package(module)
    }
Example #34
0
    def _subst_for_translate(window):
        """ Return all available substitutions"""
        import locale
        res = {
            "packages": sublime.packages_path(),
            "installed_packages": sublime.installed_packages_path()
        }
        if window.folders():
            res["folder"] = window.folders()[0]
        res["editor"] = "subl -w"
        res["win_cmd_encoding"] = "utf8"
        if sublime.platform() == "windows":
            res["win_cmd_encoding"] = locale.getdefaultlocale()[1]
            res["editor"] = '"%s"' % (sys.executable,)
        av = window.active_view()
        if av is None:
            return res
        filename = av.file_name()
        if not filename:
            return res
        filename = os.path.abspath(filename)
        res["file"] = filename
        res["file_path"] = os.path.dirname(filename)
        res["file_basename"] = os.path.basename(filename)
        if 'folder' not in res:
            res["folder"] = res["file_path"]

        if sublime.load_settings(SETTINGS_FILE).get("use_build_system_hack", False):
            project_settings = sublimerepl_build_system_hack.get_project_settings(window)
            res.update(project_settings)

        return res
Example #35
0
def do(renderer, keymap_counter):
	default_packages = ['Default']
	user_packages = ['User']
	global_settings = sublime.load_settings("Preferences.sublime-settings")
	ignored_packages = global_settings.get("ignored_packages", [])
	package_control_settings = sublime.load_settings("Package Control.sublime-settings")
	installed_packages = package_control_settings.get("installed_packages", [])
	if len(installed_packages) == 0:
		includes = ('.sublime-package')
		os_packages = []
		for (root, dirs, files) in os.walk(sublime.installed_packages_path()):
			for file in files:
				if file.endswith(includes):
					os_packages.append(file.replace(includes, ''))
		for (root, dirs, files) in os.walk(sublime.packages_path()):
			for dir in dirs:
				os_packages.append(dir)
			break	# just the top level
		installed_packages = []
		[installed_packages.append(package) for package in os_packages if package not in installed_packages]

	diff = lambda l1,l2: [x for x in l1 if x not in l2]
	active_packages = diff( default_packages + installed_packages + user_packages, ignored_packages)

	keymapsExtractor = KeymapsExtractor(active_packages, keymap_counter)
	worker_thread = WorkerThread(keymapsExtractor, renderer)
	worker_thread.start()
	ThreadProgress(worker_thread, 'Searching ' + MY_NAME, 'Done.', keymap_counter)
Example #36
0
    def remove_package(self, package):
        # Check for installed_package path
        try:
            installed_package_path = os.path.join(
                sublime.installed_packages_path(),
                package + ".sublime-package")
            if os.path.exists(installed_package_path):
                os.remove(installed_package_path)
        except:
            return False

        # Check for pristine_package_path path
        try:
            pristine_package_path = os.path.join(
                os.path.dirname(sublime.packages_path()), "Pristine Packages",
                package + ".sublime-package")
            if os.path.exists(pristine_package_path):
                os.remove(pristine_package_path)
        except:
            return False

        # Check for package dir
        try:
            os.chdir(sublime.packages_path())
            package_dir = os.path.join(sublime.packages_path(), package)
            if os.path.exists(package_dir):
                if shutil.rmtree(package_dir):
                    open(os.path.join(package_dir, 'package-control.cleanup'),
                         'w').close()
        except:
            return False

        return True
def _zip_file_exists(package, relative_path):
    zip_path = os.path.join(sublime.installed_packages_path(),
        package + '.sublime-package')

    if not os.path.exists(zip_path):
        return False

    try:
        package_zip = zipfile.ZipFile(zip_path, 'r')

    except (zipfile.BadZipfile):
        console_write(
            u'''
            An error occurred while trying to unzip the sublime-package file
            for %s.
            ''',
            package
        )
        return False

    try:
        package_zip.getinfo(relative_path)
        return True

    except (KeyError):
        return False
Example #38
0
    def is_visible(self):
        ipp_path = os.path.join(sublime.installed_packages_path(),
                                self.filename)
        p_path = os.path.join(sublime.packages_path(),
                              self.filename.replace('.sublime-package', ''))

        return not os.path.exists(ipp_path) and not os.path.exists(p_path)
Example #39
0
def get_packages_list(ignore_packages=True, ignore_patterns=[]):
    """
    Return a list of packages.
    """
    package_set = set()
    package_set.update(_get_packages_from_directory(sublime.packages_path()))

    if int(sublime.version()) >= 3006:
        package_set.update(
            _get_packages_from_directory(sublime.installed_packages_path(),
                                         ".sublime-package"))

        executable_package_path = os.path.dirname(
            sublime.executable_path()) + os.sep + "Packages"
        package_set.update(
            _get_packages_from_directory(executable_package_path,
                                         ".sublime-package"))

    if ignore_packages:
        ignored_list = sublime.load_settings(
            "Preferences.sublime-settings").get("ignored_packages", [])
    else:
        ignored_list = []

    for package in package_set:
        for pattern in ignore_patterns:
            if re.match(pattern, package):
                ignored_list.append(package)
                break

    for ignored in ignored_list:
        package_set.discard(ignored)

    return sorted(list(package_set))
Example #40
0
 def get_paths(self):
     paths = {}
     paths["packages"] = sublime.packages_path()
     paths["packages_user"] = os.path.join(sublime.packages_path(),
                                           USER_FOLDER)
     paths["installed_packages"] = sublime.installed_packages_path()
     return paths
Example #41
0
 def get_usages_data(self):
     return {
         "SchemaVersion":
         Constant.get_usages_schema_version(),
         "Version":
         Constant.get_version(),
         "DebugMode":
         str.lower(str(Settings().get("debug_mode"))),
         "AsPackage":
         str.lower(
             str(
                 os.path.exists(
                     os.path.join(sublime.installed_packages_path(),
                                  "Javatar.sublime-package")))),
         "StartupTime":
         "{0:.2f}s".format(Constant.startup_time),
         "ActionHistory":
         str.lower(str(Settings().get("enable_action_history"))),
         "SublimeVersion":
         str(sublime.version()),
         "Platform":
         sublime.platform(),
         "Architecture":
         sublime.arch()
     }
Example #42
0
def init():
    if v == '3' and (sublime.installed_packages_path() in pDir):
        pkgDir = os.path.join(sublime.packages_path(), pName)
        if not os.path.isdir(pkgDir):
            pkgFile = os.path.dirname(os.path.abspath(__file__))
            unpackSelf(pkgFile, pkgDir)
            return
    locale = ''
    firstRun = False
    fFile = os.path.join(pDir, '.firstRun')
    if not os.path.isfile(fFile):
        firstRun = True
        backupMenu()
        open(fFile, 'wt').write('')
        locale = getSetting('locale', '')
    eDir = os.path.join(mDir, version, 'en')
    if v == '3' and not os.path.isdir(eDir):
        eFile = sublime.executable_path()
        dFile = os.path.join(os.path.dirname(eFile), 'Packages',
                             'Default.sublime-package')
        unpackMenu(dFile, eDir)
    makeMenu(locale, firstRun)
    makeCommand(locale, firstRun)
    setLocale(locale, firstRun)

    s = sublime.load_settings(sFile)
    s.add_on_change('locale', updateLocale)
Example #43
0
def read_js(file_path, use_unicode=True):
	file_path = os.path.normpath(file_path)
	if hasattr(sublime, 'load_resource'):
		rel_path = None
		for prefix in [sublime.packages_path(), sublime.installed_packages_path()]:
			if file_path.startswith(prefix):
				rel_path = os.path.join('Packages', file_path[len(prefix) + 1:])
				break

		if rel_path:
			rel_path = rel_path.replace('.sublime-package', '')
			# for Windows we have to replace slashes
			# print('Loading %s' % rel_path)
			rel_path = rel_path.replace('\\', '/')
			return sublime.load_resource(rel_path)

	if use_unicode:
		f = codecs.open(file_path, 'r', 'utf-8')
	else:
		f = open(file_path, 'r')

	content = f.read()
	f.close()

	return content
Example #44
0
    def list_packages(self, unpacked_only=False):
        """
        :param unpacked_only:
            Only list packages that are not inside of .sublime-package files

        :return: A list of all installed, non-default, package names
        """

        package_names = os.listdir(sublime.packages_path())
        package_names = [path for path in package_names if
            os.path.isdir(os.path.join(sublime.packages_path(), path))]

        if int(sublime.version()) > 3000 and unpacked_only == False:
            package_files = os.listdir(sublime.installed_packages_path())
            package_names += [f.replace('.sublime-package', '') for f in package_files if re.search('\.sublime-package$', f) != None]

        # Ignore things to be deleted
        ignored = ['User']
        for package in package_names:
            cleanup_file = os.path.join(sublime.packages_path(), package,
                'package-control.cleanup')
            if os.path.exists(cleanup_file):
                ignored.append(package)

        packages = list(set(package_names) - set(ignored) -
            set(self.list_default_packages()))
        packages = sorted(packages, key=lambda s: s.lower())

        return packages
Example #45
0
def read_js(file_path, use_unicode=True):
    file_path = os.path.normpath(file_path)
    if hasattr(sublime, 'load_resource'):
        rel_path = None
        for prefix in [
                sublime.packages_path(),
                sublime.installed_packages_path()
        ]:
            if file_path.startswith(prefix):
                rel_path = os.path.join('Packages',
                                        file_path[len(prefix) + 1:])
                break

        if rel_path:
            rel_path = rel_path.replace('.sublime-package', '')
            # for Windows we have to replace slashes
            # print('Loading %s' % rel_path)
            rel_path = rel_path.replace('\\', '/')
            return sublime.load_resource(rel_path)

    if use_unicode:
        f = codecs.open(file_path, 'r', 'utf-8')
    else:
        f = open(file_path, 'r')

    content = f.read()
    f.close()

    return content
Example #46
0
def plugin_loaded():
    if DEBUG:
        UTC_TIME = datetime.utcnow()
        PYTHON = sys.version_info[:3]
        VERSION = sublime.version()
        PLATFORM = sublime.platform()
        ARCH = sublime.arch()
        PACKAGE = sublime.packages_path()
        INSTALL = sublime.installed_packages_path()

        message = (
            'Jekyll debugging mode enabled...\n'
            '\tUTC Time: {time}\n'
            '\tSystem Python: {python}\n'
            '\tSystem Platform: {plat}\n'
            '\tSystem Architecture: {arch}\n'
            '\tSublime Version: {ver}\n'
            '\tSublime Packages Path: {package}\n'
            '\tSublime Installed Packages Path: {install}\n'
        ).format(time=UTC_TIME, python=PYTHON, plat=PLATFORM, arch=ARCH,
                 ver=VERSION, package=PACKAGE, install=INSTALL)

        sublime.status_message('Jekyll: Debugging enabled...')
        debug('Plugin successfully loaded.', prefix='\n\nJekyll', level='info')
        debug(message, prefix='Jekyll', level='info')
Example #47
0
def update_binary():
    bindir = os.path.join(sublime.packages_path(), usrbin)
    binpath = os.path.join(bindir, binname)
    pkgpath = os.path.join(sublime.installed_packages_path(), 'ColorPicker.sublime-package')
    respath = 'Packages/ColorPicker/lib/' + binname
    libdir = os.path.join(sublime.packages_path(), 'ColorPicker', 'lib')
    libpath = os.path.join(libdir, binname)

    bininfo = None
    bindata = None

    if os.path.exists(binpath):
        bininfo = os.stat(binpath)
    elif not os.path.exists(bindir):
        os.makedirs(bindir, 0o755)

    if os.path.exists(libpath):
        libinfo = os.stat(libpath)
        if bininfo == None or bininfo[ST_MTIME] < libinfo[ST_MTIME]:
            with open(libpath, 'rb') as libfile:
                bindata = libfile.read()
                libfile.close()
    elif sublime_version == 3 and os.path.exists(pkgpath):
        pkginfo = os.stat(pkgpath)
        if bininfo == None or bininfo[ST_MTIME] < pkginfo[ST_MTIME]:
            bindata = sublime.load_binary_resource(respath)

    if bindata != None:
        print("* Updating " + binpath)
        with open(binpath, 'wb') as binfile:
            binfile.write(bindata)
            binfile.close()

    if not os.access(binpath, os.X_OK):
        os.chmod(binpath, 0o755)
 def run(self):
   # Get list of Installed Packages
   self.packages_dir_path = sublime.installed_packages_path()
   self.packages_list = [ p for p in os.listdir(self.packages_dir_path) if p.endswith('.sublime-package') ]
   
   # Show quick panel
   self.window.show_quick_panel(self.packages_list, self.on_package_selected)
Example #49
0
def has_colorschemeunit():
    if "ColorSchemeUnit.sublime-package" in os.listdir(
            sublime.installed_packages_path()):
        return True
    elif "ColorSchemeUnit" in os.listdir(sublime.packages_path()):
        return True
    return False
Example #50
0
    def run(self):
        ignored_packages_list = sublime.load_settings(
            "Preferences.sublime-settings").get("ignored_packages", [])

        package_paths_list = []

        if (ST2):
            packages_path = package_paths_list.append(sublime.packages_path())
            if (packages_path):
                package_paths_list.append(packages_path)
        else:
            packages_path = os.path.dirname(
                sublime.installed_packages_path()) + os.sep + "Packages"
            if (packages_path):
                package_paths_list.append(packages_path)

            packages_path = os.path.dirname(
                sublime.executable_path()) + os.sep + "Packages"
            if (packages_path):
                package_paths_list.append(packages_path)

        key_binding_extractor = KeyBindingExtractor(self.plugin_settings,
                                                    package_paths_list,
                                                    ignored_packages_list)
        key_binding_extractor.start()
        self.handle_key_binding_extraction(key_binding_extractor)
Example #51
0
    def pack_packages(self, password=None, backup=False, exclude_from_package_control=True, **kwargs):
        """
        Compresses Packages and Installed Packages
        """
        excluded_dirs = kwargs.get("excluded_dirs", [])
        packages_root_path = os.path.basename(sublime.packages_path())
        installed_packages_root_path = os.path.basename(sublime.installed_packages_path())

        # Append blacklisted Packages to excluded dirs
        for package in blacklist.packages:
            excluded_dirs.append(os.path.join(packages_root_path, package))

        # Append blacklisted Installed Packages to excluded dirs
        for package in blacklist.installed_packages:
            excluded_dirs.append(os.path.join(installed_packages_root_path, package))

        # Append custom ignored packages
        for package in blacklist.get_ignored_packages():
            excluded_dirs.append(package)

        #  Add Package Control excludes
        if exclude_from_package_control and not backup:
            excluded_dirs.extend(self._excludes_from_package_control())

        logger.info("Excluded dirs: %s" % excluded_dirs)
        kwargs["excluded_dirs"] = excluded_dirs

        # Generate a temporary output filename if necessary
        if "output_filename" not in kwargs:
            kwargs["output_filename"] = generate_temp_filename()
        self._run_executable("a", password=password, **kwargs)
        return kwargs["output_filename"]
Example #52
0
 def test_from_file_path_installed_packages(self):
     self.assertEqual(
         ResourcePath.from_file_path(
             Path(sublime.installed_packages_path(), 'test_package.sublime-package', 'foo.py')
         ),
         ResourcePath("Packages/test_package/foo.py")
     )
Example #53
0
    def on_activated(self, view):
        point = view.sel()[0].b
        if not view.score_selector(point, "text.tex.latex"):
            return

        # Checking whether LaTeX-cwl is installed
        global CWL_COMPLETION
        if os.path.exists(sublime.packages_path() + "/LaTeX-cwl") or \
            os.path.exists(sublime.installed_packages_path() + "/LaTeX-cwl.sublime-package"):
            CWL_COMPLETION = True

        if CWL_COMPLETION:
            g_settings = sublime.load_settings("Preferences.sublime-settings")
            acts = g_settings.get("auto_complete_triggers", [])

            # Whether auto trigger is already set in Preferences.sublime-settings
            TEX_AUTO_COM = False
            for i in acts:
                if i.get("selector") == "text.tex.latex" and i.get("characters") == "\\":
                    TEX_AUTO_COM = True

            if not TEX_AUTO_COM:
                acts.append({
                    "characters": "\\",
                    "selector": "text.tex.latex"
                })
                g_settings.set("auto_complete_triggers", acts)
def get_package_and_resource_name(path):
    """
    This method will return the package name and resource name from a path.

    Arguments:
    path    Path to parse for package and resource name.
    """
    package = None
    resource = None
    path = _normalize_to_sublime_path(path)
    if os.path.isabs(path):
        packages_path = _normalize_to_sublime_path(sublime.packages_path())
        if path.startswith(packages_path):
            package, resource = _search_for_package_and_resource(path, packages_path)

        if int(sublime.version()) >= 3006:
            packages_path = _normalize_to_sublime_path(sublime.installed_packages_path())
            if path.startswith(packages_path):
                package, resource = _search_for_package_and_resource(path, packages_path)

            packages_path = _normalize_to_sublime_path(os.path.dirname(sublime.executable_path()) + os.sep + "Packages")
            if path.startswith(packages_path):
                package, resource = _search_for_package_and_resource(path, packages_path)
    else:
        path = re.sub(r"^Packages/", "", path)
        split = re.split(r"/", path, 1)
        package = split[0]
        package = package.replace(".sublime-package", "")
        resource = split[1]

    return (package, resource)
Example #55
0
    def __init__(self, name_list=None):
        self._list = dict()
        self._disabled = 0
        self._dependencies = 0

        # Maps lower cased package names to listed packages on case insensitive
        # systems.
        self._case_list = dict() if _wrap("ABC") == _wrap("abc") else None

        if name_list is not None:
            if isinstance(name_list, str):
                name_list = [name_list]

            if _wrap("Abc") == _wrap("abc"):
                name_list = [_wrap(name) for name in name_list]

        self._shipped = self.__find_pkgs(PackageInfo.shipped_packages_path,
                                         name_list,
                                         shipped=True)
        self._installed = self.__find_pkgs(sublime.installed_packages_path(),
                                           name_list)
        self._unpacked = self.__find_pkgs(sublime.packages_path(),
                                          name_list,
                                          packed=False)

        for pkg in self._list.values():
            # Check if the package is a dependency and then load it's metadata.
            pkg._check_if_depdendency()
            pkg._load_metadata()

            # Count it as a dependency
            if pkg.is_dependency:
                self._dependencies += 1
def get_packages_list(ignore_packages=True, ignore_patterns=[]):
    """
    Return a list of packages.
    """
    package_set = set()
    package_set.update(_get_packages_from_directory(sublime.packages_path()))

    if int(sublime.version()) >= 3006:
        package_set.update(_get_packages_from_directory(sublime.installed_packages_path(), ".sublime-package"))

        executable_package_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages"
        package_set.update(_get_packages_from_directory(executable_package_path, ".sublime-package"))


    if ignore_packages:
        ignored_list = sublime.load_settings(
            "Preferences.sublime-settings").get("ignored_packages", [])
    else:
        ignored_list = []

    for package in package_set:
        for pattern in ignore_patterns:
            if re.match(pattern, package):
                ignored_list.append(package)
                break

    for ignored in ignored_list:
        package_set.discard(ignored)

    return sorted(list(package_set))
Example #57
0
    def _subst_for_translate(window):
        """ Return all available substitutions"""
        import locale
        res = {
            "packages": sublime.packages_path(),
            "installed_packages": sublime.installed_packages_path()
        }
        res["editor"] = "subl -w"
        res["win_cmd_encoding"] = "utf8"
        if sublime.platform() == "windows":
            res["win_cmd_encoding"] = locale.getdefaultlocale()[1]
            res["editor"] = '"%s"' % (sys.executable,)
        av = window.active_view()
        if av is None:
            return res
        filename = av.file_name()
        if not filename:
            return res
        filename = os.path.abspath(filename)
        res["file"] = filename
        res["file_path"] = os.path.dirname(filename)
        res["file_basename"] = os.path.basename(filename)
        if window.folders():
            res["folder"] = window.folders()[0]
        else:
            res["folder"] = res["file_path"]

        if sublime.load_settings(SETTINGS_FILE).get("use_build_system_hack", False):
            project_settings = sublimerepl_build_system_hack.get_project_settings(window)
            res.update(project_settings)

        return res
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.replace("\r\n", "\n").replace("\r", "\n")