Example #1
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 #2
0
    def copy_linter(self, name):
        """Copy the template linter to a new linter with the given name."""

        self.name = name
        self.fullname = 'SublimeLinter-contrib-{}'.format(name)
        self.dest = os.path.join(sublime.packages_path(), self.fullname)

        if os.path.exists(self.dest):
            sublime.error_message('The plugin “{}” already exists.'.format(self.fullname))
            return

        src = os.path.join(sublime.packages_path(), persist.PLUGIN_DIRECTORY, 'linter-plugin-template')
        self.temp_dir = None

        try:
            self.temp_dir = tempfile.mkdtemp()
            self.temp_dest = os.path.join(self.temp_dir, self.fullname)
            shutil.copytree(src, self.temp_dest)

            self.get_linter_language(name, self.configure_linter)

        except Exception as ex:
            if self.temp_dir and os.path.exists(self.temp_dir):
                shutil.rmtree(self.temp_dir)

            sublime.error_message('An error occurred while copying the template plugin: {}'.format(str(ex)))
    def backup_package_dir(self, package_name):
        """
        Does a full backup of the Packages/{package}/ dir to Backup/

        :param package_name:
            The name of the package to back up

        :return:
            If the backup succeeded
        """

        package_dir = os.path.join(sublime.packages_path(), package_name)
        if not os.path.exists(package_dir):
            return True

        try:
            backup_dir = os.path.join(os.path.dirname(
                sublime.packages_path()), 'Backup',
                datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
            if not os.path.exists(backup_dir):
                os.makedirs(backup_dir)
            package_backup_dir = os.path.join(backup_dir, package_name)
            if os.path.exists(package_backup_dir):
                console_write(u"FOLDER %s ALREADY EXISTS!" % package_backup_dir)
            shutil.copytree(package_dir, package_backup_dir)
            return True

        except (OSError, IOError) as e:
            show_error(u'An error occurred while trying to backup the package directory for %s.\n\n%s' % (
                package_name, unicode_from_os(e)))
            if os.path.exists(package_backup_dir):
                shutil.rmtree(package_backup_dir)
            return False
    def get_commands(self):
        """
        This is a stub for getting the existing commands and adding
        autocomplete
        """
        packages = os.listdir(sublime.packages_path())
        self.packages = sorted(packages, key=lambda s: s.lower())
        self.window_commands = []

        for package in self.packages:
            package_dir = sublime.packages_path() + '/' + package
            sys.path.append(package_dir)
            __all__ = [os.path.basename(f)[:-3] for f in glob.glob(package_dir + "/*.py")]
            for sub_package in __all__:
                module = __import__(sub_package)
                for obj in dir(module):
                    actual_obj = getattr(module, obj)
                    if isinstance(actual_obj,
                                  sublime_plugin.WindowCommand):
                        self.window_commands.append(obj)
                    if isinstance(actual_obj,
                                  sublime_plugin.TextCommand):
                        self.window_commands.append(obj)

        print self.window_commands
Example #5
0
	def run(self, edit):
		#print self.window.forders()
		_folder_ = self.view.window().folders()
		__mapping__ = {}
		__mapping__['programs'] = []
		for _path_ in _folder_:
			_random = int(random.random()*1000000)
			if sublime.platform() == 'windows':
				_caption = re.match(r".*\\([^\\]*)", _path_).group(1)
				_tempStr_ = '{ "command": "pathconfig", "caption": "' + _caption + '", "args":{"path":"' + re.sub(r'\\', r'\\\\', _path_) + '", "id":"keynes' + str(_random) + '", "name":"' + _caption + '"}},'
			else :
				_caption = re.match(r".*/([^/]*)", _path_).group(1)
				_tempStr_ = '{ "command": "pathconfig", "caption": "' + _caption + '", "args":{"path":"' + _path_ + '", "id":"keynes' + str(_random) + '", "name":"' + _caption + '"}},'
			print re.sub(r'\\', r'\\\\', _path_)
			__mapping__['programs'].append(_tempStr_)
		_MainRep_ = KeyTemplate(__mainTemplate__()).render({
			"programs":__mapping__['programs']
		})
		#配置文件为packages目录下FE-Package目录
		if sublime.platform() == 'windows':
			_packpath = sublime.packages_path() + r'\FE-Package\Main.sublime-menu'
		else:
			_packpath = sublime.packages_path() + r'/FE-Package/Main.sublime-menu'
		_packfile = open(_packpath, 'w')
		_packfile.writelines(_MainRep_)
		_packfile.close()
Example #6
0
	def run(self):
		#配置文件为packages目录下FE-Package目录
		if sublime.platform() == 'windows':
			path = sublime.packages_path() + r'\FE-Package\readme'
		else:
			path = sublime.packages_path() + r'/FE-Package/readme'
		self.window.open_file(path)
Example #7
0
def get_user_packages():
    user = set()
    for fname in listdir(sublime.packages_path()):
        path = join(sublime.packages_path(), fname)
        if isdir(path) and not(fname.startswith('.')):
            user.add(fname)
    return user
Example #8
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 #9
0
    def getSnippet(self, name=None, scope=['text.plain']):
        
        snippetFilenames = self.findFiles(sublime.packages_path())

        sublime_package_filenames = self.findFiles(sublime.packages_path() + "\\..", ".sublime-package")

        content = []
        for sp in sublime_package_filenames:
            file = zipfile.ZipFile(sp)
            content.append( [file.open(name).read() for name in file.namelist() if name.endswith(".sublime-snippet") ])

        content = [item for sublist in content for item in sublist]

        tex = self.xmlMatchTabTriggerFromString(content, str(name))
        package_snippet_contents =[
            x.find('content').text
            for x in tex
            if self.filterByScope(x, scope)
        ]

        snippet_xmls = self.xmlMatchTabTrigger(snippetFilenames, str(name))

        custom_snippet_contents = [
            x.find('content').text
            for x in snippet_xmls
            if self.filterByScope(x, scope)
        ]
        return custom_snippet_contents + package_snippet_contents
def plugin_loaded():
    global full_data_path, full_icons_path, full_themes_path
    full_data_path = os.path.join(sublime.packages_path()[:-len("Packages")], os.path.normpath(data_path))
    full_icons_path = os.path.join(full_data_path, "icons")
    full_themes_path = os.path.join(full_data_path, "themes")
    # Create folders
    if not os.path.exists(full_data_path):
        os.mkdir(full_data_path)
    if not os.path.exists(full_icons_path):
        os.mkdir(full_icons_path)
    if not os.path.exists(full_themes_path):
        os.mkdir(full_themes_path)

    # Copy binary
    binary = "ColorPicker_" + get_ext()
    chflags = stat.S_IXUSR|stat.S_IXGRP|stat.S_IRUSR|stat.S_IRUSR|stat.S_IWUSR|stat.S_IWGRP
    fpath = os.path.join(full_data_path, binary)
    if get_version() >= 3000:
        if not os.path.exists(fpath):
            data = sublime.load_binary_resource('/'.join(["Packages", "Color Highlighter", "ColorPicker", binary]))
            if len(data) != 0:
                write_bin_file(fpath, data)
                os.chmod(fpath, chflags)
    else:
        if not os.path.exists(fpath):
            shutil.copy(os.path.join(sublime.packages_path(), "Color Highlighter", "ColorPicker", binary), fpath)
            os.chmod(fpath, chflags)

    # restore themes
    restore_broken_schemes()
Example #11
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
    def write_file(self):
        if os.path.exists(sublime.packages_path()+'/Gitignore'):
            path = sublime.packages_path()+'/Gitignore/boilerplates/'
        else:
            path = sublime.packages_path()+'/Sublime-Gitignore/boilerplates/'

        final = ''

        for bp in self.chosen_array:
            bpfile = open(path+bp+'.gitignore', 'r')
            text = bpfile.read()
            bpfile.close()

            final = final + '###'+bp+'###\n \n'+text+'\n\n'

        view = sublime.active_window().new_file()
        edit = view.begin_edit()
        view.insert(edit, 0, final)
        view.set_name('.gitignore')
        view.end_edit(edit)

        self.chosen_array = []
        self.first_list = ['Actionscript', 'Android', 'Autotools', 'CakePHP', 'CFWheels', 'C', 'C++', 'Clojure', 'CMake', 'CodeIgniter', 'Compass', 'Concrete5', 'Coq', 'CSharp', 'Delphi', 'Django', 'Drupal', 'Erlang', 'ExpressionEngine', 'Finale', 'ForceDotCom', 'FuelPHP', 'gcov', 'Go', 'Grails', 'GWT', 'Haskell', 'Java', 'Jboss', 'Jekyll', 'Joomla', 'Jython', 'Kohana', 'LaTeX', 'Leiningen', 'LemonStand', 'Lilypond', 'Lithium', 'Magento', 'Maven', 'nanoc', 'Node', 'Objective-C', 'OCaml', 'Opa', 'opencart', 'OracleForms', 'Perl', 'PlayFramework', 'Python', 'Qooxdoo', 'Rails', 'R', 'RhodesRhomobile', 'Ruby', 'Scala', 'SeamGen', 'SketchUp', 'SugarCRM', 'Symfony2', 'Symfony', 'SymphonyCMS', 'Target3001', 'Tasm', 'Textpattern', 'TurboGears2', 'Unity', 'VB.Net', 'Waf', 'Wordpress', 'Yii', 'ZendFramework', 'Archives', 'CVS', 'Eclipse', 'Emacs', 'Espresso', 'FlexBuilder', 'IntelliJ', 'Linux', 'Matlab', 'Mercurial', 'ModelSim', 'MonoDevelop', 'NetBeans', 'OSX', 'Quartus2', 'Redcar', 'RubyMine', 'SASS', 'SBT', 'SublimeText', 'SVN', 'Tags', 'TextMate', 'vim', 'VisualStudio', 'Windows', 'XilinxISE']

        self.second_list = ['Done', 'Actionscript', 'Android', 'Autotools', 'CakePHP', 'CFWheels', 'C', 'C++', 'Clojure', 'CMake', 'CodeIgniter', 'Compass', 'Concrete5', 'Coq', 'CSharp', 'Delphi', 'Django', 'Drupal', 'Erlang', 'ExpressionEngine', 'Finale', 'ForceDotCom', 'FuelPHP', 'gcov', 'Go', 'Grails', 'GWT', 'Haskell', 'Java', 'Jboss', 'Jekyll', 'Joomla', 'Jython', 'Kohana', 'LaTeX', 'Leiningen', 'LemonStand', 'Lilypond', 'Lithium', 'Magento', 'Maven', 'nanoc', 'Node', 'Objective-C', 'OCaml', 'Opa', 'opencart', 'OracleForms', 'Perl', 'PlayFramework', 'Python', 'Qooxdoo', 'Rails', 'R', 'RhodesRhomobile', 'Ruby', 'Scala', 'SeamGen', 'SketchUp', 'SugarCRM', 'Symfony2', 'Symfony', 'SymphonyCMS', 'Target3001', 'Tasm', 'Textpattern', 'TurboGears2', 'Unity', 'VB.Net', 'Waf', 'Wordpress', 'Yii', 'ZendFramework', 'Archives', 'CVS', 'Eclipse', 'Emacs', 'Espresso', 'FlexBuilder', 'IntelliJ', 'Linux', 'Matlab', 'Mercurial', 'ModelSim', 'MonoDevelop', 'NetBeans', 'OSX', 'Quartus2', 'Redcar', 'RubyMine', 'SASS', 'SBT', 'SublimeText', 'SVN', 'Tags', 'TextMate', 'vim', 'VisualStudio', 'Windows', 'XilinxISE']
Example #13
0
    def run(self, edit):
        sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result=sock.connect_ex(("127.0.0.1", 7777))

        if result != 0:
            window=sublime.active_window()
            view=window.active_view()
            print("va a ejcauar")
            os.system("start /min startJetty") 

        folder=sublime.active_window().folders()[0]
        self.archivos=[]
        self.explore(folder)
        ruta=""
        for archivo in self.archivos:
            if archivo.endswith(".ear"):
                ruta=archivo
                break
            if archivo.endswith(".war"):ruta=archivo
        if not ruta:
            sublime.status_message("no hay nada pa desplegar")
            return
        filename=os.path.basename(ruta)
        os.chdir(folder)
        d={"filepath":ruta, "serverPath":os.path.join(JETTY_HOME_DEPLOYMENT, filename)}
        comando='mvn -q package -DskipTests && rm -f %(serverPath)s && timeout /T 2 && cp %(filepath)s %(serverPath)s && exit'%d
        print(comando)
        archivo=open(sublime.packages_path()+os.sep+"start.cmd", "w")
        archivo.write(comando)
        archivo.close()
        os.system("start /min "+sublime.packages_path()+os.sep+"start.cmd") 
Example #14
0
    def run(self, edit):
        sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result=sock.connect_ex(("127.0.0.1", 9000))
        adicional='echo "good"'
        if result == 0:
            window=sublime.active_window()
            view=window.active_view()
            print("va a ejcauar")
            adicional="start /min shutdown_tomcat"

        folder=sublime.active_window().folders()[0]
        self.archivos=[]
        self.explore(folder)
        ruta=""
        for archivo in self.archivos:
            if archivo.endswith(".ear"):
                ruta=archivo
                break
            if archivo.endswith(".war"):ruta=archivo
        if not ruta:
            sublime.status_message("no hay nada pa desplegar")
            return
        filename=os.path.basename(ruta)
        os.chdir(folder)
        d={"filepath":ruta, "serverPath":os.path.join(TOMCAT_HOME_DEPLOYMENT, filename), "folderpath":os.path.join(TOMCAT_HOME_DEPLOYMENT, filename.replace(".war", ""))}
        comando='mvn -q package -DskipTests && '+adicional+' && timeout /t 3 && rm -f -r %(folderpath)s && rm -f %(serverPath)s && cp %(filepath)s %(serverPath)s && startup && exit'%d
        print(comando)
        archivo=open(sublime.packages_path()+os.sep+"start.cmd", "w")
        archivo.write(comando)
        archivo.close()
        os.system("start /min "+sublime.packages_path()+os.sep+"start.cmd") 
Example #15
0
    def run(self, view):
        servidor=utils.get_preference("server")
        if not servidor:
            sublime.status_message("No se ha definido un servidor")
            return
        self.servidor=servidor
        comando=server_command[servidor]
        print("el servidor es : "+servidor)
        servidor=server_path[servidor]
        folder=sublime.active_window().folders()[0]
        self.archivos=[]
        self.explore(folder)
        ruta=""
        for archivo in self.archivos:
            if archivo.endswith(".ear"):
                ruta=archivo
                break
            if archivo.endswith(".war"):ruta=archivo
        if not ruta:
            sublime.status_message("no hay nada pa desplegar")
            return
        filename=os.path.basename(ruta)
        os.chdir(folder)
        d={"filepath":ruta, "serverpath":os.path.join(servidor, filename)}
#        comando='mvn -q package -DskipTests && rm -f "%(weblogicpath)s" && cp "%(filepath)s" "%(weblogicpath)s" && exit'%d
        comando=comando%d
        print(comando)
        archivo=open(sublime.packages_path()+os.sep+"start.cmd", "w")
        archivo.write(comando)
        archivo.close()
        os.system("start /min "+sublime.packages_path()+os.sep+"start.cmd")
        threading.Thread(target=self.run_server).start()
		def on_done(path):
			if not os.path.isdir(path):
				os.makedirs(path)

			if os.path.isdir(path):
				if os.listdir(path):
					if sublime.ok_cancel_dialog("The selected folder is not empty, would you like to continue and override your local settings?", "Continue"):
						override = True
					else:
						self.window.show_input_panel("Sync Folder", path, on_done, None, None)
						return
				else:
					override = False

				# Adjust settings
				s.set("sync", True)
				s.set("sync_folder", path)

				# Reset last-run file
				file_path = os.path.join(sublime.packages_path(), "User", "Package Control.last-run")
				if os.path.isfile(file_path):
					os.remove(file_path)

				# Reset last-run file
				file_path = os.path.join(sublime.packages_path(), "User", "Package Syncing.last-run")
				if os.path.isfile(file_path):
					os.remove(file_path)

				sublime.save_settings("Package Syncing.sublime-settings")
				sublime.status_message("sync_folder successfully set to \"%s\"" % path)
				#
				sublime.run_command("pkg_sync", {"mode": ["pull", "push"], "override": override})
			else:
				sublime.error_message("Invalid Path %s" % path)
    def run(self):
        if self.window.active_view().file_name():
            configFile = os.path.join(os.path.dirname(self.window.active_view().file_name()), 'pandoc-config.json')
        else:
            sublime.status_message("Cannot create project configuration for unsaved files.")
            return

        if os.path.exists(configFile):
            self.window.open_file(configFile)
            return

        defaultConfigFile = os.path.join(sublime.packages_path(), 'Pandown', 'default-pandoc-config.json')
        userConfigFile = os.path.join(sublime.packages_path(), 'User', 'pandoc-config.json')
        if not os.path.exists(defaultConfigFile) and not os.path.exists(userConfigFile):
            sublime.status_message("Could not find default Pandoc configuration.")
            print("[Pandown stores default configuration information in Projects/Pandown/default-pandoc-config.json.]")
            print("[If this file has been moved or deleted, please reinstall Pandown.]")
            print("[See the README for support information.]")
            return
        try:
            toCopy = defaultConfigFile if (not os.path.exists(userConfigFile)) else userConfigFile
            shutil.copy(toCopy, configFile)
        except Exception as e:
            sublime.status_message("Could not write " + configFile)
            print("[Pandown encountered an exception:]")
            print("[e: " + str(e) + "]")
        else:
            self.window.open_file(configFile)
    def remove_wsdl(self):
        """
        Removes all auto-completion entries, context menu entries,
        and WSDL settings entries.

        """
        # Remove WSDL objects and fields from completions...
        # TODO: Update this with logic to support checking for file
        completions_path_list = ['User', 'NSOA', 'Wsdl.sublime-completions']
        completions_path = os.path.join(sublime.packages_path(), os.path.join(*completions_path_list))

        if os.path.exists(completions_path):
            os.remove(completions_path)

        # Remove WSDL objects and fields context menu...
        context_path_list = ['User', 'NSOA', 'Context.sublime-menu']
        context_path = os.path.join(sublime.packages_path(), os.path.join(*context_path_list))

        if os.path.exists(context_path):
            os.remove(context_path)

        # Remove WSDL objects and fields from settings
        settings = sublime.load_settings('NSOA.sublime-settings')
        if settings.has('wsdl_json'):
            settings.erase('wsdl_json')

        if settings.has('wsdl_last_updated'):
            settings.erase('wsdl_last_updated')

        sublime.save_settings('NSOA.sublime-settings')
        sublime.status_message('NSOA: All WSDL data has been removed.')
	def beautify(self, text, indent, filters):
		stderr = ""
		stdout = ""
		php_path = self.formatter.settings.get('codeformatter_php_path', '');
		if (php_path == ""):
			php_path = "php"

		try:
			if (self.formatter.platform == "windows"):
				startupinfo = subprocess.STARTUPINFO()
				startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
				startupinfo.wShowWindow = subprocess.SW_HIDE

				beautifier_exe = sublime.packages_path()+"\CodeFormatter\codeformatter\lib\phpbeautifier\php_beautifier"
				cmd = sublime.packages_path()+"\CodeFormatter\codeformatter\lib\phpbeautifier\php_beautifier.bat"
				fullcmd = [str(cmd), str(php_path), str(beautifier_exe), indent, "-l", filters, "-f", "-", "-o", "-"]
				#print(" ".join(map(str, fullcmd)))
				p = subprocess.Popen(fullcmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, creationflags=subprocess.SW_HIDE)
			else:
				cmd = sublime.packages_path()+"/CodeFormatter/codeformatter/lib/phpbeautifier/php_beautifier"
				p = subprocess.Popen([str(cmd), indent, "-l", filters, "-f", "-", "-o", "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			stdout, stderr = p.communicate(text)
		except Exception as e:
			stderr = str(e)

		if (not stderr and not stdout):
			stderr = "Formatting error!"

		return stdout, stderr
def enumerate_virtual_package_folders():
    """
    
    Note that a package may appear more than once in this list.
    
    An abstract Package consist of a sublime-package sitting in one of the 
    `zipped_package_locations()` and also various overrides in a folder 
    on `sublime.packages_path()`
    
    """
    installed_packages       = ([

            # We make redundant info here, so later we know this
            bunch( zip_path    = False,
                   folder_path = join(sublime.packages_path(), d),
                   pkg_name    = d )
        for
            d in os.listdir(sublime.packages_path())
        if
            isdir (join(sublime.packages_path(), d))
    ])

    for location in zipped_package_locations():
        packages_pattern = location + '/*.sublime-package'
        packages = glob.glob(packages_pattern)

        for package in packages:
            package_info = bunch (
                folder_path=False,
                zip_path=package,
                pkg_name=basename(splitext(package)[0]))
            installed_packages.append(package_info)

    return installed_packages
Example #21
0
def find_syntax_files():
	global syntax_files

	new = []

	# 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 == '.tmLanguage':
					path = os.path.join(root, name)
					name = os.path.splitext(os.path.split(path)[1])[0]
					new.append((path, name))
			except:
				pass
	
	# Installed Packages
	for root, dirs, files in os.walk(sublime.packages_path()):
		break # don't know how to address tmLanguage files in zips for set_syntax_file
		try:
			ext = os.path.splitext(name)[-1]
			if ext == '.sublime-package':
				pass
		except:
			pass
	
	new.sort(key=lambda x: x[1])
	syntax_files = new
Example #22
0
 def on_done(self, index):
     if index == -1:
         return None
     elif index == 0:
         self.window.show_input_panel("Set remote IP",
                                      self.settings.get("remote_ip", "192.168.0.1"),
                                      self.set_ip,
                                      None,
                                      None)
     elif index == 1:
         REMOTE.adb_reconnect_async()
         self.window.run_command("remote_actions")
     elif index == 2:
         variables = self.window.active_view().extract_variables()
         if "folder" in variables:
             REMOTE.push_to_box(variables["folder"])
     elif index == 3:
         plugin_path = os.path.join(sublime.packages_path(), "KodiDevKit")
         REMOTE.get_log(self.open_file, plugin_path)
     elif index == 4:
         plugin_path = os.path.join(sublime.packages_path(), "KodiDevKit")
         REMOTE.get_screenshot(self.open_file, plugin_path)
     elif index == 5:
         REMOTE.clear_cache()
     elif index == 6:
         REMOTE.reboot()
Example #23
0
def get_project():
    if not sublime.active_window():
        return None
    win_id = sublime.active_window().id()
    project = None
    reg_session = os.path.join(sublime.packages_path(), "..", "Settings", "Session.sublime_session")
    auto_save = os.path.join(sublime.packages_path(), "..", "Settings", "Auto Save Session.sublime_session")
    session = auto_save if os.path.exists(auto_save) else reg_session

    if not os.path.exists(session) or win_id == None:
        return project

    try:
        with open(session, 'r') as f:
            # Tabs in strings messes things up for some reason
            j = json.JSONDecoder(strict=False).decode(f.read())
            for w in j['windows']:
                if w['window_id'] == win_id:
                    if "workspace_name" in w:
                        if sublime.platform() == "windows":
                            # Account for windows specific formatting
                            project = os.path.normpath(w["workspace_name"].lstrip("/").replace("/", ":/", 1))
                        else:
                            project = w["workspace_name"]
                        break
    except:
        pass

    # Throw out empty project names
    if project == None or re.match(".*\\.sublime-project", project) == None or not os.path.exists(project):
        project = None

    return project
    def getCSS(self):
        config_parser = settings.get('parser')
        config_css = settings.get('css')

        styles = ''
        if config_css and config_css != 'default':
            styles += u"<link href='%s' rel='stylesheet' type='text/css'>" % config_css
        else:
            css_filename = 'markdown.css'
            if config_parser and config_parser == 'github':
                css_filename = 'github.css'
            # path via package manager
            css_path = os.path.join(sublime.packages_path(), 'Markdown Preview', css_filename)
            if not os.path.isfile(css_path):
                # path via git repo
                css_path = os.path.join(sublime.packages_path(), 'sublimetext-markdown-preview', css_filename)
                if not os.path.isfile(css_path):
                    sublime.error_message('markdown.css file not found!')
                    raise Exception("markdown.css file not found!")
            styles += u"<style>%s</style>" % open(css_path, 'r').read().decode('utf-8')

        if settings.get('allow_css_overrides'):
            filename = self.view.file_name()
            filetypes = settings.get('markdown_filetypes')

            for filetype in filetypes:
                if filename.endswith(filetype):
                    css_filename = filename.rpartition(filetype)[0] + '.css'
                if (os.path.isfile(css_filename)):
                    styles += u"<style>%s</style>" % open(css_filename, 'r').read().decode('utf-8')

        return styles
Example #25
0
def write_menu():
    menu_path = os.path.join(sublime.packages_path(), 'User', 'Context.sublime-menu')
    print(menu_path)
    print(sublime.packages_path())
    menu_content = get_menu_items()
    with open(menu_path, 'w', encoding='utf8', newline='') as f:
        f.write(str(menu_content))
Example #26
0
	def run(self):
		#配置文件为packages目录下FE-Package目录
		if sublime.platform() == 'windows':
			path = sublime.packages_path() + r'\FE-Package\\'
		else:
			path = sublime.packages_path() + r'/FE-Package/'
		self.window.open_file(checkDir(''.join([L for L in open(path + 'make.path')])) + 'configure.conf')
    def run(self):
      global LivereloadFactory

      # autocreate config.rb for compass
      if not os.path.exists(os.path.join(self.dirname, "config.rb")):
        print "Generating config.rb"
        shutil.copy(os.path.join(sublime.packages_path(), "LiveReload","assets","config.rb"), self.dirname)

      # autocreate config.min.rb for compass
      if not os.path.exists(os.path.join(self.dirname, "config.min.rb")):
        print "Generating config.min.rb"
        shutil.copy(os.path.join(sublime.packages_path(), "LiveReload","assets","config.min.rb"), self.dirname)

      # compass compile min
      print self.compilemin
      shutil.copy(self.source,self.sourcemin)
      p = subprocess.Popen([self.compilemin],shell=True,  stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
      if p.stdout.read() :
        os.remove(self.sourcemin)
      
      # compass compile 
      print self.compile
      p = subprocess.Popen([self.compile],shell=True,  stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
      if p.stdout.read() :
        self.LivereloadFactory.send_all(json.dumps(["refresh", {
              "path": self.filename.replace('\\','/'),
              "apply_js_live": True,
              "apply_css_live": True,
              "apply_images_live": True
        }]))
Example #28
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
 def _fn(*args, **kwargs):
     try:
         return fn(*args, **kwargs)
     except MissingCredentialsException:
         sublime.error_message("Gist: GitHub username or password isn't provided in Gist.sublime-settings file")
         user_settings_path = os.path.join(sublime.packages_path(), 'User', 'Gist.sublime-settings')
         if not os.path.exists(user_settings_path):
             default_settings_path = os.path.join(sublime.packages_path(), 'Gist', 'Gist.sublime-settings')
             shutil.copy(default_settings_path, user_settings_path)
         sublime.active_window().open_file(user_settings_path)
     except subprocess.CalledProcessError as err:
         sublime.error_message("Gist: Error while contacting GitHub: cURL returned %d" % err.returncode)
     except EnvironmentError as err:
         traceback.print_exc()
         if type(err) == OSError and err.errno == 2 and api_request == api_request_curl:
             sublime.error_message("Gist: Unable to find Python SSL module or cURL")
         else:
             msg = "Gist: Error while contacting GitHub"
             if err.strerror:
                 msg += err.strerror
             sublime.error_message(msg)
     except SimpleHTTPError as err:
         msg = "Gist: GitHub returned error %d" % err.code
         try:
             response_json = json.loads(err.response)
             response_msg = response_json.get('message')
             if response_msg:
                 msg += ": " + response_msg
         except ValueError:
             pass
         sublime.error_message(msg)
     except:
         traceback.print_exc()
         sublime.error_message("Gist: unknown error (please, report a bug!)")
Example #30
0
	def parseJSON(self, package, name, ext):
		if ST2:
			path = os.path.join(sublime.packages_path(), package, name + '.' + ext)
			if not os.path.isfile(path):
				path = os.path.join(sublime.packages_path(), package, 'Default.' + ext)
				if not os.path.isfile(path):
					return None
				return None
			with codecs.open(path) as f:
				content = self.removeComments(f.read())
			if f is not None:
				f.close()
			try:
				parsedJSON = json.loads(content, cls=ConcatJSONDecoder)
			except (ValueError):
				return None
			return parsedJSON[0]
		else:
			try:
				resource = sublime.load_resource('Packages/' + package + '/' + name + '.' + ext)
			except (IOError):
				try:
					resource = sublime.load_resource('Packages/' + package + '/Default.' + ext)
				except (IOError):
					return None
				return None
			return sublime.decode_value(resource)
Example #31
0
    def __refresh_settings(self, first_load=False):
        if not first_load:
            print('[FileHistory] Reloading the settings file "%s".' %
                  (self.SETTINGS_FILE))

        self.PRINT_DEBUG = self.__ensure_setting('debug', False)

        self.GLOBAL_MAX_ENTRIES = self.__ensure_setting(
            'global_max_entries', 100)
        self.PROJECT_MAX_ENTRIES = self.__ensure_setting(
            'project_max_entries', 50)
        self.USE_SAVED_POSITION = self.__ensure_setting(
            'use_saved_position', True)
        self.NEW_TAB_POSITION = self.__ensure_setting('new_tab_position',
                                                      'next')
        self.REOPEN_IN_CURRENT_GROUP = self.__ensure_setting(
            'reopen_file_in_current_group', False)

        self.REMOVE_NON_EXISTENT_FILES = self.__ensure_setting(
            'remove_non_existent_files_on_preview', True)
        self.CLEANUP_ON_STARTUP = self.__ensure_setting(
            'cleanup_on_startup', True)
        self.DELETE_ALL_ON_STARTUP = self.__ensure_setting(
            'delete_all_on_startup', False)
        history_path = self.__ensure_setting(
            'history_file', os.path.join('User', 'FileHistory.json'))

        self.HISTORY_FILE = os.path.normpath(
            os.path.join(sublime.packages_path(), history_path))

        self.USE_MONOSPACE = self.__ensure_setting('monospace_font', False)

        self.TIMESTAMP_SHOW = self.__ensure_setting('timestamp_show', True)
        self.TIMESTAMP_FORMAT = self.__ensure_setting(
            'timestamp_format', self.DEFAULT_TIMESTAMP_FORMAT)
        self.TIMESTAMP_MODE = self.__ensure_setting('timestamp_mode',
                                                    'history_access')
        self.TIMESTAMP_RELATIVE = self.__ensure_setting(
            'timestamp_relative', True)

        self.PRETTIFY_HISTORY = self.__ensure_setting('prettify_history',
                                                      False)

        self.PATH_EXCLUDE_PATTERNS = self.__ensure_setting(
            'path_exclude_patterns', [])
        self.PATH_REINCLUDE_PATTERNS = self.__ensure_setting(
            'path_reinclude_patterns', [])

        self.MAX_BACKUP_COUNT = self.__ensure_setting('max_backup_count', 3)

        # Test if the specified format string is valid
        try:
            time.strftime(self.TIMESTAMP_FORMAT)
        except ValueError:
            print(
                '[FileHistory] Invalid timstamp_format string. Falling back to default.'
            )
            self.TIMESTAMP_FORMAT = self.DEFAULT_TIMESTAMP_FORMAT

        # Ignore the file preview setting for ST2
        self.SHOW_FILE_PREVIEW = False if is_ST2 else self.__ensure_setting(
            'show_file_preview', True)
Example #32
0
    def generate_colour_scheme(self, view, generate=True):
        # make sure we have hex AND we're >= ST3 (load_resource doesn't work in ST2)
        colour_removed = sbs_settings().get('remove_colour', 'invalid.illegal')
        colour_added = sbs_settings().get('add_colour', 'string')
        colour_modified_deletion = sbs_settings().get(
            'modified_colour_deletion', 'support.class')
        colour_modified_addition = sbs_settings().get(
            'modified_colour_addition', 'support.class')
        colour_text = sbs_settings().get('text_colour', '')

        notHex = False
        for col in [
                colour_removed, colour_added, colour_modified_deletion,
                colour_modified_addition
        ]:
            if not '#' in col:
                notHex = True

        if int(sublime.version()) < 3000 or notHex:
            return {
                'removed': colour_removed,
                'added': colour_added,
                'modified_deletion': colour_modified_deletion,
                'modified_addition': colour_modified_addition
            }

        # generate theme strings
        colourStrings = {}
        colourHexes = {}
        for col in [['removed', colour_removed], ['added', colour_added],
                    ['modified_deletion', colour_modified_deletion],
                    ['modified_addition', colour_modified_addition]]:
            colourStrings[col[0]] = 'comparison.' + col[0]
            colourHexes[col[0]] = col[1]

        # generate modified theme
        if generate:
            # load current scheme
            current_scheme = view.settings().get('color_scheme')  # no 'u' >:(
            try:
                scheme = sublime.load_resource(current_scheme)
            except:
                # sometimes load_resource can fail (seemingly on OSX when upgrading from ST2->ST3)
                # manually re-selecting the colour scheme once should fix this for good (see issue #31)
                sublime.message_dialog(
                    'Could not load colour scheme.\nFalling back to a blank colour scheme.\n\nTo fix this, please manually re-select your colour scheme in\n\tPreferences > Color Scheme\n\nThis should not happen again once action has been taken.\nSorry for the inconvenience.'
                )
                scheme = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>settings</key><array></array></dict></plist>'

            # determine if scheme is using the new .sublime-color-scheme json format
            scheme_json = False
            try:
                scheme = json.loads(scheme)
                scheme_json = True
            except:
                scheme_json = False

            # create format specific data
            if scheme_json:
                for name in colourStrings:
                    string = colourStrings[name]
                    chex = colourHexes[name]
                    scheme['rules'].append({
                        "name": name,
                        "scope": string,
                        "background": chex,
                        "foreground": colour_text
                    })

                data = json.dumps(scheme)
            else:
                xml = ''
                xml_tmpl = '<dict><key>name</key><string>{}</string><key>scope</key><string>{}</string><key>settings</key><dict><key>background</key><string>{}</string><key>foreground</key><string>{}</string></dict></dict>'
                dropzone = scheme.rfind('</array>')

                # loop through colours and generate their xml
                for name in colourStrings:
                    string = colourStrings[name]
                    chex = colourHexes[name]
                    xml += xml_tmpl.format('Comparison ' + name, string, chex,
                                           colour_text)

                # combiiiiiiiiiiiiine
                data = scheme[:dropzone] + xml + scheme[dropzone:]

            # determine theme filename
            # relative for settings, absolute for writing to file
            # replacing slashes for relative path necessary on windows
            # completely separate filenames are necessary to avoid json erroneously taking precedence
            theme_name = 'SBSCompareTheme.tmTheme'
            if scheme_json:
                theme_name = 'SBSCompareScheme.sublime-color-scheme'

            abs_theme_file = os.path.join(sublime.packages_path(), 'User',
                                          theme_name)
            rel_theme_file = os.path.join(
                os.path.basename(sublime.packages_path()), 'User', theme_name)
            rel_theme_file = rel_theme_file.replace('\\', '/')

            # save new theme
            with open(abs_theme_file, 'w', encoding='utf-8') as f:
                f.write(data)

            # save filename for later use (if we rerun this without regenerating)
            self.last_theme_file = rel_theme_file

        # set view settings to use new theme
        view.settings().set('color_scheme', self.last_theme_file)
        return colourStrings
Example #33
0
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3

"""This module exports the Gfortran plugin class."""

# Since SublimeLinter is loaded after SublimeFortran, we need to manually import Linter
import sublime, os, sys
try:
    sys.path.append(os.path.join(sublime.packages_path(), 'SublimeLinter'))
    from SublimeLinter.lint import Linter, util
    sys.path.remove(os.path.join(sublime.packages_path(), 'SublimeLinter'))
except (ImportError):
    print("SublimeFortran: Failed to load SublimeLinter")
    class Linter(object):
        pass


class GfortranFixedForm(Linter):
    """Provides an interface to gfortran."""
    syntax = 'fortranfixedform'
    cmd = 'gfortran -cpp -fsyntax-only -Wall'
    executable = None
    version_args = '--version'
    version_re = r'(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 4.0'
    multiline = True
    regex = (
        # filename:line:col: is common for multiline and single line warnings
        r'^[^:]*:(?P<line>\d+)[:.](?P<col>\d+):'
        # Then we either have a space or (a newline, a newline, some source code, a newline, a col number, a newline)
        r'(?:\s|$\r?\n^$\r?\n^.*$\r?\n^\s*\d$\r?\n)'