Beispiel #1
0
def show_select_projects(self):
	#
	# Load projects list and show select popup
	#
	#Settings load:
	settings = sublime.load_settings('ProjectsList.sublime-settings')

	self.subl_path = get_sublime_path()

	if not self.subl_path:
		sublime.error_message("No Sublime path specified for current OS!")
		raise Exception("No Sublime path specified for current OS!")

	if settings.get('projects_'+sublime.platform()):
		self.projects = settings.get('projects_'+sublime.platform())
	else:
		sublime.error_message("No projects definde, goto Manage Projects!")
		raise Exception("No projects definde, goto Manage Projects!")

	names = []

	for i in self.projects:
		names.append("%s" % (i["name"]))

	self.window.show_quick_panel(names, self.selected, sublime.MONOSPACE_FONT)
Beispiel #2
0
 def run(self):
     if sublime.platform() == 'linux':
         term = self.view.settings().get('VintageousEx_linux_terminal')
         term = term or os.environ.get('COLORTERM') or os.environ.get("TERM")
         if not term:
             sublime.status_message("Vintageous: Not terminal name found.")
             return
         try:
             self.open_shell([term, '-e', 'bash']).wait()
         except Exception as e:
             print(e)
             sublime.status_message("Vintageous: Error while executing command through shell.")
             return
     elif sublime.platform() == 'osx':
         term = self.view.settings().get('VintageousEx_osx_terminal')
         term = term or os.environ.get('COLORTERM') or os.environ.get("TERM")
         if not term:
             sublime.status_message("Vintageous: Not terminal name found.")
             return
         try:
             self.open_shell([term, '-e', 'bash']).wait()
         except Exception as e:
             print(e)
             sublime.status_message("Vintageous: Error while executing command through shell.")
             return
     elif sublime.platform() == 'windows':
         self.open_shell(['cmd.exe', '/k']).wait()
     else:
         # XXX OSX (make check explicit)
         ex_error.handle_not_implemented()
        def open_workspace_window2(cb):
            if sublime.platform() == 'linux':
                subl = open('/proc/self/cmdline').read().split(chr(0))[0]
            elif sublime.platform() == 'osx':
                # TODO: totally explodes if you install ST2 somewhere else
                settings = sublime.load_settings('Floobits.sublime-settings')
                subl = settings.get('sublime_executable', '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl')
                if not os.path.exists(subl):
                    return sublime.error_message('Can\'t find your Sublime Text executable at %s. Please add "sublime_executable /path/to/subl" to your ~/.floorc and restart Sublime Text' % subl)
            elif sublime.platform() == 'windows':
                subl = sys.executable
            else:
                raise Exception('WHAT PLATFORM ARE WE ON?!?!?')

            command = [subl]
            if get_workspace_window() is None:
                command.append('--new-window')
            command.append('--add')
            command.append(G.PROJECT_PATH)

            # Maybe no msg view yet :(
            print('command:', command)
            p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            poll_result = p.poll()
            print('poll:', poll_result)

            set_workspace_window(lambda: create_chat_view(cb))
Beispiel #4
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()
Beispiel #5
0
    def run(self, edit, paste = True):

        color = self.get_selected(edit)     # in 'RRGGBB' format or None

        binpath = os.path.join(sublime.packages_path(), usrbin, binname)
        if sublime.platform() == 'windows':
            color = self.pick_win(binpath, color)

        else:
            args = [binpath]
            if color:
                if sublime.platform() == 'osx':
                    args.append('-startColor')
                    args.append(color)
                else:
                    args.append('#' + color)

            proc = subprocess.Popen(args, stdout=subprocess.PIPE)
            color = proc.communicate()[0].strip()


        if color:
            if sublime.platform() != 'windows' or sublime_version == 2:
                color = color.decode('utf-8')

            color = '#' + color
            if paste:
                self.put_selected(edit, color)
def find_names():
    if sublime.platform() == "windows":
        return ["Default.sublime-keymap", "Default (Windows).sublime-keymap"]
    elif sublime.platform() == "osx":
        return ["Default.sublime-keymap", "Default (OSX).sublime-keymap"]
    else:
        return ["Default.sublime-keymap", "Default (Linux).sublime-keymap"]
Beispiel #7
0
    def showRelativeNumbers(self):
        view = self.view
        self.old_line_numbers =view.settings().get('line_numbers')
        view.settings().set('line_numbers', False)

        cur_line = view.rowcol(view.sel()[0].begin())[0]
        start_line = max(cur_line-self.icon_count, 0)
        end_line = min(cur_line+self.icon_count, self.view.rowcol(self.view.size())[0])

        lines = self.view.lines(sublime.Region(self.view.text_point(start_line, 0), self.view.text_point(end_line + 1, 0)))

        # Append the last line's region manually (if necessary)
        if len(lines) < end_line - start_line + 1:
            last_text_point = lines[-1].end() + 1
            lines.append(sublime.Region(last_text_point, last_text_point))

        for i in range(start_line, start_line + len(lines)):
            name = 'linenum' + str(i-start_line)
            if cur_line == i:
                num = cur_line+1
            else:
                num = int(math.fabs(cur_line - i))

            if int(sublime.version()) >= 3000:
                if num > 99:
                    icon_path = "Packages/VintageLines/icons/3/%s.png" % num
                else:
                    icon_path = "Packages/VintageLines/icons/%s/%s.png" % (sublime.platform(), num)
            else:
                if num > 99:
                    icon_path = "../VintageLines/icons/3/%s" % num
                else:
                    icon_path = "../VintageLines/icons/%s/%s" % (sublime.platform(), num)

            view.add_regions(name, [lines[i-start_line]], 'linenums', icon_path, sublime.HIDDEN)
Beispiel #8
0
def get_sublime_path():
    if sublime.platform() == 'osx':
        return '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl'
    elif sublime.platform() == 'linux':
        return open('/proc/self/cmdline').read().split(chr(0))[0]
    else:
        return sys.executable
Beispiel #9
0
def plugin_loaded():
    if sublime.platform() == "windows":
            settings_file = "CustomPATH (Windows).sublime-settings"

    elif sublime.platform() == "osx":
        settings_file = "CustomPATH (OSX).sublime-settings"

    else:
        settings_file = "CustomPATH (Linux).sublime-settings"

    settings = sublime.load_settings(settings_file)

    append_to_path = settings.get("append_to_path")

    if append_to_path is None:
        print("CustomPATH: no platform specific PATH settings found! Check readme!")
        return

    if settings.get("enabled", True):
        if settings.get("override", False):
            os.environ["PATH"] = os.pathsep.join(append_to_path)

        else:
            for path in append_to_path:
                if path not in os.environ["PATH"]:
                    new_path = "{}{}".format(path, os.pathsep) + os.environ["PATH"]
                    os.environ["PATH"] = new_path

        print("CustomPATH: new PATH:", os.environ["PATH"])
        def open_room_window(cb):
            if sublime.platform() == 'linux':
                subl = open('/proc/self/cmdline').read().split(chr(0))[0]
            elif sublime.platform() == 'osx':
                # TODO: totally explodes if you install ST2 somewhere else
                subl = settings.get('sublime_executable', '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl')
            elif sublime.platform() == 'windows':
                subl = sys.executable
            else:
                raise Exception('WHAT PLATFORM ARE WE ON?!?!?')

            command = [subl]
            if utils.get_room_window() is None:
                command.append('--new-window')
            command.append('--add')
            command.append(G.PROJECT_PATH)
            print('command:', command)
            p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            poll_result = p.poll()
            print('poll:', poll_result)

            def create_chat_view():
                with open(os.path.join(G.COLAB_DIR, 'msgs.floobits.log'), 'w') as msgs_fd:
                    msgs_fd.write('')
                msg.get_or_create_chat(cb)
            utils.set_room_window(create_chat_view)
Beispiel #11
0
def create_environment():
    """Return a dict with os.environ augmented with a better PATH.

    Platforms paths are added to PATH by getting the "paths" user settings
    for the current platform.
    """
    from . import persist

    env = {}
    env.update(os.environ)

    paths = persist.settings.get('paths', {})

    if sublime.platform() in paths:
        paths = [os.path.abspath(os.path.expanduser(path))
                 for path in convert_type(paths[sublime.platform()], [])]
    else:
        paths = []

    if paths:
        env['PATH'] = os.pathsep.join(paths) + os.pathsep + env['PATH']

    if logger.isEnabledFor(logging.INFO) and env['PATH']:
        debug_print_env(env['PATH'])

    return env
Beispiel #12
0
def get_viewer():
	default_viewer = DEFAULT_VIEWERS.get(sublime.platform(), None)
	viewer_name = get_setting('viewer', default_viewer)
	if viewer_name in ['', 'default']:
		viewer_name = default_viewer

	if viewer_name is None:
		sublime.error_message('No viewer could be found for your platform. '
				'Please configure the "viewer" setting in your LaTeXTools '
				'Preferences')
		raise NoViewerException()

	try:
		viewer = get_plugin(viewer_name + '_viewer')
	except NoSuchPluginException:
		sublime.error_message('Cannot find viewer ' + viewer_name + '.\n' +
								'Please check your LaTeXTools Preferences.')
		raise NoViewerException()

	print(repr(viewer))
	
	# assume no-args constructor
	viewer = viewer()

	if not viewer.supports_platform(sublime.platform()):
		sublime.error_message(viewer_name + ' does not support the ' +
								'current platform. Please change the viewer in ' +
								'your LaTeXTools Preferences.')
		raise NoViewerException()

	return viewer
Beispiel #13
0
    def run_single_output(self):
        p = self.view.window().folders()[0]

        if sublime.platform() == 'windows':
            p += "\\build\\{}.exe".format(os.path.basename(p))
        else:
            p += "/build/{}.out".format(os.path.basename(p))

        self.sharex = self.get_bat_ex()
        command = self.get_shell_command()

        command.append(self.sharex)
        command.append(p)
        process = 0

        try:
            if sublime.platform() == 'window':

                process = subprocess.Popen(
                                        command,
                                        shell=False,
                                        universal_newlines=True,
                                        creationflags=CREATE_NEW_CONSOLE
                                        )
            else:
                # go to the build directory and run the command
                curdir = os.curdir
                os.chdir(os.path.dirname(p))
                process = subprocess.Popen(command)
                os.chdir(curdir)

        except CalledProcessError as e:
            print(e.output)
            process.terminate()
    def handle_flagged_output(self, output):
        _, action, arg = output.split(self.stdout_flag)
        arg = arg.rstrip()

        def open_file(file, create_if_not_found):
            if not os.path.isfile(file):
                if create_if_not_found:
                    open(file, 'a').close()
                else:
                    return

            if len(sublime.windows()) == 0:
                sublime.run_command('new_window')

            window = sublime.active_window()
            window.open_file(file)

        if action == 'open_file':
            open_file(arg, False)
        elif action == 'open_startup_file':
            open_file(arg, True)
        elif action == 'open_dir':
            if sublime.platform() == 'osx':
                subprocess.Popen(['open', arg])
            elif sublime.platform() == 'linux':
                subprocess.Popen(['xdg-open', arg])
            elif sublime.platform() == 'windows':
                os.startfile(arg)
    def is_compatible(self, metadata):
        """
        Detects if a package is compatible with the current Sublime Text install

        :param metadata:
            A dict from a metadata file

        :return:
            If the package is compatible
        """

        sublime_text = metadata.get("sublime_text")
        platforms = metadata.get("platforms", [])

        # This indicates the metadata is old, so we assume a match
        if not sublime_text and not platforms:
            return True

        if not is_compatible_version(sublime_text):
            return False

        if not isinstance(platforms, list):
            platforms = [platforms]

        platform_selectors = [sublime.platform() + "-" + sublime.arch(), sublime.platform(), "*"]

        for selector in platform_selectors:
            if selector in platforms:
                return True

        return False
Beispiel #16
0
def popen(cmd, **args):
    log.debug("%s" % cmd)

    # Set environment path
    path_bak = set_envionpath()

    try:
        if sublime.platform() == "windows":
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, env=os.environ, **args)
        elif sublime.platform() == "osx" or sublime.platform() == "linux":
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ, **args)

    except Exception as e:
        log.error(e)
        log.error(os.environ["PATH"])

        # Reset environment path
        reset_envionpath(path_bak)

    # Reset environment path
    reset_envionpath(path_bak)

    return proc
Beispiel #17
0
def find_viewer(name):
    log.debug("%s" % name)

    # Load settings
    settings = tools.load_settings("LaTeXing", pdf_viewer_osx={}, pdf_viewer_windows={}, pdf_viewer_linux={})

    if sublime.platform() == "windows":
        # Check if key available
        if name in settings["pdf_viewer_windows"]:
            # Search all available locations
            for item in settings["pdf_viewer_windows"][name]:
                executable = command_executable([item], command_line_tool=False)
                if executable:
                    return executable

    elif sublime.platform() == "osx":
        # Check if key available
        if name in settings["pdf_viewer_osx"]:
            # Search all available locations
            for item in settings["pdf_viewer_osx"][name]:
                if os.path.exists(item):
                    return item

    elif sublime.platform() == "linux":
        # Check if key available
        if name in settings["pdf_viewer_linux"]:
            # Search all available locations
            for item in settings["pdf_viewer_linux"][name]:
                executable = command_executable([item], command_line_tool=False)
                if executable:
                    return executable

    return None
 def get_predefined_param(self, match):
     '''{%%}'''
     key = match.group(1)
     if key == 'filename':
         return os.path.basename(self.view.file_name() or '')
     elif key == 'filepath':
         return self.view.file_name() or ''
     elif key == 'dirname':
         return os.path.dirname(self.view.file_name() or '')
     elif key == 'platform':
         return sublime.platform()
     elif key == 'arch':
         return sublime.arch()
     elif key == 'encoding':
         encoding = self.view.encoding()
         return encoding if 'Undefined' != encoding else self.settings.get('default_encoding')
     elif key == 'ip':
         return get_local_ip()
     elif key == 'user':
         user = os.getlogin() if 'windows' != sublime.platform() else ''
         if user:
             return user
             #windows?
         user = os.popen('whoami').read()
         p = re.compile('[\r\n]', re.M)
         return re.sub(p, '', user)
     elif key == 'ext':
         return get_ext(self.view.file_name())
     elif key == 'year':
         t = datetime.datetime.today()
         return t.strftime('%Y')
     elif key == 'datetime':
         t = datetime.datetime.today()
         return t.strftime(self.get_action_param('datetime_format', '%Y-%m-%d %H:%M:%S'))
     return match.group(1)
Beispiel #19
0
 def run(self, dirs):        
     settings = helper.loadSettings("QuickXDev")
     quick_cocos2dx_root = settings.get("quick_cocos2dx_root", "")
     if len(quick_cocos2dx_root)==0:
         sublime.error_message("quick_cocos2dx_root no set")
         return
     cmdPath=""
     if sublime.platform()=="osx":
         cmdPath=quick_cocos2dx_root+"/bin/compile_scripts.sh"
     elif sublime.platform()=="windows":
         cmdPath=quick_cocos2dx_root+"/bin/compile_scripts.bat"
         if not os.path.exists(cmdPath):
             helper.writeFile(cmdPath,compile_scripts_bat)
     if cmdPath=="" or not os.path.exists(cmdPath):
         sublime.error_message("compile_scripts no exists")
         return
     self.cmdPath=cmdPath
     self.compile_scripts_key=settings.get("compile_scripts_key", "")
     self.window.run_command("hide_panel")
     output="res/game.zip"
     on_done = functools.partial(self.on_done, dirs[0])
     v = self.window.show_input_panel(
         "Output File:", output, on_done, None, None)
     v.sel().clear()
     v.sel().add(sublime.Region(4, 8))
Beispiel #20
0
	def open(self, use_powershell = True):
		if self.isDirectory():
			import subprocess
			if sublime.platform() == 'osx':
				subprocess.Popen(['/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal', '.'], cwd=self.forCwdSystemPath())
			elif sublime.platform() == 'windows':
				if use_powershell:
					try:
						subprocess.Popen(['start', 'powershell'], cwd=self.forCwdSystemPath(), shell=True)
					except:
						subprocess.Popen(['start', 'cmd', '.'], cwd=self.forCwdSystemPath(), shell=True)
				else:
					subprocess.Popen(['start', 'cmd', '.'], cwd=self.forCwdSystemPath(), shell=True)
			elif sublime.platform() == 'linux':
				subprocess.Popen(['gnome-terminal', '.'], cwd=self.forCwdSystemPath())
		else:
			if sublime.platform() == 'osx':
				import subprocess
				subprocess.Popen(['open', self.name()], cwd=self.dirname())
			elif sublime.platform() == 'windows':
				import subprocess
				subprocess.Popen(['start',  '', self.path()], cwd=self.dirname(), shell=True)
			else:
				from . import desktop
				desktop.open(self.path())
				print('using desktop')
def open_file(filepath):
    if sublime.platform() == "osx":
        subprocess.call(('open', filepath))
    elif sublime.platform() == "windows":
        os.startfile(filepath)
    elif sublime.platform() == "linux":
        subprocess.call(('xdg-open', filepath))
    def on_css_selector_entered(self, selector):

    # Create an output buffer

        self.output_view = self.window.new_file()
        self.output_view.set_name(selector + ' - Element Finder Results'
                                  )
        self.output_view.set_scratch(True)
        self.output_view.set_syntax_file('Packages/Element Finder/Element Finder Results.tmLanguage')
        self.output_view.settings().set('result_file_regex', "^([^ ].*) \([0-9]+ match(?:es)?\)$")
        self.output_view.settings().set('result_line_regex', '^ +([0-9]+): ')

    # Create a thread so that calling the command line app doesn't lock up the interface

        sublime_settings = \
            sublime.load_settings('Element Finder.sublime-settings')
        settings = {'node_path': sublime_settings.get('node_path'),
                    'extension': sublime_settings.get('extension'),
                    'ignore': sublime_settings.get('ignore')}

    # Let the user declare different Node paths for each OS, in case they sync the plugin across multiple computers

        if sublime.platform() == 'osx'and sublime_settings.get('node_path_osx') is not None:
            settings['node_path'] = sublime_settings.get('node_path_osx')
        elif sublime.platform() == 'windows'and sublime_settings.get('node_path_windows') is not None:
            settings['node_path'] = sublime_settings.get('node_path_windows')
        elif sublime.platform() == 'linux'and sublime_settings.get('node_path_linux') is not None:
            settings['node_path'] = sublime_settings.get('node_path_linux')

        self.thread = CommandLineInterface(self.dirs, selector, settings)
        self.thread.start()
        self.handle_threading()
Beispiel #23
0
    def path_to_dartium(self):
        '''Returns the path to the `chrome` binary of the 'Dartium' Chrome
        build.

        May throw a ConfigError that the caller must prepare for.
        '''
        # Dartium will not always be available on the user's machine.
        bin_name = 'chrome.exe'
        if sublime.platform() == 'osx':
            bin_name = 'Contents/MacOS/Chromium'
        elif sublime.platform() == 'linux':
            bin_name = 'chrome'

        try:
            path = self.setts.get('dart_dartium_path')
        except (KeyError, TypeError) as e:
            raise ConfigError('could not find path to Dartium')

        try:
            full_path = os.path.join(path, bin_name)
            full_path = os.path.expandvars(os.path.expanduser(full_path))
            if not os.path.exists(full_path):
                raise ConfigError()
            return full_path
        except Exception as e:
            _logger.error(e)
            raise ConfigError('could not find Dartium')
	def get_base_dir(only_base):
		platform = sublime.platform().title()
		if (platform == "Osx"):
			platform = "OSX"
		settings = sublime.load_settings('AutoBackups ('+platform+').sublime-settings')
		# Configured setting
		backup_dir =  settings.get('backup_dir')
		now_date = str(datetime.datetime.now())
		date = now_date[:10]

		backup_per_day =  settings.get('backup_per_day')
		if (backup_per_day and not only_base):
			backup_dir = backup_dir +'/'+ date

		time = now_date[11:19].replace(':', '')
		backup_per_time =  settings.get('backup_per_time')
		if (backup_per_day and backup_per_time == 'folder' and not only_base):
			backup_dir = backup_dir +'/'+ time

		if backup_dir != '':
			return os.path.expanduser(backup_dir)

		# Windows: <user folder>/My Documents/Sublime Text Backups
		if (sublime.platform() == 'windows'):
			backup_dir = 'D:/Sublime Text Backups'
			if (backup_per_day and not only_base):
				backup_dir = backup_dir +'/'+ date
			return backup_dir

		# Linux/OSX/other: ~/sublime_backups
		backup_dir = '~/.sublime/backups'
		if (backup_per_day and not only_base):
			backup_dir = backup_dir +'/'+ date
		return os.path.expanduser(backup_dir)
Beispiel #25
0
    def run(self):
        if int(self.getLatestVersion()) == int(sublime.version()):
            print ("currently on latest version")
        else:
            print ("new version available")
            if sublime.platform() == "windows":
                #download the latest installer
                s = sublime.load_settings("Preferences.sublime-settings") #get the install path from preferences
                install_path = s.get("install_path", "")

                f = urllib2.urlopen("http://www.sublimetext.com/2")
                format = formatter.NullFormatter()
                parser = LinksParser(format)
                html = f.read() 
                parser.feed(html) #get the list of latest installer urls
                parser.close()
                urls = parser.get_links()
                if sublime.arch() == "x32":
                    download_link = urls[1]

                elif sublime.arch() == "x64":
                    download_link = urls[3]

                download_link = quote(download_link, safe="%/:=&?~#+!$,;'@()*[]")
                sublime.status_message('SublimeUpdater is downloading update')
                thr = BackgroundDownloader(download_link, install_path, download_link) #start the download thread
                threads = []
                threads.append(thr)
                thr.start()

            elif sublime.platform() == "linux":
                print "linux detected"
        
            elif sublime.platform() == "osx":
                print "mac detected"
Beispiel #26
0
    def run(self, user=False):
        # Add sublime-build file
        items = [["LaTeXing/LaTeX.sublime-build", "User/LaTeX.sublime-build"]]
        items += [["LaTeXing/LaTeX (TikZ).sublime-build", "User/LaTeX (TikZ).sublime-build"]]

        # Add sublime-keymap files
        items += [["LaTeXing/Default.sublime-keymap", "User/Default.sublime-keymap"]]
        if sublime.platform() == "windows":
            items += [["LaTeXing/Default (Windows).sublime-keymap", "User/Default (Windows).sublime-keymap"]]
        elif sublime.platform() == "osx":
            items += [["LaTeXing/Default (OSX).sublime-keymap", "User/Default (OSX).sublime-keymap"]]
        elif sublime.platform() == "linux":
            items += [["LaTeXing/Default (Linux).sublime-keymap", "User/Default (Linux).sublime-keymap"]]

        # Add map files for bibsonomy, citeulike, mendeley, zotero
        items += [["LaTeXing/latexing/api/bibsonomy.map", "User/LaTeXing/bibsonomy.map"]]
        items += [["LaTeXing/latexing/api/citeulike.map", "User/LaTeXing/citeulike.map"]]
        items += [["LaTeXing/latexing/api/mendeley.map", "User/LaTeXing/mendeley.map"]]
        items += [["LaTeXing/latexing/api/zotero.map", "User/LaTeXing/zotero.map"]]

        message = ["Open %s" % item[1 if user else 0] for item in items]

        def on_done(i):
            if i >= 0:
                self.window.run_command("open_file", {"file": "${packages}/%s" % items[i][1 if user else 0]})

        if sublime.ok_cancel_dialog("You are trying to access the extended settings, be sure that you know what you are doing. In case of a problem please reset the files and try it again before reporting any problem."):
            self.window.show_quick_panel(message, on_done)
Beispiel #27
0
def set_keymap():
	path = os.path.join(sublime.packages_path(), 'User', 'Default (' + PLATFORMS[sublime.platform()] + ').sublime-keymap')

	con = ''
	if os.path.isfile(path):
		with open(path, 'r', encoding = 'utf-8') as fh:
			con = str(fh.read())
			if con.find('gohelper_godef') != -1:
				return

	if sublime.platform() == 'osx':
		keymap = '{ "keys": ["super+.", "super+g"], "command": "gohelper_godef" }'
	else:
		keymap = '{ "keys": ["ctrl+.", "ctrl+g"], "command": "gohelper_godef" }'

	start = con.find('[')
	if start == -1:
		keymap = '[\n    ' + keymap + '\n]'
		con = keymap
	else:
		keymap = '\n    ' + keymap + ','
		con = con[:start+1] + keymap + con[start+1:]

	with open(path, 'w', encoding = 'utf-8') as fh:
		fh.write(con)
 def get_sublime_path(self):
     if sublime.platform() == 'osx':
         if not self.app_path_mac:
             # taken from https://github.com/freewizard/SublimeGotoFolder/blob/master/GotoFolder.py:
             from ctypes import cdll, byref, Structure, c_int, c_char_p, c_void_p
             from ctypes.util import find_library
             Foundation = cdll.LoadLibrary(find_library('Foundation'))
             CFBundleGetMainBundle = Foundation.CFBundleGetMainBundle
             CFBundleGetMainBundle.restype = c_void_p
             bundle = CFBundleGetMainBundle()
             CFBundleCopyBundleURL = Foundation.CFBundleCopyBundleURL
             CFBundleCopyBundleURL.argtypes = [c_void_p]
             CFBundleCopyBundleURL.restype = c_void_p
             url = CFBundleCopyBundleURL(bundle)
             CFURLCopyFileSystemPath = Foundation.CFURLCopyFileSystemPath
             CFURLCopyFileSystemPath.argtypes = [c_void_p, c_int]
             CFURLCopyFileSystemPath.restype = c_void_p
             path = CFURLCopyFileSystemPath(url, c_int(0))
             CFStringGetCStringPtr = Foundation.CFStringGetCStringPtr
             CFStringGetCStringPtr.argtypes = [c_void_p, c_int]
             CFStringGetCStringPtr.restype = c_char_p
             self.app_path_mac = CFStringGetCStringPtr(path, 0)
             CFRelease = Foundation.CFRelease
             CFRelease.argtypes = [c_void_p]
             CFRelease(path)
             CFRelease(url)
         return self.app_path_mac.decode() + '/Contents/SharedSupport/bin/subl'
     if sublime.platform() == 'linux':
         return open('/proc/self/cmdline').read().split(chr(0))[0]
     return sys.executable
        def open_workspace_window2(cb):
            if sublime.platform() == 'linux':
                subl = open('/proc/self/cmdline').read().split(chr(0))[0]
            elif sublime.platform() == 'osx':
                floorc = utils.load_floorc_json()
                subl = floorc.get('SUBLIME_EXECUTABLE')
                if not subl:
                    settings = sublime.load_settings('Floobits.sublime-settings')
                    subl = settings.get('sublime_executable', '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl')
                if not os.path.exists(subl):
                    return sublime.error_message('''Can't find your Sublime Text executable at %s.
Please add "sublime_executable": "/path/to/subl" to your ~/.floorc.json and restart Sublime Text''' % subl)
            elif sublime.platform() == 'windows':
                subl = sys.executable
            else:
                raise Exception('WHAT PLATFORM ARE WE ON?!?!?')

            command = [subl]
            if get_workspace_window() is None:
                command.append('--new-window')
            command.append('--add')
            command.append(G.PROJECT_PATH)

            msg.debug('command:', command)
            p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            poll_result = p.poll()
            msg.debug('poll:', poll_result)

            set_workspace_window(cb)
Beispiel #30
0
def get_article_paths(window):
    article_paths = []

    # load INPUTDIR
    inputdir = None
    makefile_params = parse_makefile(window)
    if makefile_params and "INPUTDIR_"+sublime.platform() in makefile_params:
        inputdir = makefile_params["INPUTDIR_"+sublime.platform()]
    elif makefile_params and "INPUTDIR" in makefile_params:
        inputdir = makefile_params["INPUTDIR"]
    else:
        return []

    # get paths of all articles in INPUTDIR
    inputdir_structure = os.walk(inputdir)
    if inputdir_structure:
        for (dirpath, dirnames, filenames) in inputdir_structure:
            for filename in filenames:
                article_path = os.path.join(dirpath, filename)
                if re.search(default_filter, article_path):
                    article_paths.append(article_path)
    else:
        return []

    return article_paths
Beispiel #31
0
    def run(self, base_file, user_file=None, default=None):
        """
        :param base_file:
            A unicode string of the path to the base settings file. Typically
            this will be in the form: "${packages}/PackageName/Package.sublime-settings"

        :param user_file:
            An optional file path to the user's editable version of the settings
            file. If not provided, the filename from base_file will be appended
            to "${packages}/User/".

        :param default:
            An optional unicode string of the default contents if the user
            version of the settings file does not yet exist. Use "$0" to place
            the cursor.
        """

        if base_file is None:
            raise ValueError(
                'No base_file argument was passed to edit_settings')

        platform_name = {
            'osx': 'OSX',
            'windows': 'Windows',
            'linux': 'Linux',
        }[sublime.platform()]

        variables = {
            'packages': '${packages}',
            'platform': platform_name,
        }

        base_file = sublime.expand_variables(base_file.replace('\\', '\\\\'),
                                             variables)
        if user_file is not None:
            user_file = sublime.expand_variables(
                user_file.replace('\\', '\\\\'), variables)

        base_path = base_file.replace('${packages}', 'res://Packages')
        is_resource = base_path.startswith('res://')
        file_name = os.path.basename(base_file)
        resource_exists = is_resource and base_path[
            6:] in sublime.find_resources(file_name)
        filesystem_exists = (not is_resource) and os.path.exists(base_path)

        if not resource_exists and not filesystem_exists:
            sublime.error_message('The settings file "' + base_path +
                                  '" could not be opened')
            return

        if user_file is None:
            user_package_path = os.path.join(sublime.packages_path(), 'User')
            user_file = os.path.join(user_package_path, file_name)

            # If the user path does not exist, and it is a supported
            # platform-variant file path, then try and non-platform-variant
            # file path.
            if not os.path.exists(os.path.join(user_package_path, file_name)):
                for suffix in {
                        '.sublime-keymap', '.sublime-mousemap', '.sublime-menu'
                }:
                    platform_suffix = ' (%s)%s' % (platform_name, suffix)
                    if not file_name.endswith(platform_suffix):
                        continue
                    non_platform_file_name = file_name[:-len(platform_suffix
                                                             )] + suffix
                    non_platform_path = os.path.join(user_package_path,
                                                     non_platform_file_name)
                    if os.path.exists(non_platform_path):
                        user_file = non_platform_path
                        break

        sublime.run_command('new_window')
        new_window = sublime.active_window()

        new_window.run_command(
            'set_layout', {
                'cols': [0.0, 0.5, 1.0],
                'rows': [0.0, 1.0],
                'cells': [[0, 0, 1, 1], [1, 0, 2, 1]]
            })
        new_window.focus_group(0)
        new_window.run_command('open_file', {'file': base_file})
        new_window.focus_group(1)
        new_window.run_command('open_file', {
            'file': user_file,
            'contents': default
        })

        new_window.set_tabs_visible(True)
        new_window.set_sidebar_visible(False)

        base_view = new_window.active_view_in_group(0)
        user_view = new_window.active_view_in_group(1)

        base_settings = base_view.settings()
        base_settings.set('edit_settings_view', 'base')
        base_settings.set('edit_settings_other_view_id', user_view.id())

        user_settings = user_view.settings()
        user_settings.set('edit_settings_view', 'user')
        user_settings.set('edit_settings_other_view_id', base_view.id())
        if not os.path.exists(user_file):
            user_view.set_scratch(True)
            user_settings.set('edit_settings_default',
                              default.replace('$0', ''))
 def encode_process_command(self, command):
     is_sublime_2_and_in_windows = sublime.platform() == "windows" and int(
         sublime.version()) < 3000
     return command.encode(sys.getfilesystemencoding()
                           ) if is_sublime_2_and_in_windows else command
    def _on_main_thread(self, results):
        builder_name = get_setting(
            'builder', 'traditional', view=self.view
        )

        if builder_name in ['', 'default']:
            builder_name = 'traditional'

        builder_settings = get_setting('builder_settings', view=self.view)
        builder_path = get_setting('builder_path', view=self.view)

        if builder_name in ['simple', 'traditional', 'script']:
            builder_path = None
        else:
            bld_path = os.path.join(sublime.packages_path(), builder_path)
            add_plugin_path(bld_path)

        builder_name = _classname_to_internal_name(builder_name)

        try:
            get_plugin('{0}_builder'.format(builder_name))
            builder_available = True
        except NoSuchPluginException:
            traceback.print_exc()
            builder_available = False

        results.append([
            [u'Builder', u'Status'],
            [
                builder_name,
                u'available' if builder_available else u'missing'
            ]
        ])

        if builder_path:
            results.append([[u'Builder Path'], [builder_path]])

        if builder_settings is not None:
            table = [[u'Builder Setting', u'Value']]
            for key in sorted(builder_settings.keys()):
                value = builder_settings[key]
                table.append([key, value])
            results.append(table)

        # is current view a TeX file?
        view = self.view
        if view.score_selector(0, 'text.tex.latex') != 0:
            tex_root = get_tex_root(view)
            tex_directives = parse_tex_directives(
                tex_root,
                multi_values=['options'],
                key_maps={'ts-program': 'program'}
            )

            results.append([[u'TeX Root'], [tex_root]])

            results.append([
                [u'LaTeX Engine'],
                [
                    tex_directives.get(
                        'program',
                        get_setting(
                            'program', 'pdflatex', self.view
                        )
                    )
                ]
            ])

            table = [[u'LaTeX Output Setting', u'Value']]
            output_directory = get_output_directory(view)
            if output_directory:
                table.append(
                    ['output_directory', output_directory]
                )
            aux_directory = get_aux_directory(view)
            if aux_directory:
                table.append(['aux_directory', aux_directory])
            jobname = get_jobname(view)
            if jobname and jobname != os.path.splitext(
                os.path.basename(tex_root)
            )[0]:
                table.append(['jobname', jobname])

            if len(table) > 1:
                results.append(table)

            options = get_setting('builder_settings', {}, self.view).\
                get('options', [])
            options.extend(tex_directives.get('options', []))

            if len(options) > 0:
                table = [[u'LaTeX Options']]
                for option in options:
                    table.append([option])

                results.append(table)

        default_viewer = DEFAULT_VIEWERS.get(sublime.platform(), None)
        viewer_name = get_setting('viewer', default_viewer)
        if viewer_name in ['', 'default']:
            viewer_name = default_viewer

        try:
            viewer_plugin = get_plugin(viewer_name + '_viewer')
            viewer_available = True
        except NoSuchPluginException:
            viewer_available = False

        viewer_location = 'N/A'
        if viewer_available:
            if viewer_name == 'command':
                # assume the command viewer is always valid
                viewer_location = 'N/A'
            elif viewer_name in ('evince', 'okular', 'zathura'):
                viewer_location = which(viewer_name)
                viewer_available = bool(viewer_location)
            elif viewer_name == 'preview':
                viewer_location = '/Applications/Preview.app'

                if not os.path.exists(viewer_location):
                    try:
                        viewer_location = check_output([
                            'osascript',
                            '-e',
                            'POSIX path of '
                            '(path to app id "com.apple.Preview")'
                        ], use_texpath=False)
                    except subprocess.CalledProcessError:
                        viewer_location = None

                viewer_available = False \
                    if not viewer_location else os.path.exists(viewer_location)
            elif viewer_name == 'skim':
                viewer_location = '/Applications/Skim.app'

                if not os.path.exists(viewer_location):
                    try:
                        viewer_location = check_output([
                            'osascript',
                            '-e',
                            'POSIX path of '
                            '(path to app id "net.sourceforge.skim-app.skim")'
                        ], use_texpath=False)
                    except subprocess.CalledProcessError:
                        viewer_location = None

                viewer_available = False \
                    if not viewer_location else os.path.exists(viewer_location)
            elif viewer_name == 'sumatra':
                sumatra_exe = get_setting('viewer_settings', {}).\
                    get('sumatra', get_setting('windows', {}).
                        get('sumatra', 'SumatraPDF.exe')) or \
                    'SumatraPDF.exe'

                viewer_location = which(sumatra_exe)
                if not bool(viewer_location):
                    viewer_location = viewer_plugin()._find_sumatra_exe()
                    viewer_available = bool(viewer_location)

        if not viewer_available:
            viewer_location = 'N/A'

        results.append([
            [u'Viewer', u'Status', u'Location'],
            [
                viewer_name,
                u'available' if viewer_available else u'missing',
                viewer_location
            ]
        ])

        if callable(self.on_done):
            self.on_done(results)
    def run(self):
        texpath = self.texpath
        results = []

        env = copy.deepcopy(os.environ)

        if texpath is not None:
            env['PATH'] = texpath
        if self.build_env is not None:
            update_environment(env, self.build_env)

        table = [
            ['Variable', 'Value']
        ]

        table.append(['PATH', env.get('PATH', '')])

        if self.uses_miktex:
            get_tex_path_variable = get_tex_path_variable_miktex
            should_run = which('findtexmf', path=texpath) is not None
        else:
            get_tex_path_variable = get_tex_path_variable_texlive
            should_run = which('kpsewhich', path=texpath) is not None

        if should_run:
            for var in ['TEXINPUTS', 'BIBINPUTS', 'BSTINPUTS']:
                table.append([var, get_tex_path_variable(var, env)])

        if self.uses_miktex:
            for var in ['BIBTEX', 'LATEX', 'PDFLATEX', 'MAKEINDEX',
                        'MAKEINFO', 'TEX', 'PDFTEX', 'TEXINDEX']:
                value = env.get(var, None)
                if value is not None:
                    table.append([var, value])

        results.append(table)

        table = [
            ['Program', 'Location', 'Status', 'Version']
        ]

        # skip sublime_exe on OS X
        # we only use this for the hack to re-focus on ST
        # which doesn't work on OS X anyway
        if sublime.platform() != 'osx':
            sublime_exe = self.sublime_exe
            available = sublime_exe is not None

            if available:
                if not os.path.isabs(sublime_exe):
                    sublime_exe = which(sublime_exe)

                basename, extension = os.path.splitext(sublime_exe)
                if extension is not None:
                    sublime_exe = ''.join((basename, extension.lower()))

            version_info = get_version_info(
                sublime_exe, env=env
            ) if available else None

            table.append([
                'sublime',
                sublime_exe if available and version_info is not None else u'',
                (u'available'
                    if available and version_info is not None else u'missing'),
                version_info if version_info is not None else u'unavailable'
            ])

        # a list of programs, each program is either a string or a list
        # of alternatives (e.g. 32/64 bit version)
        programs = [
            'latexmk' if not self.uses_miktex else 'texify', 'pdflatex',
            'xelatex', 'lualatex', 'biber', 'bibtex', 'bibtex8', 'kpsewhich'
        ]

        if _HAS_PREVIEW:
            # ImageMagick requires gs to work with PDFs
            programs += [['magick', 'convert']]

        for program in programs:
            if isinstance(program, list):
                program_list = program
                program = program_list[0]
                location = None
                for p in program_list:
                    location = which(p, path=texpath)
                    if location is not None:
                        program = p
                        break
            else:
                location = which(program, path=texpath)

            available = location is not None

            if available:
                basename, extension = os.path.splitext(location)
                if extension is not None:
                    location = ''.join((basename, extension.lower()))

            version_info = get_version_info(
                location, env=env
            ) if available else None

            available_str = (
                u'available' if available and version_info is not None
                else u'missing'
            )

            if (available and program in ['magick', 'convert'] and
                    not convert_installed()):
                available_str = u'restart required'

            table.append([
                program,
                location if available and version_info is not None else u'',
                available_str,
                version_info if version_info is not None else u'unavailable'
            ])

        program = 'ghostscript'
        location = get_gs_command()

        available = location is not None

        if available:
            basename, extension = os.path.splitext(location)
            if extension is not None:
                location = ''.join((basename, extension.lower()))

        version_info = get_version_info(
            location, env=env
        ) if available else None

        available_str = (
            u'available' if available and version_info is not None
            else u'missing'
        )

        if available and _HAS_PREVIEW and not ghostscript_installed():
            available_str = u'restart required'

        table.append([
            program,
            location if available and version_info is not None else u'',
            available_str,
            version_info if version_info is not None else u'unavailable'
        ])

        results.append(table)

        # This really only works for the default template
        # Note that no attempt is made to find other packages that the
        # included package depends on
        if (_HAS_PREVIEW and ghostscript_installed() and
                get_setting('preview_math_template_file') is None and
                get_setting("preview_math_mode", view=self.view) != "none"):

            find_package_re = re.compile(
                r'\\usepackage(?:\[[^\]]*\])?\{(?P<pkg>[^\}]*)\}'
            )

            packages = ["standalone.cls", "preview.sty", "xcolor.sty"]

            package_settings = get_setting(
                "preview_math_template_packages", [], view=self.view)
            # extract all packages from each package line
            for pkg_str in package_settings:
                # search for all \usepackage in the line
                for m in find_package_re.finditer(pkg_str):
                    pkg_arg = m.group("pkg")
                    # search for each package in the \usepackage argument
                    for pkg in pkg_arg.split(","):
                        pkg = pkg.strip()
                        if pkg:
                            packages.append(pkg + ".sty")

            if packages:
                table = [[u'Packages for equation preview', u'Status']]

                for package in packages:
                    available = kpsewhich(package) is not None
                    package_name = package.split(".")[0]
                    table.append([
                        package_name,
                        (u'available' if available else u'missing')
                    ])

                results.append(table)

        run_on_main_thread(partial(self._on_main_thread, results), timeout=30)
    def lookup_executables(cls, cmd):
        """
        Attempt to locate the gem and ruby specified in cmd, return new cmd list.

        The following forms are valid:

        gem@ruby
        gem
        ruby

        If rbenv is installed and the gem is also under rbenv control,
        the gem will be executed directly. Otherwise [ruby <, gem>] will
        be returned.

        If rvm-auto-ruby is installed, [rvm-auto-ruby <, gem>] will be
        returned.

        Otherwise [ruby] or [gem] will be returned.

        """

        ruby = None
        rbenv = util.which('rbenv')

        if not rbenv:
            ruby = util.which('rvm-auto-ruby')

        if not ruby:
            ruby = util.which('ruby')

        if not ruby:
            ruby = util.which('jruby')

        if not rbenv and not ruby:
            persist.printf(
                'WARNING: {} deactivated, cannot locate ruby, rbenv or rvm-auto-ruby'
                .format(cls.name, cmd[0])
            )
            return []

        if isinstance(cmd, str):
            cmd = shlex.split(cmd)

        match = CMD_RE.match(cmd[0])

        if match:
            gem = match.group('gem')
        elif cmd[0] != 'ruby':
            gem = cmd[0]
        else:
            gem = ''

        if gem:
            gem_path = util.which(gem)

            if gem_path:
                if (rbenv and
                    ('{0}.rbenv{0}shims{0}'.format(os.sep) in gem_path or
                     (os.altsep and '{0}.rbenv{0}shims{0}'.format(os.altsep in gem_path)))):
                    ruby_cmd = [gem_path]
                elif (sublime.platform() == 'windows'):
                    ruby_cmd = [gem_path]
                else:
                    ruby_cmd = [ruby, gem_path]
            else:
                persist.printf(
                    'WARNING: {} deactivated, cannot locate the gem \'{}\''
                    .format(cls.name, gem)
                )
                return []
        else:
            ruby_cmd = [ruby]

        if cls.env is None:
            # Don't use GEM_HOME with rbenv, it prevents it from using gem shims
            if rbenv:
                cls.env = {}
            else:
                gem_home = util.get_environment_variable('GEM_HOME')

                if gem_home:
                    cls.env = {'GEM_HOME': gem_home}
                else:
                    cls.env = {}

        return ruby_cmd
Beispiel #36
0
    def muterun(self, user_command):
        # create a parsed command line string
        if version_info[0] == 3:
            com_args = shlex.split(user_command) # use shlex for command line handling in ST3 / Py3
        else:
            com_args = user_command.split() # use simple split on whitespace in ST2, Py2.6 does not support unicode in shlex
        # Handle missing command when user presses enter/return key
        if not com_args:
            no_command_msg = "Please enter a command"
            self.view.run_command('glue_writer', {'text': no_command_msg, 'command': '', 'exit': False})
        # EXIT command
        elif com_args[0] == "exit":
            self.cleanup() # run the cleanup method
            self.view.run_command('glue_writer', {'text': '', 'command': '', 'exit': True})
        # CD command
        elif com_args[0] == "cd":
            if len(com_args) > 1:
                # include the ~ user home directory idiom
                if com_args[1] == "~":
                    change_path = os.path.expanduser('~')
                else:
                    change_path = com_args[1]
                if os.path.exists(change_path) and os.path.isdir(change_path):
                    os.chdir(change_path)
                    directory_change_abspath = os.getcwd()
                    dir_change_text = directory_change_abspath + '\n'
                    directory_change_cmd = "cd " + change_path
                    self.current_dirpath = directory_change_abspath
                    self.settings.set('glue_working_directory', directory_change_abspath)
                    sublime.status_message('Glue: Current directory: ' + directory_change_abspath) # notify user of CWD
                    self.view.run_command('glue_writer', {'text': dir_change_text, 'command': directory_change_cmd, 'exit': False})
                else:
                    directory_change_cmd = "cd " + change_path
                    dirchange_error_message = "Directory path '" + change_path + "' does not exist\n"
                    self.view.run_command('glue_writer', {'text': dirchange_error_message, 'command': directory_change_cmd, 'exit': False})
            else:
                dirchange_error_message = "Please enter a path following the 'cd' command\n"
                self.view.run_command('glue_writer', {'text': dirchange_error_message, 'command': 'cd', 'exit': False})
        # GLUE commands
        elif com_args[0] == 'glue':
            glue_command = ' '.join(com_args)
            if len(com_args) > 1:
                # HELP Command
                if com_args[1] == "--help" or com_args[1] == "-h" or com_args[1] == "help":
                    help_text = get_help_text()
                    self.view.run_command('glue_writer', {'text': help_text, 'command': glue_command, 'exit': False})
                # BROWSE command
                elif com_args[1] == "browse":
                    if len(com_args) > 2:
                        import webbrowser
                        browse_string = com_args[2]
                        # if they requested a url with protocol, just open it
                        if browse_string.startswith('http://') or browse_string.startswith('https://'):
                            webbrowser.open(browse_string)
                        else:
                            # check if it is a local file that user wants to open in browser
                              # remove the initial OS dependent filepath separator character if added (will be added back in .join method below)
                            if browse_string.startswith(os.sep):
                                browse_string = browse_string[1:] # remove the first char (?are there typically two chars '\\' in Windows?)
                            elif os.altsep != None:
                                if browse_string.startswith(os.altsep): # if there is an alternate separator (i.e. / on windows)
                                    browse_string = browse_string[1:] # then remove it
                            check_path = os.path.join(os.path.abspath(self.current_dirpath), browse_string)
                            # test for existence of local file on the path
                            if self.is_file_here(check_path):
                                webbrowser.open('file://' + check_path) # if it is a local file, open it in browser
                            else:
                                webbrowser.open('http://' + browse_string) # if not, assume that it is a URL without protcol and add it
                        browser_msg = "glue browse [ " + browse_string + " ] complete\n"
                        self.view.run_command('glue_writer', {'text': browser_msg, 'command': glue_command, 'exit': False})
                    else:
                        browser_error_msg = "Please enter a URL or local filepath after the glue browse command\n"
                        self.view.run_command('glue_writer', {'text': browser_error_msg, 'command': glue_command, 'exit': False})
                # CLEAR command
                elif com_args[1] == "clear":
                    self.view.run_command('glue_clear_editor')
                    # keeps the input panel open for more commands
                    self.view.run_command('glue')
                # FINDER command
                elif com_args[1] == "finder":
                    # user is requesting a directory as an argument
                    if len(com_args) > 2:
                        finder_dirpath = com_args[2]
                        if os.path.isdir(finder_dirpath):
                            self.view.window().run_command("open_dir", {"dir": os.path.abspath(finder_dirpath)}) # open it
                            curdir_finder_msg = "The requested directory was opened in your finder\n"
                        elif os.path.isfile(finder_dirpath):
                            finder_dirpath = os.path.dirname(finder_dirpath)
                            self.view.window().run_command("open_dir", {"dir": os.path.abspath(finder_dirpath)}) # open it
                            curdir_finder_msg = "The requested directory was opened in your finder\n"
                        else:
                            curdir_finder_msg = "Unable to find the requested directory path.  Please try again.\n"
                        # provide Glue view output to user after execution of the finder reveal
                        self.view.run_command('glue_writer', {'text': curdir_finder_msg, 'command': glue_command, 'exit': False})
                    # user is requesting the current working directory (i.e. no argument)
                    else:
                        if len(self.current_dirpath) > 0 and os.path.isdir(self.current_dirpath):
                            self.view.window().run_command("open_dir", {"dir": self.current_dirpath})
                            curdir_finder_msg = "The current directory was opened in your finder.\n"
                            self.view.run_command('glue_writer', {'text': curdir_finder_msg, 'command': glue_command, 'exit': False})
                        else:
                            curdir_finderror_msg = "Unable to detect the current working directory.  Please restart the Glue plugin and try again.\n"
                            self.view.run_command('glue_writer', {'text': curdir_finderror_msg, 'command': glue_command, 'exit': False})
                # GOTO command
                elif com_args[1] == "goto":
                    if len(com_args) > 2:
                        goto_user_msg = "goto " + com_args[2] + " completed\n"
                        self.view.window().run_command("show_overlay", {"overlay": "goto", "show_files": True, "text": com_args[2]})
                        self.view.run_command('glue_writer', {'text': goto_user_msg, 'command': glue_command, 'exit': False})
                    else:
                        # if no query string, just open the overlay
                        goto_user_msg = "goto overlay launch completed\n"
                        self.view.window().run_command("show_overlay", {"overlay": "goto", "show_files": True})
                        self.view.run_command('glue_writer', {'text': goto_user_msg, 'command': glue_command, 'exit': False})
                # LOCALHOST command
                elif com_args[1] == "localhost":
                    import webbrowser
                    localhost_url = 'http://localhost:8000'
                    if len(com_args) > 2:
                        protocol = com_args[2] # the argument is the requested protocol (doesn't perform sanity check)
                        localhost_url = 'http://localhost:' + protocol
                    webbrowser.open(localhost_url)
                    localhost_browse_msg = "glue localhost complete\n"
                    self.view.run_command('glue_writer', {'text': localhost_browse_msg, 'command': glue_command, 'exit': False})
                # NEW command
                elif com_args[1] == "new":
                    filenew_text = "glue new command completed\n"
                    self.view.run_command('glue_writer', {'text': filenew_text, 'command': glue_command, 'exit': False})
                    self.view.window().new_file()
                # OPEN command
                elif com_args[1] == "open":
                    if len(com_args) > 2:
                        fileopen_text = "glue open command completed\n"
                        self.view.run_command('glue_writer', {'text': fileopen_text, 'command': glue_command, 'exit': False})
                        self.view.window().run_command('glue_file_opener', {'current_dir': self.current_dirpath, 'file_list': com_args[2:]})
                    else:
                        missing_file_error_msg = "Please enter at least one filepath after the open command.\n"
                        self.view.run_command('glue_writer', {'text': missing_file_error_msg, 'command': glue_command, 'exit': False})
                # PATH command
                elif com_args[1] == "path":
                    if len(self.userpath) == 0:
                        # obtain the 'real' mac osx path using the get_mac_path method if not set by user
                        if sublime.platform() == "osx":
                            # get the PATH
                            updated_path = self.get_mac_path() # attempt to obtain the PATH set in the user's respective shell startup file
                            # set the Mac environ PATH to the obtained PATH
                            os.environ['PATH'] = updated_path
                            # assign the PATH to the self.userpath attribute for the executable search below (and for reuse while running)
                            self.userpath = updated_path
                            the_path = self.userpath
                        elif sublime.platform() == "windows":
                            the_path = os.environ['PATH']
                            # do not set the PATH in Windows, letting Win shell handle the command
                        elif sublime.platform() == "linux":
                            self.userpath = os.environ['PATH']
                            the_path = self.userpath
                    else:
                        # if there is a self.userpath that is set (user set in settings, previously set above) then set Python environ PATH string
                        the_path = self.userpath
                    self.view.run_command('glue_writer', {'text': the_path + '\n', 'command': glue_command, 'exit': False})
                # TEMPLATE command
                elif com_args[1] == "template":
                    if len(com_args) > 2:
                        template_name = ""
                        template_filename = ""
                        template_multi = False
                        # test for the flag and name option in the user command
                        for argument in com_args[2:]: # only test the arguments after the 'template' subcommand
                            if "--multi" in argument:
                                template_multi = True # user indicated that the file will specify multiple file paths
                            elif argument.startswith('--name='):
                                name_list = argument.split('=')
                                template_filename = name_list[1] # the user assigned file write name of the file
                            else:
                                template_name = argument # if it is not one of the above options, then it is the requested template name
                        print_string = template_name + " " + template_filename + " " + str(template_multi)
                        self.view.run_command('glue_writer', {'text': print_string, 'command': glue_command, 'exit': False})
                    else:
                        # user did not enter a template name
                        template_err_msg = "Please enter a template name after your command.\n"
                        self.view.run_command('glue_writer', {'text': template_err_msg, 'command': glue_command, 'exit': False})
                # USER command
                elif com_args[1] == "user":
                    uc_file_path = os.path.join(sublime.packages_path(), 'Glue-Commands', 'glue.json')
                    if self.is_file_here(uc_file_path):
                        fr = FileReader(uc_file_path)
                        user_json = fr.read_utf8()
                        usercom_dict = json.loads(user_json)
                        if len(usercom_dict) > 0:
                            if len(usercom_dict) == 1:
                                com_extension_string = 'extension'
                                com_number_string = 'lonely'
                            else:
                                com_extension_string = 'extensions'
                                com_number_string = str(len(usercom_dict))
                            number_com_msg = "Your " + com_number_string + " Glue " + com_extension_string + ":\n\n"
                            com_list = []
                            for key, value in self.xitems(usercom_dict):
                                com_string = key + " : " + value
                                com_list.append(com_string)
                            com_string = '\n'.join(sorted(com_list))
                            com_string = number_com_msg + com_string + '\n'
                            self.view.run_command('glue_writer', {'text': com_string, 'command': glue_command, 'exit': False})
                        else:
                            user_error_msg = "Your glue.json file does not contain any commands\n"
                            self.view.run_command('glue_writer', {'text': user_error_msg, 'command': glue_command, 'exit': False})
                    else:
                        usercom_error_msg = "The glue.json file could not be found.  Please confirm that this is contained in a Glue-Commands directory in your Sublime Text Packages directory.\n"
                        self.view.run_command('glue_writer', {'text': usercom_error_msg, 'command': glue_command, 'exit': False})
                # WCO command
                elif com_args[1] == "wco":
                    if len(com_args) > 2:
                        fileopen_text = "glue wco command completed\n"
                        self.view.run_command('glue_writer', {'text': fileopen_text, 'command': glue_command, 'exit': False})
                        self.view.window().run_command('glue_file_wildcard_opener', {'current_dir': self.current_dirpath, 'match_pattern': com_args[2]})
                    else:
                        missing_file_error_msg = "Please enter at least one filepath after the open command.\n"
                        self.view.run_command('glue_writer', {'text': missing_file_error_msg, 'command': glue_command, 'exit': False})
                # TEST command
                elif com_args[1] == "test":
                    pass
                    # test open containing folder

                    #self.view.window().run_command("open_dir", {"dir": self.current_dirpath})

                    # self.view.run_command('glue_writer', {'text': current_proj, 'command': glue_command, 'exit': False})
                # USER ALIAS commands
                else:
                    if len(com_args) > 1:
                        uc_file_path = os.path.join(sublime.packages_path(), 'Glue-Commands', 'glue.json')
                        if self.is_file_here(uc_file_path):
                            fr = FileReader(uc_file_path)
                            user_json = fr.read_utf8()
                            usercom_dict = json.loads(user_json)
                            # if arguments from command, add those in location indicated by the file
                            if len(com_args) > 2:
                                # arguments were included on the command line, pass them to the user command
                                arguments = ' '.join(com_args[2:])
                            else:
                                # no additional arguments were included so pass empty string if there is an {{args}} tag
                                arguments = ''
                            if com_args[1] in usercom_dict:
                                user_command = usercom_dict[com_args[1]]
                                user_command = user_command.replace('{{args}}', arguments) # replace with CL args
                                user_command = user_command.replace('{{pwd}}', os.getcwd()) #  replace with working dir path
                                user_command = user_command.replace('{{clipboard}}', sublime.get_clipboard()) # replace with contents of clipboard
                                self.muterun(user_command) # execute the command
                            else:
                                # didn't find a glue alias with the requested name in the existing glue alias settings file
                                bad_cmd_error_msg = "Glue could not identify that command.  Please try again.\n"
                                self.view.run_command('glue_writer', {'text': bad_cmd_error_msg, 'command': glue_command, 'exit': False})
                        # Didn't find a glue alias setting file, provide error message
                        else:
                            bad_cmd_error_msg = "Glue could not identify that command.  Please try again.\n"
                            self.view.run_command('glue_writer', {'text': bad_cmd_error_msg, 'command': glue_command, 'exit': False})
            else:
                missing_arg_error_msg = "Glue requires an argument.  Please use 'glue help' for for more information.\n"
                self.view.run_command('glue_writer', {'text': missing_arg_error_msg, 'command': glue_command, 'exit': False})
        # Execute the system command that was entered
        else:
            try:
                if len(com_args) > 0:
                    arguments = ' '.join(com_args[1:])
                else:
                    arguments = ''

                command = os.path.join(self.get_path(com_args[0]), com_args[0]) + " " + arguments
                t = threading.Thread(target=self.execute_command, args=(command, user_command))
                t.start() # launch the thread to execute the command
                self.progress_indicator(t) # provide progress indicator
                self.print_on_complete(t, user_command) # polls for completion of the thread and prints to editor
            except Exception as e:
                raise e
Beispiel #37
0
 def cleanup(self):
     self.current_dirpath = "" # clear the saved working directory path
     self.start_dirpath = "" # clear the start directory path for the file
     self.settings.set('glue_working_directory', '') # clear the saved directory path
     if sublime.platform() == "osx":
         os.environ['PATH'] = self.original_env_path # cleanup any environ PATH changes that Glue performed on Mac systems
Beispiel #38
0
 def load(self):
     if platform() != 'windows':
         raise Exception(
             'WindowsDefaultViewer only supported on Windows platforms')
Beispiel #39
0
                'Aborting lint. SublimeLinter needs a restart of Sublime.')
            return True

        changed = view.change_count() != initial_change_count
        if changed:
            logger.info('Buffer {} inconsistent. Aborting lint.'.format(
                view.buffer_id()))

        return changed

    return view_has_changed


ENV_READY_TIMEOUT = 60
ENV_IS_READY_STATE = {
    'ready': False if sublime.platform() == 'osx' else True,
    'start_time': None,
    'first_path': None
}


def environment_is_ready():
    ready = ENV_IS_READY_STATE['ready']
    if ready:
        return True

    path = os.environ['PATH']
    if '/local/' in path:
        logger.info('Env seems ok: PATH: {}'.format(path))
        ENV_IS_READY_STATE['ready'] = True
        return True
Beispiel #40
0
    def run(self, edit, transformation):

        # string to work with
        region = sublime.Region(0, self.view.size())
        contents = self.view.substr(region)

        # pandoc executable
        binary_name = 'pandoc.exe' if sublime.platform(
        ) == 'windows' else 'pandoc'
        pandoc = _find_binary(binary_name, _s('pandoc-path'))
        if pandoc is None:
            return
        cmd = [pandoc]

        # from format
        score = 0
        for scope, c_iformat in transformation['scope'].items():
            c_score = self.view.score_selector(0, scope)
            if c_score <= score:
                continue
            score = c_score
            iformat = c_iformat
        cmd.extend(['-f', iformat])

        # configured parameters
        args = Args(transformation['pandoc-arguments'])
        # Use pandoc output format name as file extension unless specified by out-ext in transformation
        try:
            transformation['out-ext']
        except:
            argsext = None
        else:
            argsext = transformation['out-ext']
        # output format
        oformat = args.get(short=['t', 'w'], long=['to', 'write'])
        oext = argsext

        # pandoc doesn't actually take 'pdf' as an output format
        # see https://github.com/jgm/pandoc/issues/571
        if oformat == 'pdf':
            args = args.remove(short=['t', 'w'],
                               long=['to', 'write'],
                               values=['pdf'])

        # output file locally
        try:
            transformation['out-local']
        except:
            argslocal = None
        else:
            argslocal = transformation['out-local']

        # get current file path
        current_file_path = self.view.file_name()
        if current_file_path:
            working_dir = os.path.dirname(current_file_path)
            file_name = os.path.splitext(current_file_path)[0]
        else:
            working_dir = None
            file_name = None

        # if write to file, add -o if necessary, set file path to output_path
        if oformat is not None and oformat in _s('pandoc-format-file'):
            output_path = args.get(short=['o'], long=['output'])
            if output_path is None:
                # note the file extension matches the pandoc format name
                if argslocal and file_name:
                    output_path = file_name
                else:
                    output_path = tempfile.NamedTemporaryFile().name
                # If a specific output format not specified in transformation, default to pandoc format name
                if oext is None:
                    output_path += "." + oformat
                else:
                    output_path += "." + oext
                args.extend(['-o', output_path])

        cmd.extend(args)

        # run pandoc
        process = subprocess.Popen(cmd,
                                   shell=False,
                                   stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,
                                   cwd=working_dir)
        result, error = process.communicate(contents.encode('utf-8'))

        # handle pandoc errors
        if error:
            sublime.error_message('\n\n'.join([
                'Error when running:', ' '.join(cmd),
                error.decode('utf-8').strip()
            ]))
            return

        # write pandoc command to console
        print(' '.join(cmd))

        # if write to file, open
        if oformat is not None and oformat in _s('pandoc-format-file'):
            try:
                if sublime.platform() == 'osx':
                    subprocess.call(["open", output_path])
                elif sublime.platform() == 'windows':
                    os.startfile(output_path)
                elif os.name == 'posix':
                    subprocess.call(('xdg-open', output_path))
            except:
                sublime.message_dialog('Wrote to file ' + output_path)
            return

        # write to buffer
        if result:
            if transformation['new-buffer']:
                w = self.view.window()
                w.new_file()
                view = w.active_view()
                region = sublime.Region(0, view.size())
            else:
                view = self.view
            view.replace(edit, region,
                         result.decode('utf8').replace('\r\n', '\n'))
            view.set_syntax_file(transformation['syntax_file'])
 def _preexec_val(self):
     return os.setsid if sublime.platform() != "windows" else None
	def commands(self):
		# Print greeting
		self.display("\n\nScriptBuilder: ")

		# create an environment to be used for all subprocesses
		# adds any settings from the `env` dict to the current
		# environment
		env = copy(os.environ)
		if self.env is not None and isinstance(self.env, dict):
			env.update(self.env)

		if self.cmd is None:
			sublime.error_message(
				"You MUST set a command in your LaTeXTools.sublime-settings " +
				"file before launching the script builder."
			)
			# I'm not sure this is the best way to handle things...
			raise StopIteration()

		if isinstance(self.cmd, strbase):
			self.cmd = [self.cmd]

		for cmd in self.cmd:
			replaced_var = False
			if isinstance(cmd, strbase):
				cmd, replaced_var = self.substitute(cmd)
			else:
				for i, component in enumerate(cmd):
					cmd[i], replaced = self.substitute(component)
					replaced_var = replaced_var or replaced

			if not replaced_var:
				if isinstance(cmd, strbase):
					cmd += ' ' + self.base_name
				else:
					cmd.append(self.base_name)

			if sublime.platform() != 'windows':
				if not isinstance(cmd, strbase):
					cmd = u' '.join([quote(s) for s in cmd])
				self.display("Invoking '{0}'... ".format(cmd))
			else:
				if not isinstance(cmd, strbase):
					self.display("Invoking '{0}'... ".format(
						u' '.join([quote(s) for s in cmd])
					))
				else:
					self.display("Invoking '{0}'... ".format(cmd))

			startupinfo = None
			preexec_fn = None

			if sublime.platform() == 'windows':
				startupinfo = subprocess.STARTUPINFO()
				startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
			else:
				preexec_fn = os.setsid

			p = Popen(
				cmd,
				stdout=PIPE,
				stderr=STDOUT,
				startupinfo=startupinfo,
				shell=True,
				env=env,
				cwd=self.tex_dir,
				preexec_fn=preexec_fn
			)

			yield (p, "")

			self.display("done.\n")

			# This is for debugging purposes
			if self.display_log and p.stdout is not None:
				self.display("\nCommand results:\n")
				self.display(self.out)
				self.display("\n\n")
Beispiel #43
0
import sublime
from os import path

root_dir = path.split(__file__)[0]
base_name = path.split(root_dir)[1]

settings_file = 'FastOlympicCoding.sublime-settings'

default_settings_file = 'FastOlympicCoding ({os}).sublime-settings'.format(
    os={
        'windows': 'Windows',
        'linux': 'Linux',
        'osx': 'OSX'
    }[sublime.platform().lower()])

settings = {}
run_supported_exts = set()


def get_settings():
    return settings


def init_settings(_settings):
    global settings
    settings = _settings


def is_run_supported_ext(ext):
    _run_settings = get_settings().get('run_settings', None)
    if _run_settings is not None:
Beispiel #44
0
def fix_osx_path():
    if str(sublime.platform()) == "osx":
        capitan_path = "/usr/local/bin"
        if not capitan_path in os.environ["PATH"]:
            os.environ["PATH"] += ":" + capitan_path
Beispiel #45
0
def getSysPlatform():
	# platform may be "osx", "linux" or "windows"
	sys_platform = sublime.platform()
	return sys_platform
Beispiel #46
0
    def list_available_packages(self):
        """
        Returns a master list of every available package from all sources

        :return:
            A dict in the format:
            {
                'Package Name': {
                    # Package details - see example-packages.json for format
                },
                ...
            }
        """

        if self.settings.get('debug'):
            console_write(u"Fetching list of available packages", True)
            console_write(u"  Platform: %s-%s" %
                          (sublime.platform(), sublime.arch()))
            console_write(u"  Sublime Text Version: %s" % sublime.version())
            console_write(u"  Package Control Version: %s" % __version__)

        cache_ttl = self.settings.get('cache_length')
        repositories = self.list_repositories()
        packages = {}
        downloaders = {}
        active = []
        repos_to_download = []
        name_map = self.settings.get('package_name_map', {})

        # Repositories are run in reverse order so that the ones first
        # on the list will overwrite those last on the list
        for repo in repositories[::-1]:
            cache_key = repo + '.packages'
            repository_packages = get_cache(cache_key)

            if repository_packages != None:
                packages.update(repository_packages)

            else:
                domain = urlparse(repo).hostname
                if domain not in downloaders:
                    downloaders[domain] = BackgroundDownloader(
                        self.settings, REPOSITORY_PROVIDERS)
                downloaders[domain].add_url(repo)
                repos_to_download.append(repo)

        for downloader in list(downloaders.values()):
            downloader.start()
            active.append(downloader)

        # Wait for all of the downloaders to finish
        while active:
            downloader = active.pop()
            downloader.join()

        # Grabs the results and stuff it all in the cache
        for repo in repos_to_download:
            domain = urlparse(repo).hostname
            downloader = downloaders[domain]
            provider = downloader.get_provider(repo)

            _repository_packages = provider.get_packages()
            if _repository_packages == False:
                continue

            # Allow name mapping of packages for schema version < 2.0
            repository_packages = {}
            for name, info in _repository_packages.items():
                name = name_map.get(name, name)
                info['name'] = name
                repository_packages[name] = info

            cache_key = repo + '.packages'
            set_cache(cache_key, repository_packages, cache_ttl)
            packages.update(repository_packages)

            renamed_packages = provider.get_renamed_packages()
            set_cache_under_settings(self, 'renamed_packages', repo,
                                     renamed_packages, cache_ttl)

            unavailable_packages = provider.get_unavailable_packages()
            set_cache_under_settings(self,
                                     'unavailable_packages',
                                     repo,
                                     unavailable_packages,
                                     cache_ttl,
                                     list_=True)

        return packages
                    return message('package not found')

            tests = [
                t for t in resources if t.startswith('Packages/%s/' % package)
            ]

        if not len(tests):
            return message(
                'ColorSchemeUnit: no tests found; be sure run tests from within the packages directory'
            )

        if not output:
            output = TestOutputPanel('color_scheme_unit', self.window)

        output.write("ColorSchemeUnit %s\n\n" % __version__)
        output.write("Runtime: %s build %s\n" % (platform(), version()))
        output.write("Package: %s\n" % package)

        if file:
            output.write("File:    %s\n" % file)

        output.write("\n")

        result_printer = ResultPrinter(
            output, debug=self.view.settings().get('color_scheme_unit.debug'))
        code_coverage = Coverage(
            output,
            self.view.settings().get('color_scheme_unit.coverage'), file)

        skipped = []
        errors = []
Beispiel #48
0
import json
import locale
from numbers import Number
import os
import getpass
import re
import shutil
from string import Template
import stat
import sublime
import subprocess
import sys
import tempfile
from xml.etree import ElementTree

if sublime.platform() != 'windows':
    import pwd

#
# Public constants
#
STREAM_STDOUT = 1
STREAM_STDERR = 2
STREAM_BOTH = STREAM_STDOUT + STREAM_STDERR

PYTHON_CMD_RE = re.compile(r'(?P<script>[^@]+)?@python(?P<version>[\d\.]+)?')
VERSION_RE = re.compile(r'(?P<major>\d+)(?:\.(?P<minor>\d+))?')

INLINE_SETTINGS_RE = re.compile(
    r'(?i).*?\[sublimelinter[ ]+(?P<settings>[^\]]+)\]')
INLINE_SETTING_RE = re.compile(
Beispiel #49
0
def find_python(version=None, script=None, module=None):
    """
    Return the path to and version of python and an optional related script.

    If not None, version should be a string/numeric version of python to locate, e.g.
    '3' or '3.3'. Only major/minor versions are examined. This method then does
    its best to locate a version of python that satisfies the requested version.
    If module is not None, Sublime Text's python version is tested against the
    requested version.

    If version is None, the path to the default system python is used, unless
    module is not None, in which case '<builtin>' is returned.

    If not None, script should be the name of a python script that is typically
    installed with easy_install or pip, e.g. 'pep8' or 'pyflakes'.

    A tuple of the python path, script path, major version, minor version is returned.

    """

    from . import persist
    persist.debug('find_python(version={!r}, script={!r}, module={!r})'.format(
        version, script, module))

    path = None
    script_path = None

    requested_version = {'major': None, 'minor': None}

    if module is None:
        available_version = {'major': None, 'minor': None}
    else:
        available_version = {
            'major': sys.version_info.major,
            'minor': sys.version_info.minor
        }

    if version is None:
        # If no specific version is requested and we have a module,
        # assume the linter will run using ST's python.
        if module is not None:
            result = ('<builtin>', script, available_version['major'],
                      available_version['minor'])
            persist.debug('find_python: <=', repr(result))
            return result

        # No version was specified, get the default python
        path = find_executable('python')
        persist.debug('find_python: default python =', path)
    else:
        version = str(version)
        requested_version = extract_major_minor_version(version)
        persist.debug('find_python: requested version =',
                      repr(requested_version))

        # If there is no module, we will use a system python.
        # If there is a module, a specific version was requested,
        # and the builtin version does not fulfill the request,
        # use the system python.
        if module is None:
            need_system_python = True
        else:
            persist.debug('find_python: available version =',
                          repr(available_version))
            need_system_python = not version_fulfills_request(
                available_version, requested_version)
            path = '<builtin>'

        if need_system_python:
            if sublime.platform() in ('osx', 'linux'):
                path = find_posix_python(version)
            else:
                path = find_windows_python(version)

            persist.debug('find_python: system python =', path)

    if path and path != '<builtin>':
        available_version = get_python_version(path)
        persist.debug('find_python: available version =',
                      repr(available_version))

        if version_fulfills_request(available_version, requested_version):
            if script:
                script_path = find_python_script(path, script)
                persist.debug('find_python: {!r} path = {}'.format(
                    script, script_path))

                if script_path is None:
                    path = None
                elif script_path.endswith('.exe'):
                    path = script_path
                    script_path = None
        else:
            path = script_path = None

    result = (path, script_path, available_version['major'],
              available_version['minor'])
    persist.debug('find_python: <=', repr(result))
    return result
 def run(self, edit):
     self.view.window().open_file(
         settings.get(sublime.platform() + '_hosts_file_location'))
Beispiel #51
0
# @date         2020-03-19 11:16:59 +0800
# @author       Tomy Hsieh <*****@*****.**>
# @copyright    Copyright (c) 2019-present, Duc Ng. (bitst0rm)
# @link         https://github.com/bitst0rm
# @license      The MIT License (MIT)

import os
from os.path import (abspath, basename, expanduser, expandvars, isdir, isfile,
                     join, normpath, pathsep, split, splitext)
import sys
from imp import reload
import logging
import sublime

log = logging.getLogger('root')
IS_WINDOWS = sublime.platform() == 'windows'
VERSION = '0.1.6'
PLUGIN_NAME = 'Formatter'
ASSETS_DIRECTORY = 'formatter.assets'

LOAD_ORDER = [
    '.src.formatter_beautysh', '.src.formatter_black',
    '.src.formatter_clangformat', '.src.formatter_cleancss',
    '.src.formatter_csscomb', '.src.formatter_eslint',
    '.src.formatter_htmlminifier', '.src.formatter_htmltidy',
    '.src.formatter_jsbeautifier', '.src.formatter_jsonmax',
    '.src.formatter_jsonmin', '.src.formatter_perltidy',
    '.src.formatter_phpcsfixer', '.src.formatter_prettier',
    '.src.formatter_rubocop', '.src.formatter_stylelint',
    '.src.formatter_terser', '.src.formatter_uncrustify',
    '.src.formatter_yapf', '.src.formatter', '.src.common', '.main'
Beispiel #52
0
# Copyright (C) 2018 The NeoVintageous Team (NeoVintageous).
#
# This file is part of NeoVintageous.
#
# NeoVintageous is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# NeoVintageous is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NeoVintageous.  If not, see <https://www.gnu.org/licenses/>.

import sublime

HOST_PLATFORM = sublime.platform()

WINDOWS = 'windows'
LINUX = 'linux'
OSX = 'osx'
Beispiel #53
0
    def run(self, edit):
        paste = None
        sel = self.view.sel()
        start_color = None
        start_color_osx = None
        start_color_win = 0x000000

        # get the currently selected color - if any
        if len(sel) > 0:
            selected = self.view.substr(self.view.word(sel[0])).strip()
            if selected.startswith('#'): selected = selected[1:]
            if self.__is_valid_hex_color(selected):
                if len(selected) > 6:
                    selected = selected[0:6]
                start_color = "#" + selected
                start_color_osx = selected
                start_color_win = self.__hexstr_to_bgr(selected)

        if sublime.platform() == 'windows':

            s = sublime.load_settings("ColorPicker.sublime-settings")
            custom_colors = s.get("custom_colors", ['0'] * 16)

            if len(custom_colors) < 16:
                custom_colors = ['0'] * 16
                s.set('custom_colors', custom_colors)

            cc = CHOOSECOLOR()
            ctypes.memset(ctypes.byref(cc), 0, ctypes.sizeof(cc))
            cc.lStructSize = ctypes.sizeof(cc)
            cc.hwndOwner = self.view.window().hwnd()
            cc.Flags = CC_SOLIDCOLOR | CC_FULLOPEN | CC_RGBINIT
            cc.rgbResult = c_uint32(start_color_win)
            cc.lpCustColors = self.__to_custom_color_array(custom_colors)

            if ChooseColorW(ctypes.byref(cc)):
                color = self.__bgr_to_hexstr(cc.rgbResult)
            else:
                color = None

        elif sublime.platform() == 'osx':
            location = os.path.join(sublime.packages_path(), 'Rainmeter',
                                    'lib', 'osx_colorpicker')
            args = [location]

            if not os.access(location, os.X_OK):
                os.chmod(location, 0755)

            if start_color_osx:
                args.append('-startColor')
                args.append(start_color_osx)

        else:
            location = os.path.join(sublime.packages_path(), 'Rainmeter',
                                    'lib', 'linux_colorpicker.py')
            args = [location]

            if not os.access(location, os.X_OK):
                os.chmod(location, 0755)

            if start_color:
                args.append(start_color)

        if sublime.platform() == 'osx' or sublime.platform() == 'linux':
            proc = subprocess.Popen(args, stdout=subprocess.PIPE)
            color = proc.communicate()[0].strip()

        if color:
            # replace all regions with color
            for region in sel:
                word = self.view.word(region)
                # if the selected word is a valid color, replace it
                if self.__is_valid_hex_color(self.view.substr(word)):
                    if len(self.view.substr(word)) > 6:
                        word = sublime.Region(word.a, word.a + 6)
                    # include '#' if present
                    self.view.replace(edit, word, color)
                #if the selected region starts with a #, keep it
                elif self.view.substr(region).startswith('#'):
                    reduced = sublime.Region(region.begin() + 1, region.end())
                    if self.__is_valid_hex_color(self.view.substr(reduced)):
                        if len(reduced) > 6:
                            reduced = sublime.Region(reduced.a, reduced.a + 6)
                        self.view.replace(edit, reduced, color)
                    else:
                        self.view.replace(edit, region, '#' + color)
                # otherwise just replace the selected region
                else:
                    self.view.replace(edit, region, color)
def sublime_format_path(pth):
    """Format path for Sublime internally."""
    m = re.match(r"^([A-Za-z]{1}):(?:/|\\)(.*)", pth)
    if sublime.platform() == "windows" and m is not None:
        pth = m.group(1) + "/" + m.group(2)
    return pth.replace("\\", "/")
def _get_texpath(view):
    texpath = get_setting(sublime.platform(), {}, view).get('texpath')
    return expand_vars(texpath) if texpath is not None else None
Beispiel #56
0
def IsWindows():
    return sublime.platform() == 'windows'
Beispiel #57
0
 def get_cd_cmd(self, path):
     if sublime.platform() == "windows":
         return "cd /d " + path
     else:
         return "cd " + path
Beispiel #58
0
import os
import sys
import re

from .utils import UTSetting
from .utils import OutputPanel
from .utils import JsonFile
from .utils import reload_package
from .utils import ProgressBar

import sublime

version = sublime.version()
platform = sublime.platform()


class UnitTestingMixin(object):

    @property
    def current_package_name(self):
        """Return back the name of the current package."""
        window = sublime.active_window()
        view = window.active_view()
        spp = os.path.realpath(sublime.packages_path())
        if view and view.file_name():
            file_path = os.path.realpath(view.file_name())
            if file_path.startswith(spp):
                return file_path[len(spp):].split(os.sep)[1]

        folders = sublime.active_window().folders()
        if folders and len(folders) > 0:
Beispiel #59
0
 def run_in_os_termial(self, cmd_list):
     if sublime.platform() == "windows":
         cmd_list.append("pause")
     cmd_str = self._get_cmd_str(cmd_list)
     thread = threading.Thread(target=os.system, args=(cmd_str,))
     thread.start()
Beispiel #60
0
def is_windows():
    """Returns `True` if ST is running on Windows.
    """
    return sublime.platform() == 'windows'